Spaces:
Runtime error

Bombog944 commited on
Commit
2371cae
·
verified ·
1 Parent(s): 02a5e1e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +222 -132
app.py CHANGED
@@ -1,137 +1,227 @@
1
- import os
2
- os.environ["TOKENIZERS_PARALLELISM"] = "false"
3
- from io import BytesIO
4
- import tempfile
5
  import gradio as gr
6
- from deep_translator import GoogleTranslator
7
- import fitz # pymupdf
8
- from reportlab.pdfgen import canvas
9
- from reportlab.lib.pagesizes import A4
10
- from reportlab.lib.utils import ImageReader
11
- from docx import Document
12
- from pptx import Presentation
13
-
14
- translator = GoogleTranslator(source="auto", target="ar")
15
-
16
- def translate_chunked(text):
17
- """يقسم النص لقطع صغيرة لتفادي حدود API"""
18
- max_len = 3800
19
- parts = [text[i:i + max_len] for i in range(0, len(text), max_len)]
20
- out_parts = []
21
- for p in parts:
22
- try:
23
- out_parts.append(translator.translate(p))
24
- except Exception as e:
25
- out_parts.append(f"[خطأ في الترجمة: {e}]")
26
- return " ".join(out_parts)
27
-
28
- def translate_pdf_bytes(pdf_bytes):
29
- doc = fitz.open(stream=pdf_bytes, filetype="pdf")
30
- temp_out = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
31
- c = canvas.Canvas(temp_out.name, pagesize=A4)
32
-
33
- for page_index, page in enumerate(doc):
34
- blocks = page.get_text("blocks")
35
- try:
36
- images = page.get_images(full=True)
37
- y_img = 500
38
- for img in images:
39
- xref = img[0]
40
- try:
41
- base_image = doc.extract_image(xref)
42
- image_bytes = base_image["image"]
43
- image = ImageReader(BytesIO(image_bytes))
44
- c.drawImage(image, 50, y_img, width=200, height=150)
45
- y_img -= 160
46
- except Exception:
47
- pass
48
- except Exception:
49
- pass
50
-
51
- lines = []
52
- for b in blocks:
53
- text = b[4]
54
- for ln in text.split("\n"):
55
- if ln.strip():
56
- lines.append(ln.strip())
57
-
58
- y = 700
59
- for ln in lines:
60
- if y < 100:
61
- c.showPage()
62
- y = 750
63
- c.setFont("Helvetica", 10)
64
- c.drawString(50, y, ln)
65
- y -= 14
66
- translated = translate_chunked(ln)
67
- if translated:
68
- c.setFont("Helvetica-Oblique", 10)
69
- c.setFillColorRGB(0.1, 0.5, 0.1)
70
- c.drawString(60, y, translated)
71
- c.setFillColorRGB(0, 0, 0)
72
- y -= 18
73
- c.showPage()
74
-
75
- c.save()
76
  doc.close()
77
- return temp_out.name
78
-
79
- def translate_docx(file_path):
80
- doc = Document(file_path)
81
- for para in doc.paragraphs:
82
- if para.text.strip():
83
- translation = translate_chunked(para.text)
84
- para.add_run("\n" + translation).italic = True
85
- out_path = tempfile.NamedTemporaryFile(delete=False, suffix=".docx").name
86
- doc.save(out_path)
87
- return out_path
88
-
89
- def translate_pptx(file_path):
90
- prs = Presentation(file_path)
91
- for slide in prs.slides:
92
- for shape in slide.shapes:
93
- if hasattr(shape, "text"):
94
- original = shape.text
95
- if original.strip():
96
- translated = translate_chunked(original)
97
- shape.text = f"{original}\n{translated}"
98
- out_path = tempfile.NamedTemporaryFile(delete=False, suffix=".pptx").name
99
- prs.save(out_path)
100
- return out_path
101
-
102
- def process_file(file_obj):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  try:
104
- # ✅ حل مشكلة NamedString (Gradio upload)
105
- file_path = file_obj.name if hasattr(file_obj, "name") else None
106
- if not file_path:
107
- raise ValueError("لم أتمكن من قراءة الملف المرفوع.")
108
-
109
- ext = os.path.splitext(file_path)[1].lower()
110
- if ext == ".pdf":
111
- pdf_bytes = open(file_path, "rb").read()
112
- out_path = translate_pdf_bytes(pdf_bytes)
113
- elif ext == ".docx":
114
- out_path = translate_docx(file_path)
115
- elif ext == ".pptx":
116
- out_path = translate_pptx(file_path)
117
- else:
118
- return f"الامتداد {ext} غير مدعوم حاليًا. استخدم PDF أو DOCX أو PPTX."
119
-
120
- return open(out_path, "rb")
121
- except Exception as e:
122
- return f"حدث خطأ أثناء المعالجة: {e}"
123
-
124
- title = "🧠 File Translator — يضيف الترجمة تحت كل سطر"
125
- desc = "ارفع ملف PDF أو Word أو PowerPoint. الترجمة تظهر تحت كل سطر بنفس التنسيق والصور. بدون فيزا وبدون تعقيد."
126
-
127
- demo = gr.Interface(
128
- fn=process_file,
129
- inputs=gr.File(label="📄 ارفع الملف (PDF / DOCX / PPTX)"),
130
- outputs=gr.File(label="📥 الملف المترجم جاهز للتحميل"),
131
- title=title,
132
- description=desc,
133
- flagging_mode="never" # ✅ بدل allow_flagging القديم
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  )
135
 
136
- if __name__ == "__main__":
137
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
1
+ # app.py
 
 
 
2
  import gradio as gr
3
+ import fitz # PyMuPDF for PDF processing
4
+ from PIL import Image, ImageDraw, ImageFont
5
+ import io
6
+ from transformers import pipeline
7
+ from deep_translator import GoogleTranslator # يمكن استبدالها بـ Hugging Face translation model
8
+
9
+ # -------------------------------------------------------------
10
+ # 1. إعداد نماذج Hugging Face / أدوات الترجمة
11
+ # -------------------------------------------------------------
12
+
13
+ # نموذج OCR من Hugging Face (مثال، قد لا يعطي إحداثيات دقيقة لكل سطر)
14
+ # للأسف، معظم نماذج OCR الجاهزة في Hugging Face لا توفر إحداثيات SBOX دقيقة لكل "سطر"
15
+ # ستحتاج لنموذج متخصص مثل LayoutLMv3 أو Tesseract (خارجي)
16
+ # ocr_pipeline = pipeline("ocr", model="microsoft/trocr-base-handwritten") # مثال فقط، لا يعطي إحداثيات
17
+
18
+ # سنستخدم حل OCR بسيط يعتمد على PyMuPDF (أو Tesseract إذا تم تثبيته كخارجية)
19
+ # للترجمة، نستخدم deep_translator كخيار سهل
20
+ translator = GoogleTranslator(source='auto', target='ar')
21
+
22
+ # -------------------------------------------------------------
23
+ # 2. وظائف معالجة الملفات والصور
24
+ # -------------------------------------------------------------
25
+
26
+ def pdf_to_image_bytes(pdf_file):
27
+ """يحول صفحات PDF إلى قائمة من بايتات الصور."""
28
+ doc = fitz.open(stream=pdf_file.read(), filetype="pdf")
29
+ image_bytes_list = []
30
+ for i, page in enumerate(doc):
31
+ pix = page.get_pixmap(dpi=200) # دقة 200 كافية للويب
32
+ img_byte_arr = io.BytesIO()
33
+ Image.frombytes("RGB", [pix.width, pix.height], pix.samples).save(img_byte_arr, format="PNG")
34
+ image_bytes_list.append(img_byte_arr.getvalue())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  doc.close()
36
+ return image_bytes_list
37
+
38
+ def process_page_image(image_bytes):
39
+ """
40
+ يستخرج النص من صورة الصفحة، يترجمه، ويضيفه كتراكب.
41
+ ⚠️ التحدي: OCR دقيق مع إحداثيات لكل سطر، والكتابة العربية الصحيحة.
42
+ """
43
+ img = Image.open(io.BytesIO(image_bytes)).convert("RGB")
44
+ draw = ImageDraw.Draw(img)
45
+
46
+ # اختيار خط عربي يدعم RTL (يجب أن يكون موجوداً في بيئة Hugging Face Space)
47
+ # مثال: NotoSansArabic-Regular.ttf أو Arial.ttf
48
+ try:
49
+ # تأكد من وجود هذا الخط في مجلد fonts داخل الـ Space الخاص بك
50
+ font_path = "/usr/share/fonts/truetype/noto/NotoSansArabic-Regular.ttf"
51
+ # أو أي خط عربي آخر يمكنك إضافته لبيئة Docker في Hugging Face Space
52
+ font = ImageFont.truetype(font_path, size=24)
53
+ except IOError:
54
+ font = ImageFont.load_default()
55
+ print("Warning: NotoSansArabic font not found, using default. Arabic text might be rendered incorrectly.")
56
+
57
+ # ------ هنا تأتي الخطوة المعقدة جداً: OCR مع إحداثيات السطر --------
58
+ # PyMuPDF يمكنه استخراج النص والإحداثيات ولكن ليس دقيقًا لكل "سطر" ككتلة واحدة
59
+ # Tesseract (تتطلب تثبيت خارجي) أفضل لإخراج الإحداثيات
60
+ # نماذج Hugging Face مثل DocTr (DocTransformer) قد تساعد ولكنها تتطلب استدعاء API خاص
61
+
62
+ # حالياً، سنستخدم حلاً مبسطاً: استخراج كل النص، ثم تقسيمه لسطور وترجمته
63
+ # هذا لن يحافظ على إحداثيات السطر الأصلي بدقة، ولكن سيضيف الترجمة في مكان جديد
64
+
65
+ # استخراج النص باستخدام PyMuPDF (بما أنه من PDF)
66
+ # هذا الكود هو تقديري فقط ولا يستخرج إحداثيات كل سطر على الصورة مباشرة
67
+ # للحصول على إحداثيات دقيقة، ستحتاج إلى OCR أقوى!
68
+ dummy_text_lines = ["This is a sample line of text.", "Another line for translation."]
69
+ # ^^^^^^^^^^ في الواقع ستحتاج لاستبدال هذا بـ OCR حقيقي من الصورة ^^^^^^^^^^
70
+
71
+ # محاكاة OCR بسيط (للتوضيح فقط، لن يعطي إحداثيات دقيقة)
72
+ text_data = []
73
+ # هنا يجب عليك استخدام OCR حقيقي على الصورة واستخراج النص مع الـ bounding boxes لكل سطر
74
+ # example_text_bbox = {"text": "Hello World", "bbox": (50, 50, 200, 70)}
75
+
76
+ # بما أننا لا نستطيع استخراج إحداثيات دقيقة من Hugging Face OCR مباشرة لكل سطر بحد ذاته
77
+ # سنقوم بإنشاء منطقة جديدة لإضافة الترجمة
78
+
79
+ y_offset = 50 # بداية إضافة الترجمات
80
+ line_height = 30 # ارتفاع تقديري للسطر
81
+
82
+ # هذا الجزء يحتاج إلى تحسين كبير جداً ليعمل كما تصف
83
+ # يجب أن يكون لديك list of {"text": original_text, "bbox": (x1,y1,x2,y2)}
84
+
85
+ # مثال توضيحي (لن يعمل بدقة)
86
+ # for i, line in enumerate(dummy_text_lines):
87
+ # translated_line = translator.translate(line)
88
+ # # تحديد مكان عشوائي لإضافة الترجمة (غير دقيق)
89
+ # draw.text((50, y_offset + (i * 2 * line_height)), translated_line, fill=(0, 0, 0), font=font)
90
+
91
+
92
+ # حل أفضل (ولكن ليس مثاليًا بدون OCR دقيق بالإحداثيات):
93
+ # استخدام OCR من Hugging Face للحصول على كل النصوص ككتلة
94
+ # ثم ترجمتها ووضعها في جزء من الصورة
95
+
96
+ # This part would require a robust OCR model like LayoutLMv3 with custom parsing
97
+ # or integrating Tesseract via an external process in the Hugging Face Space setup.
98
+ # For now, let's just attempt to get text and translate without perfect overlay.
99
+
100
+ # -----------------------------------------------------------------
101
+ # محاولة استخدام PyTesseract (يتطلب تثبيت Tesseract-OCR في بيئة Docker)
102
+ # -----------------------------------------------------------------
103
  try:
104
+ import pytesseract
105
+ # تعيين مسار Tesseract إذا لم يكن في PATH (قد يكون مختلفًا في Hugging Face Space)
106
+ # pytesseract.pytesseract.tesseract_cmd = '/usr/bin/tesseract' # أو حسب المسار الصحيح
107
+
108
+ # استخراج البيانات بما فيها الإحداثيات
109
+ data = pytesseract.image_to_data(img, output_type=pytesseract.Output.DICT, lang='eng') # يمكن إضافة 'ara' للتعرف على العربي أيضًا
110
+
111
+ # تجميع السطور
112
+ lines_info = []
113
+ current_line = []
114
+ current_bbox = [float('inf'), float('inf'), float('-inf'), float('-inf')]
115
+
116
+ for i in range(len(data['text'])):
117
+ text = data['text'][i].strip()
118
+ conf = int(data['conf'][i])
119
+ if conf > 60 and text: # Filter out low confidence and empty text
120
+ x, y, w, h = data['left'][i], data['top'][i], data['width'][i], data['height'][i]
121
+ word_bbox = (x, y, x + w, y + h)
122
+
123
+ # Assuming words are grouped by line_num for simplicity
124
+ if not current_line or data['line_num'][i] == data['line_num'][i-1] : # if same line or first word
125
+ current_line.append(text)
126
+ current_bbox[0] = min(current_bbox[0], word_bbox[0])
127
+ current_bbox[1] = min(current_bbox[1], word_bbox[1])
128
+ current_bbox[2] = max(current_bbox[2], word_bbox[2])
129
+ current_bbox[3] = max(current_bbox[3], word_bbox[3])
130
+ else: # New line
131
+ if current_line:
132
+ lines_info.append({"original": " ".join(current_line), "bbox": tuple(current_bbox)})
133
+ current_line = [text]
134
+ current_bbox = list(word_bbox)
135
+
136
+ # Add the last line
137
+ if current_line:
138
+ lines_info.append({"original": " ".join(current_line), "bbox": tuple(current_bbox)})
139
+
140
+
141
+ # الآن نقوم بالترجمة والإضافة
142
+ translated_img = img.copy()
143
+ draw_translated = ImageDraw.Draw(translated_img)
144
+
145
+ y_offset_for_translation = 25 # مسافة بين السطر الأصلي والترجمة
146
+
147
+ for line_data in lines_info:
148
+ original_text = line_data['original']
149
+ x1, y1, x2, y2 = line_data['bbox']
150
+
151
+ if original_text: # تأكد أن هناك نصًا لترجمته
152
+ translated_text = translator.translate(original_text)
153
+
154
+ # لحل مشكلة RTL، قد تحتاج مكتبات مثل arabic_reshaper و bidi
155
+ # from arabic_reshaper import ArabicReshaper
156
+ # from bidi.algorithm import get_display
157
+ # reshaper = ArabicReshaper()
158
+ # translated_text_reshaped = reshaper.reshape(translated_text)
159
+ # translated_text_display = get_display(translated_text_reshaped)
160
+ # draw_translated.text((x1, y2 + y_offset_for_translation), translated_text_display, fill=(0, 0, 0), font=font)
161
+
162
+ draw_translated.text((x1, y2 + y_offset_for_translation), translated_text, fill=(0, 0, 0), font=font) # بدون RTL
163
+
164
+ img = translated_img # نستخدم الصورة المترجمة
165
+
166
+ except ImportError:
167
+ print("Warning: pytesseract not found or Tesseract-OCR not installed. Cannot perform advanced OCR.")
168
+ # fallback if Tesseract is not available
169
+ draw.text((50, img.height - 100), "Translation unavailable without Tesseract-OCR.", fill=(255, 0, 0), font=font)
170
+
171
+
172
+ # تحويل الصورة إلى بايتات لإرجاعها في Gradio
173
+ img_byte_arr = io.BytesIO()
174
+ img.save(img_byte_arr, format="PNG")
175
+ return img_byte_arr.getvalue()
176
+
177
+
178
+ def process_document(file):
179
+ """الواجهة الرئيسية التي تستقبل الملف."""
180
+ if file is None:
181
+ return "Please upload a document."
182
+
183
+ file_path = file.name # Gradio يمرر File object
184
+
185
+ # 1. تحويل الملف إلى صور (نركز على PDF هنا)
186
+ if file_path.lower().endswith(".pdf"):
187
+ image_bytes_list = pdf_to_image_bytes(file)
188
+ else:
189
+ # هنا ستكون بحاجة لكود تحويل DOCX/PPTX إلى PDF أولاً
190
+ # وهو تحدي كبير في بيئة Hugging Face Space بدون أدوات خارجية
191
+ return "Only PDF files are supported directly in this demo. DOCX/PPTX conversion is complex."
192
+
193
+ if not image_bytes_list:
194
+ return "Failed to convert document to images."
195
+
196
+ processed_images_bytes = []
197
+ for img_bytes in image_bytes_list:
198
+ processed_images_bytes.append(process_page_image(img_bytes))
199
+
200
+ # 2. تجميع الصور المترجمة في ملف PDF واحد جديد (اختياري)
201
+ # يمكن إرجاع قائمة الصور مباشرة ليتم عرضها في Gradio
202
+
203
+ # إذا أردت إرجاع PDF، ستحتاج مكتبة لإنشاء PDF من صور
204
+ # مثلاً reportlab أو fpdf2، ولكن Gradio قد لا يدعم عرضها مباشرة
205
+ # هنا سنرجع قائمة الصور ليتم عرضها في Gradio Gallery
206
+ return processed_images_bytes
207
+
208
+
209
+ # -------------------------------------------------------------
210
+ # 3. واجهة المستخدم باستخدام Gradio
211
+ # -------------------------------------------------------------
212
+
213
+ # إنشاء واجهة Gradio
214
+ iface = gr.Interface(
215
+ fn=process_document,
216
+ inputs=gr.File(label="Upload your document (PDF only for now)"),
217
+ outputs=gr.Gallery(label="Translated Pages", show_label=True, columns=2, object_fit="contain"),
218
+ title="Document Translator with Image Overlay (Hugging Face Demo)",
219
+ description="Upload a PDF document. Each page will be converted to an image, text will be extracted, translated to Arabic, and overlaid. Note: OCR accuracy and Arabic RTL rendering are challenging in this demo.",
220
+ allow_flagging="never",
221
+ examples=[
222
+ # يمكنك إضافة أمثلة لملفات PDF هنا
223
+ ]
224
  )
225
 
226
+ iface.launch()
227
+