Spaces:
Runtime error

Bombog944 commited on
Commit
149a4e2
·
verified ·
1 Parent(s): 04af013

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -26
app.py CHANGED
@@ -1,22 +1,22 @@
1
- # app.py
2
  import os
3
- os.environ["TOKENIZERS_PARALLELISM"] = "false" # سرعة واستقرار
4
  from io import BytesIO
5
  import tempfile
6
-
7
  import gradio as gr
8
  from deep_translator import GoogleTranslator
9
  import fitz # pymupdf
10
  from reportlab.pdfgen import canvas
11
  from reportlab.lib.pagesizes import A4
12
  from reportlab.lib.utils import ImageReader
 
 
13
 
14
  translator = GoogleTranslator(source="auto", target="ar")
15
 
16
  def translate_chunked(text):
17
- """تقسيم النص إلى قطع صغيرة وترجمة كل قطعة لتفادي حد 5000 حرف"""
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:
@@ -31,9 +31,7 @@ def translate_pdf_bytes(pdf_bytes):
31
  c = canvas.Canvas(temp_out.name, pagesize=A4)
32
 
33
  for page_index, page in enumerate(doc):
34
- # استخراج النص سطر سطر
35
- blocks = page.get_text("blocks") # blocks give rectangles with text lines
36
- # وضع صور أولًا (لو موجودة)
37
  try:
38
  images = page.get_images(full=True)
39
  y_img = 500
@@ -45,12 +43,11 @@ def translate_pdf_bytes(pdf_bytes):
45
  image = ImageReader(BytesIO(image_bytes))
46
  c.drawImage(image, 50, y_img, width=200, height=150)
47
  y_img -= 160
48
- except Exception as e_img:
49
- print(f"تجاوُز صورة تالفة في صفحة {page_index+1}: {e_img}")
50
  except Exception:
51
  pass
52
 
53
- # نظمنا السطور حسب الارتفاع داخل الصفحة
54
  lines = []
55
  for b in blocks:
56
  text = b[4]
@@ -59,50 +56,81 @@ def translate_pdf_bytes(pdf_bytes):
59
  lines.append(ln.strip())
60
 
61
  y = 700
62
- c.setFont("Helvetica", 10)
63
  for ln in lines:
64
  if y < 100:
65
  c.showPage()
66
  y = 750
67
- c.setFont("Helvetica", 10)
68
- # اكتب السطر الأصلي
69
  c.drawString(50, y, ln)
70
  y -= 14
71
- # ترجم السطر على شكل قطعة (bulk صغير)
72
  translated = translate_chunked(ln)
73
  if translated:
74
  c.setFont("Helvetica-Oblique", 10)
75
- # ترجمة مائلة ولون بسيط
76
- c.setFillColorRGB(0.15, 0.45, 0.15)
77
  c.drawString(60, y, translated)
78
  c.setFillColorRGB(0, 0, 0)
79
  y -= 18
80
- c.setFont("Helvetica", 10)
81
-
82
  c.showPage()
83
 
84
  c.save()
85
  doc.close()
86
  return temp_out.name
87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  def process_file(file_obj):
89
  try:
90
- pdf_bytes = file_obj.read()
91
- out_path = translate_pdf_bytes(pdf_bytes)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  return open(out_path, "rb")
93
  except Exception as e:
94
  return f"حدث خطأ أثناء المعالجة: {e}"
95
 
96
- title = "🧠 مترجم PDF — يضيف الترجمة تحت كل سطر (بدون فيزا)"
97
- desc = "ارفع PDF إنجليزي. الأداة تترجم سطرًا-سطر وتحفظ الصور، وترد ملف PDF جاهز للتحميل."
98
 
99
  demo = gr.Interface(
100
  fn=process_file,
101
- inputs=gr.File(label="ارفع ملف PDF (English)"),
102
- outputs=gr.File(label="الملف المترجم"),
103
  title=title,
104
  description=desc,
105
- allow_flagging="never"
106
  )
107
 
108
  if __name__ == "__main__":
 
 
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:
 
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
 
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]
 
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__":