import gradio as gr from transformers import AutoTokenizer, AutoModelForSeq2SeqLM import docx import pdfplumber import tempfile # 1. تحميل النموذج والمُجزئ print("جاري تحميل النموذج والمُجزئ، يرجى الانتظار...") model_name = "Helsinki-NLP/opus-mt-ar-en" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForSeq2SeqLM.from_pretrained(model_name) print("تم التحميل بنجاح! جاري تشغيل الواجهة...") # 2. دالة ترجمة النصوص العادية def translate_arabic_to_english(arabic_text): if not arabic_text or not arabic_text.strip(): return "الرجاء إدخال نص / Please enter text" inputs = tokenizer(arabic_text, return_tensors="pt", padding=True, truncation=True, max_length=512) translated_tokens = model.generate(**inputs) result_text = tokenizer.decode(translated_tokens[0], skip_special_tokens=True) return result_text # 3. دالة معالجة وترجمة الملفات def translate_file(file_obj): if file_obj is None: return "الرجاء رفع ملف.", None file_path = file_obj.name ext = file_path.lower().split('.')[-1] extracted_text = "" try: if ext == "docx": doc = docx.Document(file_path) extracted_text = "\n".join([para.text for para in doc.paragraphs if para.text.strip()]) elif ext == "pdf": with pdfplumber.open(file_path) as pdf: for page in pdf.pages: text = page.extract_text() if text: extracted_text += text + "\n" elif ext == "txt": with open(file_path, "r", encoding="utf-8") as f: extracted_text = f.read() else: return "عذراً، صيغة الملف غير مدعومة.", None if not extracted_text.strip(): return "الملف فارغ أو لا يحتوي على نص قابل للقراءة.", None lines = extracted_text.split('\n') translated_lines = [] for line in lines: if line.strip(): translated_lines.append(translate_arabic_to_english(line)) else: translated_lines.append("") final_translation = "\n".join(translated_lines) temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".txt", mode="w", encoding="utf-8") temp_file.write(final_translation) temp_file.close() return final_translation, temp_file.name except Exception as e: return f"حدث خطأ أثناء معالجة الملف: {str(e)}", None # 4. بناء الواجهة الاحترافية (متوافقة مع Gradio 6.0) flat_theme = gr.themes.Soft(primary_hue="teal", font=[gr.themes.GoogleFont("Cairo"), "sans-serif"]) # التعديل الأول: إزالة theme و css من هنا with gr.Blocks() as app: gr.Markdown("
مشروع ترجمة النصوص والمستندات باستخدام النماذج العصبية
") with gr.Tabs(): with gr.Tab("ترجمة النصوص 📝"): with gr.Row(): with gr.Column(): input_text = gr.Textbox(label="النص العربي 🇪🇬", lines=5, rtl=True, placeholder="اكتب النص هنا...") with gr.Row(): translate_btn = gr.Button("ترجم الآن 🚀", variant="primary") clear_btn = gr.ClearButton(components=[input_text], value="مسح 🗑️") gr.Examples( examples=[ ["الذكاء الاصطناعي هو المستقبل"], ["كل الشكر لمبادرة سفراء الذكاء الاصطناعي"] ], inputs=input_text, label="أمثلة جاهزة:" ) with gr.Column(): # التعديل الثاني: إزالة show_copy_button output_text = gr.Textbox(label="الترجمة الإنجليزية 🇺🇸", lines=5, interactive=False) translate_btn.click(fn=translate_arabic_to_english, inputs=input_text, outputs=output_text) clear_btn.click(lambda: "", outputs=output_text) with gr.Tab("ترجمة المستندات 📄"): gr.Markdown("قم برفع ملف (Word, PDF, TXT) باللغة العربية، وسيقوم الذكاء الاصطناعي بقراءته وترجمته بالكامل.") with gr.Row(): with gr.Column(): file_input = gr.File(label="ارفع الملف هنا", file_types=[".pdf", ".docx", ".txt"]) file_translate_btn = gr.Button("ترجمة الملف 🚀", variant="primary") with gr.Column(): # التعديل الثالث: إزالة show_copy_button file_output_text = gr.Textbox(label="محتوى الملف مترجماً 🇺🇸", lines=10, interactive=False) file_download = gr.File(label="تحميل النتيجة") file_translate_btn.click( fn=translate_file, inputs=file_input, outputs=[file_output_text, file_download] ) # التعديل الرابع: نقل theme و css إلى هنا app.launch(theme=flat_theme, css="footer {visibility: hidden}")