import gradio as gr import subprocess import os import tempfile import shutil def convert_file(file, to_format): if file is None: return None # احفظ الملف مؤقتاً input_path = file.name # عين اسم ملف الإخراج بناءً على التنسيق المطلوب output_ext = to_format base_name = os.path.splitext(os.path.basename(input_path))[0] tmp_dir = tempfile.mkdtemp() output_path = os.path.join(tmp_dir, f"{base_name}.{output_ext}") try: # أمر LibreOffice للتحويل بصمت (headless) subprocess.run([ "libreoffice", "--headless", "--convert-to", output_ext, "--outdir", tmp_dir, input_path ], check=True) # أرجع الملف الناتج return output_path except subprocess.CalledProcessError as e: return f"Error: {e}" finally: # احذف الملف المدخل مؤقتاً بعد التحويل try: os.remove(input_path) except Exception: pass def word_to_pdf(file): return convert_file(file, "pdf") def pdf_to_word(file): return convert_file(file, "docx") with gr.Blocks() as demo: gr.Markdown("# محول Word ⇄ PDF باستخدام LibreOffice") with gr.Tab("Word → PDF"): word_input = gr.File(label="ارفع ملف Word (.docx)") word_output = gr.File(label="تحميل PDF الناتج") word_btn = gr.Button("حوّل") word_btn.click(fn=word_to_pdf, inputs=word_input, outputs=word_output) with gr.Tab("PDF → Word"): pdf_input = gr.File(label="ارفع ملف PDF (.pdf)") pdf_output = gr.File(label="تحميل Word الناتج") pdf_btn = gr.Button("حوّل") pdf_btn.click(fn=pdf_to_word, inputs=pdf_input, outputs=pdf_output) demo.launch()