Alhdrawi commited on
Commit
75e87de
·
verified ·
1 Parent(s): 922cf2f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -0
app.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import subprocess
3
+ import os
4
+ import tempfile
5
+ import shutil
6
+
7
+ def convert_file(file, to_format):
8
+ if file is None:
9
+ return None
10
+
11
+ # احفظ الملف مؤقتاً
12
+ input_path = file.name
13
+ # عين اسم ملف الإخراج بناءً على التنسيق المطلوب
14
+ output_ext = to_format
15
+ base_name = os.path.splitext(os.path.basename(input_path))[0]
16
+ tmp_dir = tempfile.mkdtemp()
17
+ output_path = os.path.join(tmp_dir, f"{base_name}.{output_ext}")
18
+
19
+ try:
20
+ # أمر LibreOffice للتحويل بصمت (headless)
21
+ subprocess.run([
22
+ "libreoffice",
23
+ "--headless",
24
+ "--convert-to",
25
+ output_ext,
26
+ "--outdir",
27
+ tmp_dir,
28
+ input_path
29
+ ], check=True)
30
+
31
+ # أرجع الملف الناتج
32
+ return output_path
33
+
34
+ except subprocess.CalledProcessError as e:
35
+ return f"Error: {e}"
36
+ finally:
37
+ # احذف الملف المدخل مؤقتاً بعد التحويل
38
+ try:
39
+ os.remove(input_path)
40
+ except Exception:
41
+ pass
42
+
43
+ def word_to_pdf(file):
44
+ return convert_file(file, "pdf")
45
+
46
+ def pdf_to_word(file):
47
+ return convert_file(file, "docx")
48
+
49
+ with gr.Blocks() as demo:
50
+ gr.Markdown("# محول Word ⇄ PDF باستخدام LibreOffice")
51
+
52
+ with gr.Tab("Word → PDF"):
53
+ word_input = gr.File(label="ارفع ملف Word (.docx)")
54
+ word_output = gr.File(label="تحميل PDF الناتج")
55
+ word_btn = gr.Button("حوّل")
56
+ word_btn.click(fn=word_to_pdf, inputs=word_input, outputs=word_output)
57
+
58
+ with gr.Tab("PDF → Word"):
59
+ pdf_input = gr.File(label="ارفع ملف PDF (.pdf)")
60
+ pdf_output = gr.File(label="تحميل Word الناتج")
61
+ pdf_btn = gr.Button("حوّل")
62
+ pdf_btn.click(fn=pdf_to_word, inputs=pdf_input, outputs=pdf_output)
63
+
64
+ demo.launch()