Spaces:
Runtime error

Minitranslate / app.py
Bombog944's picture
Update app.py
2371cae verified
Raw History Blame Contribute Delete
12.4 kB
# app.py
import gradio as gr
import fitz # PyMuPDF for PDF processing
from PIL import Image, ImageDraw, ImageFont
import io
from transformers import pipeline
from deep_translator import GoogleTranslator # يمكن استبدالها بـ Hugging Face translation model
# -------------------------------------------------------------
# 1. إعداد نماذج Hugging Face / أدوات الترجمة
# -------------------------------------------------------------
# نموذج OCR من Hugging Face (مثال، قد لا يعطي إحداثيات دقيقة لكل سطر)
# للأسف، معظم نماذج OCR الجاهزة في Hugging Face لا توفر إحداثيات SBOX دقيقة لكل "سطر"
# ستحتاج لنموذج متخصص مثل LayoutLMv3 أو Tesseract (خارجي)
# ocr_pipeline = pipeline("ocr", model="microsoft/trocr-base-handwritten") # مثال فقط، لا يعطي إحداثيات
# سنستخدم حل OCR بسيط يعتمد على PyMuPDF (أو Tesseract إذا تم تثبيته كخارجية)
# للترجمة، نستخدم deep_translator كخيار سهل
translator = GoogleTranslator(source='auto', target='ar')
# -------------------------------------------------------------
# 2. وظائف معالجة الملفات والصور
# -------------------------------------------------------------
def pdf_to_image_bytes(pdf_file):
"""يحول صفحات PDF إلى قائمة من بايتات الصور."""
doc = fitz.open(stream=pdf_file.read(), filetype="pdf")
image_bytes_list = []
for i, page in enumerate(doc):
pix = page.get_pixmap(dpi=200) # دقة 200 كافية للويب
img_byte_arr = io.BytesIO()
Image.frombytes("RGB", [pix.width, pix.height], pix.samples).save(img_byte_arr, format="PNG")
image_bytes_list.append(img_byte_arr.getvalue())
doc.close()
return image_bytes_list
def process_page_image(image_bytes):
"""
يستخرج النص من صورة الصفحة، يترجمه، ويضيفه كتراكب.
⚠️ التحدي: OCR دقيق مع إحداثيات لكل سطر، والكتابة العربية الصحيحة.
"""
img = Image.open(io.BytesIO(image_bytes)).convert("RGB")
draw = ImageDraw.Draw(img)
# اختيار خط عربي يدعم RTL (يجب أن يكون موجوداً في بيئة Hugging Face Space)
# مثال: NotoSansArabic-Regular.ttf أو Arial.ttf
try:
# تأكد من وجود هذا الخط في مجلد fonts داخل الـ Space الخاص بك
font_path = "/usr/share/fonts/truetype/noto/NotoSansArabic-Regular.ttf"
# أو أي خط عربي آخر يمكنك إضافته لبيئة Docker في Hugging Face Space
font = ImageFont.truetype(font_path, size=24)
except IOError:
font = ImageFont.load_default()
print("Warning: NotoSansArabic font not found, using default. Arabic text might be rendered incorrectly.")
# ------ هنا تأتي الخطوة المعقدة جداً: OCR مع إحداثيات السطر --------
# PyMuPDF يمكنه استخراج النص والإحداثيات ولكن ليس دقيقًا لكل "سطر" ككتلة واحدة
# Tesseract (تتطلب تثبيت خارجي) أفضل لإخراج الإحداثيات
# نماذج Hugging Face مثل DocTr (DocTransformer) قد تساعد ولكنها تتطلب استدعاء API خاص
# حالياً، سنستخدم حلاً مبسطاً: استخراج كل النص، ثم تقسيمه لسطور وترجمته
# هذا لن يحافظ على إحداثيات السطر الأصلي بدقة، ولكن سيضيف الترجمة في مكان جديد
# استخراج النص باستخدام PyMuPDF (بما أنه من PDF)
# هذا الكود هو تقديري فقط ولا يستخرج إحداثيات كل سطر على الصورة مباشرة
# للحصول على إحداثيات دقيقة، ستحتاج إلى OCR أقوى!
dummy_text_lines = ["This is a sample line of text.", "Another line for translation."]
# ^^^^^^^^^^ في الواقع ستحتاج لاستبدال هذا بـ OCR حقيقي من الصورة ^^^^^^^^^^
# محاكاة OCR بسيط (للتوضيح فقط، لن يعطي إحداثيات دقيقة)
text_data = []
# هنا يجب عليك استخدام OCR حقيقي على الصورة واستخراج النص مع الـ bounding boxes لكل سطر
# example_text_bbox = {"text": "Hello World", "bbox": (50, 50, 200, 70)}
# بما أننا لا نستطيع استخراج إحداثيات دقيقة من Hugging Face OCR مباشرة لكل سطر بحد ذاته
# سنقوم بإنشاء منطقة جديدة لإضافة الترجمة
y_offset = 50 # بداية إضافة الترجمات
line_height = 30 # ارتفاع تقديري للسطر
# هذا الجزء يحتاج إلى تحسين كبير جداً ليعمل كما تصف
# يجب أن يكون لديك list of {"text": original_text, "bbox": (x1,y1,x2,y2)}
# مثال توضيحي (لن يعمل بدقة)
# for i, line in enumerate(dummy_text_lines):
# translated_line = translator.translate(line)
# # تحديد مكان عشوائي لإضافة الترجمة (غير دقيق)
# draw.text((50, y_offset + (i * 2 * line_height)), translated_line, fill=(0, 0, 0), font=font)
# حل أفضل (ولكن ليس مثاليًا بدون OCR دقيق بالإحداثيات):
# استخدام OCR من Hugging Face للحصول على كل النصوص ككتلة
# ثم ترجمتها ووضعها في جزء من الصورة
# This part would require a robust OCR model like LayoutLMv3 with custom parsing
# or integrating Tesseract via an external process in the Hugging Face Space setup.
# For now, let's just attempt to get text and translate without perfect overlay.
# -----------------------------------------------------------------
# محاولة استخدام PyTesseract (يتطلب تثبيت Tesseract-OCR في بيئة Docker)
# -----------------------------------------------------------------
try:
import pytesseract
# تعيين مسار Tesseract إذا لم يكن في PATH (قد يكون مختلفًا في Hugging Face Space)
# pytesseract.pytesseract.tesseract_cmd = '/usr/bin/tesseract' # أو حسب المسار الصحيح
# استخراج البيانات بما فيها الإحداثيات
data = pytesseract.image_to_data(img, output_type=pytesseract.Output.DICT, lang='eng') # يمكن إضافة 'ara' للتعرف على العربي أيضًا
# تجميع السطور
lines_info = []
current_line = []
current_bbox = [float('inf'), float('inf'), float('-inf'), float('-inf')]
for i in range(len(data['text'])):
text = data['text'][i].strip()
conf = int(data['conf'][i])
if conf > 60 and text: # Filter out low confidence and empty text
x, y, w, h = data['left'][i], data['top'][i], data['width'][i], data['height'][i]
word_bbox = (x, y, x + w, y + h)
# Assuming words are grouped by line_num for simplicity
if not current_line or data['line_num'][i] == data['line_num'][i-1] : # if same line or first word
current_line.append(text)
current_bbox[0] = min(current_bbox[0], word_bbox[0])
current_bbox[1] = min(current_bbox[1], word_bbox[1])
current_bbox[2] = max(current_bbox[2], word_bbox[2])
current_bbox[3] = max(current_bbox[3], word_bbox[3])
else: # New line
if current_line:
lines_info.append({"original": " ".join(current_line), "bbox": tuple(current_bbox)})
current_line = [text]
current_bbox = list(word_bbox)
# Add the last line
if current_line:
lines_info.append({"original": " ".join(current_line), "bbox": tuple(current_bbox)})
# الآن نقوم بالترجمة والإضافة
translated_img = img.copy()
draw_translated = ImageDraw.Draw(translated_img)
y_offset_for_translation = 25 # مسافة بين السطر الأصلي والترجمة
for line_data in lines_info:
original_text = line_data['original']
x1, y1, x2, y2 = line_data['bbox']
if original_text: # تأكد أن هناك نصًا لترجمته
translated_text = translator.translate(original_text)
# لحل مشكلة RTL، قد تحتاج مكتبات مثل arabic_reshaper و bidi
# from arabic_reshaper import ArabicReshaper
# from bidi.algorithm import get_display
# reshaper = ArabicReshaper()
# translated_text_reshaped = reshaper.reshape(translated_text)
# translated_text_display = get_display(translated_text_reshaped)
# draw_translated.text((x1, y2 + y_offset_for_translation), translated_text_display, fill=(0, 0, 0), font=font)
draw_translated.text((x1, y2 + y_offset_for_translation), translated_text, fill=(0, 0, 0), font=font) # بدون RTL
img = translated_img # نستخدم الصورة المترجمة
except ImportError:
print("Warning: pytesseract not found or Tesseract-OCR not installed. Cannot perform advanced OCR.")
# fallback if Tesseract is not available
draw.text((50, img.height - 100), "Translation unavailable without Tesseract-OCR.", fill=(255, 0, 0), font=font)
# تحويل الصورة إلى بايتات لإرجاعها في Gradio
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format="PNG")
return img_byte_arr.getvalue()
def process_document(file):
"""الواجهة الرئيسية التي تستقبل الملف."""
if file is None:
return "Please upload a document."
file_path = file.name # Gradio يمرر File object
# 1. تحويل الملف إلى صور (نركز على PDF هنا)
if file_path.lower().endswith(".pdf"):
image_bytes_list = pdf_to_image_bytes(file)
else:
# هنا ستكون بحاجة لكود تحويل DOCX/PPTX إلى PDF أولاً
# وهو تحدي كبير في بيئة Hugging Face Space بدون أدوات خارجية
return "Only PDF files are supported directly in this demo. DOCX/PPTX conversion is complex."
if not image_bytes_list:
return "Failed to convert document to images."
processed_images_bytes = []
for img_bytes in image_bytes_list:
processed_images_bytes.append(process_page_image(img_bytes))
# 2. تجميع الصور المترجمة في ملف PDF واحد جديد (اختياري)
# يمكن إرجاع قائمة الصور مباشرة ليتم عرضها في Gradio
# إذا أردت إرجاع PDF، ستحتاج مكتبة لإنشاء PDF من صور
# مثلاً reportlab أو fpdf2، ولكن Gradio قد لا يدعم عرضها مباشرة
# هنا سنرجع قائمة الصور ليتم عرضها في Gradio Gallery
return processed_images_bytes
# -------------------------------------------------------------
# 3. واجهة المستخدم باستخدام Gradio
# -------------------------------------------------------------
# إنشاء واجهة Gradio
iface = gr.Interface(
fn=process_document,
inputs=gr.File(label="Upload your document (PDF only for now)"),
outputs=gr.Gallery(label="Translated Pages", show_label=True, columns=2, object_fit="contain"),
title="Document Translator with Image Overlay (Hugging Face Demo)",
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.",
allow_flagging="never",
examples=[
# يمكنك إضافة أمثلة لملفات PDF هنا
]
)
iface.launch()