Spaces:
Runtime error
Runtime error
Download app.py from Bombog944/File-translator: direct link, hf CLI and curl.
- Browser
- Download file 4.58 kB
-
https://huggingface.co/spaces/Bombog944/File-translator/resolve/main/app.py
- Command line
-
hf download hf://spaces/Bombog944/File-translator/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Bombog944/File-translator/resolve/main/app.py
4.58 kB
| import os | |
| import tempfile | |
| from flask import Flask, render_template_string, request, send_file, jsonify | |
| from deep_translator import GoogleTranslator | |
| import fitz # PyMuPDF | |
| from reportlab.pdfgen import canvas | |
| from reportlab.lib.pagesizes import A4 | |
| from reportlab.lib.utils import ImageReader | |
| from io import BytesIO | |
| app = Flask(__name__) | |
| # واجهة المستخدم | |
| HTML_PAGE = """ | |
| <!DOCTYPE html> | |
| <html lang="ar" dir="rtl"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <title>مترجم PDF مباشر</title> | |
| <style> | |
| body {font-family: sans-serif; background:#f2f2f2; text-align:center; margin-top:80px;} | |
| form {background:#fff; padding:30px; border-radius:10px; box-shadow:0 0 10px #ccc; display:inline-block;} | |
| input[type=file] {margin:10px;} | |
| button {padding:10px 20px; background:#2e8b57; color:white; border:none; border-radius:5px; cursor:pointer;} | |
| button:hover {background:#256e45;} | |
| </style> | |
| </head> | |
| <body> | |
| <h2>📘 مترجم PDF — ترجمة تحت كل سطر</h2> | |
| <form id="uploadForm" method="POST" enctype="multipart/form-data"> | |
| <input type="file" name="file" accept=".pdf" required><br> | |
| <button type="submit">ابدأ الترجمة</button> | |
| </form> | |
| <div id="result" style="margin-top:20px;"></div> | |
| <script> | |
| const form = document.getElementById('uploadForm'); | |
| form.onsubmit = async (e) => { | |
| e.preventDefault(); | |
| const formData = new FormData(form); | |
| document.getElementById('result').innerHTML = '⏳ جاري الترجمة... برجاء الانتظار'; | |
| const res = await fetch('/translate', { method: 'POST', body: formData }); | |
| if (res.ok) { | |
| const blob = await res.blob(); | |
| const url = window.URL.createObjectURL(blob); | |
| document.getElementById('result').innerHTML = '<a href="' + url + '" download="translated_output.pdf"><button>⬇️ تحميل الملف المترجم</button></a>'; | |
| } else { | |
| const err = await res.text(); | |
| document.getElementById('result').innerHTML = '❌ حدث خطأ أثناء الترجمة: ' + err; | |
| } | |
| }; | |
| </script> | |
| </body> | |
| </html> | |
| """ | |
| def translate_line(line): | |
| """ترجمة سطر واحد مع التعامل مع الأخطاء""" | |
| try: | |
| if not line.strip(): | |
| return "" | |
| return GoogleTranslator(source='auto', target='ar').translate(line) | |
| except Exception as e: | |
| return f"[تعذرت ترجمة السطر: {e}]" | |
| def home(): | |
| return render_template_string(HTML_PAGE) | |
| def translate_pdf(): | |
| try: | |
| if 'file' not in request.files: | |
| return jsonify({'error': 'لم يتم رفع ملف'}), 400 | |
| file = request.files['file'] | |
| if not file.filename.endswith('.pdf'): | |
| return jsonify({'error': 'يُقبل فقط ملفات PDF'}), 400 | |
| pdf_bytes = file.read() | |
| original_doc = fitz.open("pdf", pdf_bytes) | |
| output_path = tempfile.mktemp(suffix=".pdf") | |
| c = canvas.Canvas(output_path, pagesize=A4) | |
| for page_index, page in enumerate(original_doc): | |
| text = page.get_text("text") | |
| if not text.strip(): | |
| continue | |
| # استخراج الصور ووضعها أولًا | |
| image_list = page.get_images(full=True) | |
| for img in image_list: | |
| xref = img[0] | |
| base_image = original_doc.extract_image(xref) | |
| image_bytes = base_image["image"] | |
| image = ImageReader(BytesIO(image_bytes)) | |
| c.drawImage(image, 50, 400, width=200, height=200) | |
| # كتابة النص + الترجمة | |
| lines = text.split('\n') | |
| y = 350 | |
| for line in lines: | |
| if y < 100: # لو الصفحة قربت تخلص | |
| c.showPage() | |
| y = 750 | |
| c.setFont("Helvetica", 10) | |
| c.drawString(50, y, line.strip()) | |
| y -= 14 | |
| translated = translate_line(line) | |
| if translated: | |
| c.setFont("Helvetica-Oblique", 10) | |
| c.setFillColorRGB(0.2, 0.5, 0.2) | |
| c.drawString(70, y, translated) | |
| c.setFillColorRGB(0, 0, 0) | |
| y -= 18 | |
| c.showPage() | |
| c.save() | |
| return send_file(output_path, as_attachment=True, download_name="translated_output.pdf") | |
| except Exception as e: | |
| return jsonify({'error': f'حدث خطأ غير متوقع: {str(e)}'}), 500 | |
| if __name__ == '__main__': | |
| app.run(debug=True) |