Spaces:
Sleeping
Sleeping
Update app.py
Browse files5 unmodified lines67891011121314151617181920212211 unmodified lines34353637383940414243444546474849505152532 unmodified lines5657585960616219 unmodified lines8283848586878889909192939495969725 unmodified lines12312412512612712812913013114 unmodified lines14614714814915015115215315415510 unmodified lines1661671681691701711721731741751761771782 unmodified lines1811821831841851861871881891901911921931941951961971981992005 unmodified linesimport base64import osimport unicodedata# Traducción (opcional, sigue igual)from transformers import pipelinetranslator = pipeline("translation_en_to_es", model="Helsinki-NLP/opus-mt-en-es")# EasyOCRimport easyocrocr_reader = easyocr.Reader(['en', 'es'])# ---------- OCR y limpieza de texto ----------def clean_ocr_text(text):text = unicodedata.normalize("NFC", text)11 unmodified linestranslated.append(result[0]["translation_text"])return "\n".join(translated)# ---------- EasyOCR replacement ----------def easyocr_image_to_string(image):np_image = np.array(image)results = ocr_reader.readtext(np_image, detail=0, paragraph=True)return "\n".join(results)# ---------- Funciones de imagen ----------def text_area_ratio(image):np_img = np.array(image.convert("L"))_, thresh = cv2.threshold(np_img, 150, 255, cv2.THRESH_BINARY_INV)contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)text_area = sum(w * h for x, y, w, h in [cv2.boundingRect(c) for c in contours if 8 < cv2.boundingRect(c)[3] < 40 and 5 < cv2.boundingRect(c)[2] < 100])total_area = np_img.shape[0] * np_img.shape[1]return text_area / total_area if total_area > 0 else 02 unmodified linesdef is_primarily_text(image, ocr_threshold=30):if has_significant_text(image):ocr_result = easyocr_image_to_string(image)return len(ocr_result.strip()) > ocr_thresholdreturn False19 unmodified linesresults.append(crop)return results# ---------- Extracción de texto + imágenes ----------def clean_bullet_line(text):text = unicodedata.normalize("NFKC", text)text = text.replace("e@", "-")text = text.replace("@", "-")text = text.replace("•", "-")text = text.replace("*", "-")text = text.replace("·", "-")text = text.replace("–", "-")text = " ".join(text.split())return text25 unmodified linesbase_image = page.parent.extract_image(xref)image_bytes = base_image["image"]ext = base_image["ext"]image_path = f"/tmp/imagen_p{page_index + 1}_{img_index + 1}.{ext}"with open(image_path, "wb") as f:f.write(image_bytes)image_paths.append(image_path)elements.append((float("inf") - img_index, f"\n\n\n", 10))image_counter += 114 unmodified linesmarkdown_output += "\n---\n\n"return markdown_output.strip()# ---------- Función principal ----------def convert(pdf_file):temp_pdf_path = pdf_file.namedoc = fitz.open(temp_pdf_path)markdown_output = ""image_paths = []10 unmodified linesmarkdown_output += f"\n## Página {page_num + 1}\n\n"pix = page.get_pixmap(dpi=300)img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)image_path = f"/tmp/ocr_page_{page_num + 1}.jpg"img.save(image_path)image_paths.append(image_path)markdown_output += f"\n"try:ocr_text = easyocr_image_to_string(img)except Exception:ocr_text = ""ocr_text_clean = clean_ocr_text(ocr_text)2 unmodified linescrops = extract_visual_regions(img)for i, crop in enumerate(crops):crop_path = f"/tmp/recorte_p{page_num + 1}_{i + 1}.jpg"crop.save(crop_path)image_paths.append(crop_path)markdown_output += f"\n\n\n"markdown_output += "\n---\n\n"markdown_path = "/tmp/resultado.md"with open(markdown_path, "w", encoding="utf-8") as f:f.write(markdown_output)return markdown_output.strip(), image_paths, markdown_path# ---------- Gradio Interface ----------with gr.Blocks() as demo:with gr.Row():5 unmodified lines6789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525311 unmodified lines65666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321332 unmodified lines13613713813914014114219 unmodified lines16216316416516616716816917017117217325 unmodified lines19920020120220320420520620720814 unmodified lines22322422522622722822923023123223323423510 unmodified lines2462472482492502512522532542552562572582592 unmodified lines2622632642652662672682692702712722732742752762772782792802812822835 unmodified linesimport base64import osimport unicodedataimport torchimport tempfileimport atexitfrom transformers import pipeline, AutoModelForImageTextToText, AutoProcessor# ========== CONFIG ==========translator = pipeline("translation_en_to_es", model="Helsinki-NLP/opus-mt-en-es")print("Loading Nanonets OCR model...")nanonets_model_path = "nanonets/Nanonets-OCR-s"nanonets_model = AutoModelForImageTextToText.from_pretrained(nanonets_model_path,torch_dtype="auto",device_map="auto",attn_implementation="flash_attention_2",)nanonets_model.eval()nanonets_processor = AutoProcessor.from_pretrained(nanonets_model_path)print("Nanonets model loaded!")# ========== TEMP FILE CLEANUP ==========generated_files = []temp_dir = tempfile.gettempdir()def register_file(path):generated_files.append(path)return pathdef cleanup():for path in generated_files:try:os.remove(path)except Exception:passatexit.register(cleanup)# ========== TEXT CLEANING ==========def clean_ocr_text(text):text = unicodedata.normalize("NFC", text)11 unmodified linestranslated.append(result[0]["translation_text"])return "\n".join(translated)# ========== NANONETS OCR ==========def nanonets_image_to_string(image, max_tokens=2048):prompt = ("Extract the text from the above document as if you were reading it naturally. ""Return the tables in html format. Return the equations in LaTeX representation. ""If there is an image in the document and image caption is not present, add a small description ""of the image inside the <img></img> tag; otherwise, add the image caption inside <img></img>. ""Watermarks should be wrapped in brackets. Ex: <watermark>OFFICIAL COPY</watermark>. ""Page numbers should be wrapped in brackets. Ex: <page_number>14</page_number> or <page_number>9/22</page_number>. ""Prefer using ☐ and ☑ for check boxes.")if not isinstance(image, Image.Image):image = Image.fromarray(image)messages = [{"role": "system", "content": "You are a helpful assistant."},{"role": "user","content": [{"type": "image", "image": image},{"type": "text", "text": prompt},],},]text_input = nanonets_processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)inputs = nanonets_processor(text=[text_input], images=[image], padding=True, return_tensors="pt")inputs = inputs.to(nanonets_model.device)with torch.no_grad():output_ids = nanonets_model.generate(**inputs,max_new_tokens=max_tokens,do_sample=False,repetition_penalty=1.25,)generated_ids = [output_ids[len(input_ids):]for input_ids, output_ids in zip(inputs.input_ids, output_ids)]output_text = nanonets_processor.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)return output_text[0]# ========== IMAGE ANALYSIS ==========def text_area_ratio(image):np_img = np.array(image.convert("L"))_, thresh = cv2.threshold(np_img, 150, 255, cv2.THRESH_BINARY_INV)contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)text_area = sum(w * hfor x, y, w, h in [cv2.boundingRect(c) for c in contoursif 8 < cv2.boundingRect(c)[3] < 40 and 5 < cv2.boundingRect(c)[2] < 100])total_area = np_img.shape[0] * np_img.shape[1]return text_area / total_area if total_area > 0 else 02 unmodified linesdef is_primarily_text(image, ocr_threshold=30):if has_significant_text(image):ocr_result = nanonets_image_to_string(image)return len(ocr_result.strip()) > ocr_thresholdreturn False19 unmodified linesresults.append(crop)return results# ========== PDF TEXT + IMAGE EXTRACTION ==========def clean_bullet_line(text):text = unicodedata.normalize("NFKC", text)for bullet in ["e@", "@", "•", "*", "·", "–"]:text = text.replace(bullet, "-")text = " ".join(text.split())return text25 unmodified linesbase_image = page.parent.extract_image(xref)image_bytes = base_image["image"]ext = base_image["ext"]image_path = os.path.join(temp_dir, f"imagen_p{page_index + 1}_{img_index + 1}.{ext}")with open(image_path, "wb") as f:f.write(image_bytes)register_file(image_path)image_paths.append(image_path)elements.append((float("inf") - img_index, f"\n\n\n", 10))image_counter += 114 unmodified linesmarkdown_output += "\n---\n\n"return markdown_output.strip()# ========== MAIN FUNCTION ==========def convert(pdf_file):temp_pdf_path = pdf_file.nameif not os.path.exists(temp_pdf_path):raise FileNotFoundError("El archivo PDF no se encontró.")doc = fitz.open(temp_pdf_path)markdown_output = ""image_paths = []10 unmodified linesmarkdown_output += f"\n## Página {page_num + 1}\n\n"pix = page.get_pixmap(dpi=300)img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)image_path = os.path.join(temp_dir, f"ocr_page_{page_num + 1}.jpg")img.save(image_path)register_file(image_path)image_paths.append(image_path)markdown_output += f"\n"try:ocr_text = nanonets_image_to_string(img)except Exception:ocr_text = ""ocr_text_clean = clean_ocr_text(ocr_text)2 unmodified linescrops = extract_visual_regions(img)for i, crop in enumerate(crops):crop_path = os.path.join(temp_dir, f"recorte_p{page_num + 1}_{i + 1}.jpg")crop.save(crop_path)register_file(crop_path)image_paths.append(crop_path)markdown_output += f"\n\n\n"markdown_output += "\n---\n\n"markdown_path = os.path.join(temp_dir, "resultado.md")with open(markdown_path, "w", encoding="utf-8") as f:f.write(markdown_output)register_file(markdown_path)return markdown_output.strip(), image_paths, markdown_path# ========== GRADIO UI ==========with gr.Blocks() as demo:with gr.Row():
app.py+113-30