Spaces:
Runtime error

New / app.py
Bombog944's picture
Update app.py
5d13747 verified
Raw History Blame Contribute Delete
4.54 kB
import gradio as gr
import easyocr
from deep_translator import GoogleTranslator
from PIL import Image, ImageDraw
import numpy as np
import fitz # PyMuPDF ู„ู‚ุฑุงุกุฉ PDF
from docx import Document
from pptx import Presentation
import tempfile
import os
import cv2
reader = easyocr.Reader(['en'])
translator = GoogleTranslator(source='en', target='ar')
# ====== ูˆุธุงุฆู ุงู„ู…ุณุงุนุฏุฉ ======
def pdf_to_images(pdf_path):
pdf = fitz.open(pdf_path)
images = []
for page in pdf:
pix = page.get_pixmap()
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
images.append(img)
return images
def docx_to_images(docx_path):
doc = Document(docx_path)
images = []
text = "\n".join([p.text for p in doc.paragraphs if p.text.strip()])
img = text_to_image(text)
images.append(img)
return images
def pptx_to_images(pptx_path):
prs = Presentation(pptx_path)
images = []
for slide in prs.slides:
text = []
for shape in slide.shapes:
if hasattr(shape, "text"):
text.append(shape.text)
img = text_to_image("\n".join(text))
images.append(img)
return images
def txt_to_images(txt_path):
with open(txt_path, "r", encoding="utf-8") as f:
text = f.read()
return [text_to_image(text)]
def text_to_image(text, width=800, height=1000):
img = Image.new("RGB", (width, height), color="white")
draw = ImageDraw.Draw(img)
lines = text.split("\n")
y = 20
for line in lines:
draw.text((20, y), line[:1000], fill="black")
y += 30
return img
def detect_format(file_path):
ext = os.path.splitext(file_path)[1].lower()
if ext in [".jpg", ".jpeg", ".png"]:
return "image"
elif ext == ".pdf":
return "pdf"
elif ext in [".doc", ".docx"]:
return "docx"
elif ext in [".ppt", ".pptx"]:
return "pptx"
elif ext == ".txt":
return "txt"
else:
raise ValueError("Unsupported file format.")
def translate_image(img):
result = reader.readtext(np.array(img))
translated_img = img.copy()
draw = ImageDraw.Draw(translated_img)
for (bbox, text, prob) in result:
try:
translated = translator.translate(text)
top_left = tuple(map(int, bbox[0]))
bottom_right = tuple(map(int, bbox[2]))
draw.rectangle([top_left, bottom_right], outline="red", width=2)
draw.text((top_left[0], top_left[1]-20), translated, fill="red")
except:
continue
combined = Image.new("RGB", (img.width * 2, img.height))
combined.paste(img, (0, 0))
combined.paste(translated_img, (img.width, 0))
return combined
# ====== ุงู„ุฏุงู„ุฉ ุงู„ุฑุฆูŠุณูŠุฉ ======
def process_file(file_obj):
temp = tempfile.NamedTemporaryFile(delete=False)
temp.write(file_obj.read())
temp.close()
file_type = detect_format(temp.name)
if file_type == "image":
images = [Image.open(temp.name)]
elif file_type == "pdf":
images = pdf_to_images(temp.name)
elif file_type == "docx":
images = docx_to_images(temp.name)
elif file_type == "pptx":
images = pptx_to_images(temp.name)
elif file_type == "txt":
images = txt_to_images(temp.name)
else:
raise ValueError("Unsupported file format.")
output_images = []
zip_path = tempfile.NamedTemporaryFile(delete=False, suffix=".zip").name
os.makedirs("output", exist_ok=True)
import zipfile
with zipfile.ZipFile(zip_path, "w") as zipf:
for i, img in enumerate(images):
translated = translate_image(img)
img_name = f"page_{i+1}.jpg"
compare_name = f"translated_{i+1}.jpg"
img_path = f"output/{compare_name}"
translated.save(img_path)
zipf.write(img_path, compare_name)
output_images.append(translated)
return output_images, zip_path
# ====== ูˆุงุฌู‡ุฉ ุงู„ู…ุณุชุฎุฏู… ======
demo = gr.Interface(
fn=process_file,
inputs=gr.File(label="Upload any document or image"),
outputs=[
gr.Gallery(label="Translated Comparisons").style(grid=[2], height="auto"),
gr.File(label="Download All Results (ZIP)")
],
title="๐ŸŒ Universal Document Translator",
description="Upload a PDF, Word, PowerPoint, Text, or Image file. The app converts pages to images, translates visible text (English โ†’ Arabic), and shows side-by-side comparisons.",
)
demo.launch()