File size: 1,952 Bytes
75e87de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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()