Spaces:
Runtime error
Runtime error
Delete pdf_processor.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130from typing import Optional, BinaryIOfrom pathlib import Pathimport tempfilefrom pdf2image import convert_from_pathfrom PIL import Image, ImageDraw, ImageFontimport loggingfrom exceptions import PDFTranslationErrorfrom config import FILE_CONFIG, FONT_CONFIGfrom image_processor import ImageProcessorfrom ocr_engine import OCREnginefrom translator import Translatorfrom utils import validate_file, get_output_path, cleanup_temp_files
logger = logging.getLogger(__name__)
class PDFProcessor: """Handles PDF processing and translation""" def __init__(self): """Initialize PDF processor with required components""" self.image_processor = ImageProcessor() self.ocr_engine = OCREngine() self.translator = Translator() def process_pdf( self, pdf_file: BinaryIO, source_lang: str = "auto", target_lang: str = "fa" ) -> Path: """ Process PDF file and return path to translated PDF Args: pdf_file: PDF file object source_lang: Source language code target_lang: Target language code Returns: Path to translated PDF """ try: # Validate file validate_file(pdf_file) # Create temporary directory with tempfile.TemporaryDirectory() as temp_dir: temp_dir = Path(temp_dir) temp_pdf = temp_dir / "input.pdf" # Save uploaded PDF with open(temp_pdf, "wb") as f: pdf_file.seek(0) f.write(pdf_file.read()) # Convert PDF to images images = convert_from_path(temp_pdf) if not images: raise PDFTranslationError("No pages found in PDF") processed_images = [] # Process each page for i, img in enumerate(images): logger.info(f"Processing page {i+1}/{len(images)}") # Convert PIL Image to numpy array img_np = np.array(img) # Enhance image enhanced_img = self.image_processor.prepare_for_ocr(img_np) # Perform OCR ocr_results = self.ocr_engine.process_image(enhanced_img) # Merge overlapping results merged_results = self.ocr_engine.merge_results(ocr_results) # Create output image output_img = Image.fromarray(enhanced_img) draw = ImageDraw.Draw(output_img) # Load appropriate font try: font_path = (FONT_CONFIG["rtl_font"] if target_lang in ['fa', 'ar'] else FONT_CONFIG["ltr_font"]) font = ImageFont.truetype( font_path, FONT_CONFIG["default_size"] ) except Exception as e: logger.warning(f"Failed to load font: {str(e)}") font = ImageFont.load_default() # Collect texts for batch translation texts = [text for _, text, _ in merged_results] translations = self.translator.batch_translate( texts, source_lang, target_lang ) # Draw translations for (box, _, _), translation in zip(merged_results, translations): x1, y1, _, _ = box draw.text((x1, y1), translation, font=font, fill=(0, 0, 0)) processed_images.append(output_img) # Save result output_path = get_output_path() processed_images[0].save( output_path, "PDF", save_all=True, append_images=processed_images[1:], resolution=300 ) return output_path except Exception as e: logger.error(f"PDF processing failed: {str(e)}") raise PDFTranslationError(f"PDF processing failed: {str(e)}") finally: # Cleanup if 'temp_pdf' in locals(): cleanup_temp_files(temp_pdf)pdf_processor.pyDeleted-130