async
This commit is contained in:
+40
-26
@@ -5,12 +5,17 @@ import pyperclip
|
||||
from typing import Dict, Any, List, Optional, Callable
|
||||
from pathlib import Path
|
||||
import re
|
||||
import googletrans
|
||||
import asyncio
|
||||
|
||||
console = Console()
|
||||
|
||||
# Create the main grafana subcommand
|
||||
grafana_app = typer.Typer()
|
||||
|
||||
# Global translator instance
|
||||
translator = googletrans.Translator()
|
||||
|
||||
def safe_get(data: Dict[str, Any], key: str, default: Any = None) -> Any:
|
||||
"""Safely get a value from a dictionary."""
|
||||
return data.get(key, default)
|
||||
@@ -23,8 +28,8 @@ def contains_chinese(text: str) -> bool:
|
||||
chinese_pattern = re.compile(r'[\u4e00-\u9fff\u3400-\u4dbf\u20000-\u2a6df\u2a700-\u2b73f\u2b740-\u2b81f\u2b820-\u2ceaf\uf900-\ufaff\u3300-\u33ff\ufe30-\ufe4f\uf900-\ufaff\u2f800-\u2fa1f]')
|
||||
return bool(chinese_pattern.search(text))
|
||||
|
||||
def mutate_chinese_titles(data: Dict[str, Any]) -> None:
|
||||
"""Recursively mutate titles containing Chinese characters."""
|
||||
async def mutate_chinese_titles(data: Dict[str, Any]) -> None:
|
||||
"""Recursively translate Chinese titles to English."""
|
||||
if not isinstance(data, dict):
|
||||
return
|
||||
|
||||
@@ -33,13 +38,19 @@ def mutate_chinese_titles(data: Dict[str, Any]) -> None:
|
||||
|
||||
for key, value in data.items():
|
||||
if key in title_keys and isinstance(value, str) and contains_chinese(value):
|
||||
data[key] = "please_translate_me"
|
||||
try:
|
||||
# Translate Chinese text to English
|
||||
translation = await translator.translate(value, dest='en')
|
||||
data[key] = translation.text
|
||||
console.print(f"[dim]Translated '{value}' → '{translation.text}'[/dim]")
|
||||
except Exception as e:
|
||||
console.print(f"[yellow]Warning: Failed to translate '{value}': {e}[/yellow]")
|
||||
elif isinstance(value, dict):
|
||||
mutate_chinese_titles(value)
|
||||
await mutate_chinese_titles(value)
|
||||
elif isinstance(value, list):
|
||||
for item in value:
|
||||
if isinstance(item, dict):
|
||||
mutate_chinese_titles(item)
|
||||
await mutate_chinese_titles(item)
|
||||
|
||||
def mutate_panel(panel: Dict[str, Any]) -> None:
|
||||
"""Mutate a single panel by setting repeat and repeatDirection fields."""
|
||||
@@ -88,9 +99,9 @@ def mutate_grafana_json_repeat(data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
|
||||
return mutated_data
|
||||
|
||||
def mutate_grafana_json_chinese(data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
async def mutate_grafana_json_chinese(data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
Mutate Grafana JSON by replacing Chinese text in titles with 'please_translate_me'.
|
||||
Mutate Grafana JSON by translating Chinese text in titles to English.
|
||||
|
||||
Args:
|
||||
data: The Grafana dashboard JSON data
|
||||
@@ -101,12 +112,12 @@ def mutate_grafana_json_chinese(data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
# Make a copy to avoid mutating the original
|
||||
mutated_data = json.loads(json.dumps(data))
|
||||
|
||||
# Apply Chinese title mutation recursively
|
||||
mutate_chinese_titles(mutated_data)
|
||||
# Apply Chinese title translation recursively
|
||||
await mutate_chinese_titles(mutated_data)
|
||||
|
||||
return mutated_data
|
||||
|
||||
def mutate_grafana_json_all(data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
async def mutate_grafana_json_all(data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
Apply both mutations: repeat fields and Chinese title translation.
|
||||
|
||||
@@ -121,12 +132,12 @@ def mutate_grafana_json_all(data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
console.print("[green]✓ Applied repeat field mutation[/green]")
|
||||
|
||||
# Then apply Chinese title translation
|
||||
mutated_data = mutate_grafana_json_chinese(mutated_data)
|
||||
mutated_data = await mutate_grafana_json_chinese(mutated_data)
|
||||
console.print("[green]✓ Applied Chinese title translation[/green]")
|
||||
|
||||
return mutated_data
|
||||
|
||||
def process_grafana_json(
|
||||
async def process_grafana_json(
|
||||
mutation_func: Callable[[Dict[str, Any]], Dict[str, Any]],
|
||||
input_file: Optional[Path],
|
||||
output_file: Optional[Path],
|
||||
@@ -173,7 +184,10 @@ def process_grafana_json(
|
||||
|
||||
# Apply mutation
|
||||
try:
|
||||
mutated_data = mutation_func(data)
|
||||
if asyncio.iscoroutinefunction(mutation_func):
|
||||
mutated_data = await mutation_func(data)
|
||||
else:
|
||||
mutated_data = mutation_func(data)
|
||||
console.print(f"[green]{success_message}[/green]")
|
||||
except Exception as e:
|
||||
console.print(f"[red]Error mutating JSON: {e}[/red]")
|
||||
@@ -213,15 +227,15 @@ def mutate_dashboard(
|
||||
- Set maxPerRow to 12
|
||||
- Remove repeat field from row-type panels
|
||||
"""
|
||||
process_grafana_json(
|
||||
asyncio.run(process_grafana_json(
|
||||
mutation_func=mutate_grafana_json_repeat,
|
||||
input_file=input_file,
|
||||
output_file=output_file,
|
||||
process_message="Processing Grafana dashboard JSON...",
|
||||
success_message="Successfully mutated Grafana JSON!"
|
||||
)
|
||||
))
|
||||
|
||||
@grafana_app.command("translate", short_help="Replace Chinese text in titles with 'please_translate_me'.")
|
||||
@grafana_app.command("translate", short_help="Translate Chinese text in titles to English.")
|
||||
def translate_dashboard(
|
||||
input_file: Optional[Path] = typer.Option(
|
||||
None, "--input-file", "-i", help="Input JSON file path. If not provided, reads from clipboard."
|
||||
@@ -231,19 +245,19 @@ def translate_dashboard(
|
||||
)
|
||||
):
|
||||
"""
|
||||
Replace Chinese text in titles with 'please_translate_me'.
|
||||
Translate Chinese text in titles to English using Google Translate.
|
||||
|
||||
This command processes Grafana dashboard JSON and replaces any Chinese characters
|
||||
This command processes Grafana dashboard JSON and translates any Chinese characters
|
||||
in title-related fields (title, name, description, tooltip, legendFormat, text)
|
||||
with the placeholder text 'please_translate_me'.
|
||||
to English using Google Translate.
|
||||
"""
|
||||
process_grafana_json(
|
||||
asyncio.run(process_grafana_json(
|
||||
mutation_func=mutate_grafana_json_chinese,
|
||||
input_file=input_file,
|
||||
output_file=output_file,
|
||||
process_message="Processing Grafana dashboard JSON for Chinese title translation...",
|
||||
success_message="Successfully replaced Chinese text in titles!"
|
||||
)
|
||||
success_message="Successfully translated Chinese text in titles!"
|
||||
))
|
||||
|
||||
@grafana_app.command("mutate-all", short_help="Apply both repeat field mutation and Chinese title translation.")
|
||||
def mutate_all_dashboard(
|
||||
@@ -255,16 +269,16 @@ def mutate_all_dashboard(
|
||||
)
|
||||
):
|
||||
"""
|
||||
Apply both mutations: set repeat fields and replace Chinese text in titles.
|
||||
Apply both mutations: set repeat fields and translate Chinese text in titles.
|
||||
|
||||
This command processes Grafana dashboard JSON and applies both:
|
||||
1. Repeat field mutation (repeat="instance", repeatDirection="h", maxPerRow=12)
|
||||
2. Chinese title translation (replaces Chinese characters with 'please_translate_me')
|
||||
2. Chinese title translation (translates Chinese characters to English using Google Translate)
|
||||
"""
|
||||
process_grafana_json(
|
||||
asyncio.run(process_grafana_json(
|
||||
mutation_func=mutate_grafana_json_all,
|
||||
input_file=input_file,
|
||||
output_file=output_file,
|
||||
process_message="Processing Grafana dashboard JSON with all mutations...",
|
||||
success_message="Successfully applied all mutations!"
|
||||
)
|
||||
))
|
||||
Reference in New Issue
Block a user