Spaces:
Sleeping
Sleeping
Download app.py from leedanon/smart-translator: direct link, hf CLI and curl.
- Browser
- Download file 2.09 kB
-
https://huggingface.co/spaces/leedanon/smart-translator/resolve/main/app.py
- Command line
-
hf download hf://spaces/leedanon/smart-translator/app.py
-
curl -L -o app.py https://huggingface.co/spaces/leedanon/smart-translator/resolve/main/app.py
2.09 kB
| import gradio as gr | |
| import json | |
| from langdetect import detect | |
| from transformers import pipeline, MBart50TokenizerFast, MBartForConditionalGeneration | |
| with open("lang_model_map.json", "r", encoding="utf-8") as f: | |
| LANG_MODEL_MAP = json.load(f) | |
| MBART_LANG_CODES = { | |
| "he": "he_IL", | |
| "fr": "fr_XX", | |
| "es": "es_XX", | |
| "de": "de_DE" | |
| } | |
| def detect_language(text): | |
| try: | |
| lang = detect(text) | |
| if "砖诇讜诐" in text or "注讜诇诐" in text: | |
| return "he" | |
| return lang | |
| except: | |
| return "unknown" | |
| def translate_text(text, src_lang): | |
| if src_lang == "en": | |
| return text | |
| model_name = LANG_MODEL_MAP.get(src_lang) | |
| if model_name == "facebook/mbart-large-50-many-to-one-mmt": | |
| tokenizer = MBart50TokenizerFast.from_pretrained(model_name) | |
| model = MBartForConditionalGeneration.from_pretrained(model_name) | |
| tokenizer.src_lang = MBART_LANG_CODES.get(src_lang, "he_IL") | |
| encoded = tokenizer(text, return_tensors="pt") | |
| generated_tokens = model.generate( | |
| **encoded, | |
| forced_bos_token_id=tokenizer.lang_code_to_id["en_XX"] | |
| ) | |
| return tokenizer.decode(generated_tokens[0], skip_special_tokens=True) | |
| try: | |
| translator = pipeline("translation", model=model_name) | |
| result = translator(text, max_length=1000)[0]['translation_text'] | |
| return result | |
| except Exception as e: | |
| return f"砖讙讬讗讛 讘转专讙讜诐: {str(e)}" | |
| def translate_interface(text): | |
| lang = detect_language(text) | |
| translation = translate_text(text, lang) | |
| return text, lang, translation | |
| iface = gr.Interface( | |
| fn=translate_interface, | |
| inputs=gr.Textbox(label="讛讻谞住 讟拽住讟 诇转专讙讜诐"), | |
| outputs=[ | |
| gr.Textbox(label="讟拽住讟 诪拽讜专讬"), | |
| gr.Textbox(label="砖驻讛 砖讝讜讛转讛"), | |
| gr.Textbox(label="转专讙讜诐 诇讗谞讙诇讬转") | |
| ], | |
| title="馃 诪转专讙诐 讞讻诐", | |
| description="讛讻谞住 讟拽住讟 讘砖驻讛 讻诇砖讛讬, 讜讛诪注专讻转 转讝讛讛 讗转 讛砖驻讛 讜转专讙诐 诇讗谞讙诇讬转." | |
| ) | |
| iface.launch() |