Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from googletrans import Translator
|
| 3 |
+
from docx import Document
|
| 4 |
+
from io import BytesIO
|
| 5 |
+
from PyPDF2 import PdfReader, PdfWriter
|
| 6 |
+
|
| 7 |
+
translator = Translator()
|
| 8 |
+
|
| 9 |
+
def translate_text(text):
|
| 10 |
+
result = ""
|
| 11 |
+
for line in text.split("\n"):
|
| 12 |
+
if line.strip():
|
| 13 |
+
trans = translator.translate(line, dest="ar").text
|
| 14 |
+
result += f"{line}\n{trans}\n\n"
|
| 15 |
+
return result
|
| 16 |
+
|
| 17 |
+
def translate_file(file):
|
| 18 |
+
filename = file.name.lower()
|
| 19 |
+
|
| 20 |
+
if filename.endswith(".docx"):
|
| 21 |
+
doc = Document(file.name)
|
| 22 |
+
new_doc = Document()
|
| 23 |
+
for para in doc.paragraphs:
|
| 24 |
+
if para.text.strip():
|
| 25 |
+
new_doc.add_paragraph(para.text)
|
| 26 |
+
trans = translator.translate(para.text, dest="ar").text
|
| 27 |
+
new_doc.add_paragraph(trans)
|
| 28 |
+
else:
|
| 29 |
+
new_doc.add_paragraph("")
|
| 30 |
+
output = BytesIO()
|
| 31 |
+
new_doc.save(output)
|
| 32 |
+
output.seek(0)
|
| 33 |
+
return output, "translated.docx"
|
| 34 |
+
|
| 35 |
+
elif filename.endswith(".pdf"):
|
| 36 |
+
reader = PdfReader(file.name)
|
| 37 |
+
writer = PdfWriter()
|
| 38 |
+
for page in reader.pages:
|
| 39 |
+
text = page.extract_text()
|
| 40 |
+
if text:
|
| 41 |
+
translated = translate_text(text)
|
| 42 |
+
page.extract_text = lambda: translated
|
| 43 |
+
writer.add_page(page)
|
| 44 |
+
output = BytesIO()
|
| 45 |
+
writer.write(output)
|
| 46 |
+
output.seek(0)
|
| 47 |
+
return output, "translated.pdf"
|
| 48 |
+
|
| 49 |
+
else:
|
| 50 |
+
return None, "Unsupported file type"
|
| 51 |
+
|
| 52 |
+
demo = gr.Interface(
|
| 53 |
+
fn=translate_file,
|
| 54 |
+
inputs=gr.File(label="ارفع ملف Word أو PDF"),
|
| 55 |
+
outputs=gr.File(label="الملف المترجم"),
|
| 56 |
+
title="AI File Translator",
|
| 57 |
+
description="يترجم الملف الإنجليزي للعربية ويضيف الترجمة أسفل كل جملة مع الحفاظ على التنسيق."
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
demo.launch()
|