Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import tempfile, os, io | |
| from translator import Translator | |
| from docx_translation import translate_document | |
| fanar_api_key = os.getenv("FANAR_API_KEY") | |
| if not fanar_api_key: | |
| raise RuntimeError("FANAR_API_KEY is not set") | |
| translator = Translator(api_key=fanar_api_key, langpair="en-ar", model="Fanar-Shaheen-MT-1") | |
| def _normalize_to_docx_path(obj) -> str: | |
| if isinstance(obj, (bytes, bytearray)): | |
| tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".docx") | |
| tmp.write(obj); tmp.close() | |
| return tmp.name | |
| if isinstance(obj, str) and os.path.exists(obj): | |
| return obj | |
| try: | |
| tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".docx") | |
| obj.save(tmp.name) # python-docx Document-like | |
| tmp.close() | |
| return tmp.name | |
| except Exception as e: | |
| raise RuntimeError("translate_document must return bytes, a path, or a python-docx Document.") from e | |
| def run_translation(file_path): | |
| if not file_path: | |
| raise gr.Error("Please upload a DOCX file first.") | |
| translated = translate_document( | |
| docx_path=file_path, # if your function wants bytes, switch to File(type="bytes") and wrap with io.BytesIO | |
| translator=translator, | |
| font_mapping=None, | |
| use_cache=False, | |
| ) | |
| out_path = _normalize_to_docx_path(translated) | |
| return out_path # gr.File accepts a path | |
| with gr.Blocks(title="Document Translator") as demo: | |
| gr.Markdown("# Fanar Document Translation") | |
| gr.Markdown("## Upload a DOCX and download the translated version") | |
| with gr.Row(): | |
| doc_input = gr.File(label="Upload DOCX file", file_types=[".docx"], type="filepath") | |
| with gr.Row(): | |
| translate_btn = gr.Button("Translate") | |
| with gr.Row(): | |
| out_file = gr.File(label="Translated DOCX") | |
| translate_btn.click(run_translation, doc_input, out_file, show_api=False) | |
| demo.launch() | |