Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333 unmodified lines373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208import gradio as grimport fitz # PyMuPDFfrom PIL import Imageimport numpy as npimport cv2import pytesseractimport base64import osimport unicodedata# NUEVO: Traducciónfrom transformers import pipeline# Inicializa el pipeline de traducción EN->ES una sola veztranslator = pipeline("translation_en_to_es", model="Helsinki-NLP/opus-mt-en-es")# ---------- OCR y limpieza de texto ----------def clean_ocr_text(text):text = unicodedata.normalize("NFC", text)lines = text.splitlines()cleaned_lines = [line.strip() for line in lines if line.strip()]return "\n".join(cleaned_lines)def translate_text(text):"""Traduce texto del inglés al español si está en inglés (siempre lo traduce para simplificar)"""# Para hacerlo robusto podrías agregar detección de idioma (langdetect),# pero para este ejemplo traducimos siempreif len(text.strip()) < 5:return textchunks = [text[i:i+500] for i in range(0, len(text), 500)]3 unmodified linestranslated.append(result[0]["translation_text"])return "\n".join(translated)# ---------- 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 0def has_significant_text(image):return text_area_ratio(image) > 0.25def is_primarily_text(image, ocr_threshold=30):if has_significant_text(image):ocr_result = pytesseract.image_to_string(image, lang="eng+spa")return len(ocr_result.strip()) > ocr_thresholdreturn Falsedef is_likely_photo(crop):np_crop = np.array(crop)gray = cv2.cvtColor(np_crop, cv2.COLOR_RGB2GRAY)return np.std(gray) > 25 and len(np.unique(gray)) > 50def extract_visual_regions(image):np_img = np.array(image.convert("RGB"))gray = cv2.cvtColor(np_img, cv2.COLOR_RGB2GRAY)_, binary = cv2.threshold(gray, 220, 255, cv2.THRESH_BINARY_INV)closed = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_RECT, (15, 15)))num_labels, labels, stats, _ = cv2.connectedComponentsWithStats(closed, connectivity=8)results = []for i in range(1, num_labels):x, y, w, h, area = stats[i]if area > 2000 and 0.3 < (w / float(h)) < 3.5:bbox = (x, y, x + w, y + h)crop = image.crop(bbox)if is_likely_photo(crop) and text_area_ratio(crop) < 0.25 and not is_primarily_text(crop):results.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 textdef extract_text_markdown(doc, image_paths, page_index, seen_xrefs):markdown_output = f"\n## Página {page_index + 1}\n\n"image_counter = 1elements = []page = doc[0]blocks = page.get_text("dict")["blocks"]for b in blocks:y = b["bbox"][1]if b["type"] == 0:for line in b["lines"]:line_y = line["bbox"][1]line_text = " ".join([span["text"] for span in line["spans"]]).strip()line_text = clean_bullet_line(line_text)max_font_size = max([span.get("size", 10) for span in line["spans"]])if line_text:elements.append((line_y, line_text, max_font_size))images_on_page = page.get_images(full=True)for img_index, img in enumerate(images_on_page):xref = img[0]if xref in seen_xrefs:continueseen_xrefs.add(xref)try:base_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 += 1except Exception as e:elements.append((float("inf"), f"[Error imagen: {e}]", 10))elements.sort(key=lambda x: x[0])previous_y = Nonefor y, text, font_size in elements:is_header = font_size >= 14if previous_y is not None and abs(y - previous_y) > 10:markdown_output += "\n"translated = translate_text(text.strip())markdown_output += f"\n### {translated}\n" if is_header else translated + "\n"previous_y = ymarkdown_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 = []seen_xrefs = set()for page_num in range(len(doc)):page = doc[page_num]text = page.get_text("text").strip()if len(text) > 30:# Texto nativo del PDFextracted = extract_text_markdown([page], image_paths, page_num, seen_xrefs)markdown_output += extracted + "\n"else:# Página "escaneada" -> OCRmarkdown_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 = pytesseract.image_to_string(img, lang="eng+spa")except pytesseract.TesseractError:ocr_text = ""ocr_text_clean = clean_ocr_text(ocr_text)translated_ocr = translate_text(ocr_text_clean)markdown_output += translated_ocr + "\n"crops = 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():pdf_input = gr.File(label="Upload your PDF", type="filepath", file_types=[".pdf"])submit_btn = gr.Button("Process PDF")markdown_output = gr.Textbox(label="Generated Markdown", lines=25, interactive=True)gallery_output = gr.Gallery(label="Extracted and Detected Images", type="file")download_md = gr.File(label="Download Markdown File")submit_btn.click(fn=convert, inputs=[pdf_input], outputs=[markdown_output, gallery_output, download_md])demo.launch()1234567891011121314151617181920212223242526272829303132333435363738393 unmodified lines434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222import osimport base64import jsonimport unicodedataimport fitzfrom PIL import Imagefrom io import BytesIOimport gradio as grimport numpy as npimport cv2from dotenv import load_dotenvfrom openai import OpenAIfrom typhoon_ocr import prepare_ocr_messagesfrom transformers import pipelineload_dotenv()openai = OpenAI(base_url=os.getenv("TYPHOON_BASE_URL"),api_key=os.getenv("TYPHOON_API_KEY"))TYPHOON_MODEL = os.getenv("TYPHOON_OCR_MODEL")translator = pipeline("translation_en_to_es", model="Helsinki-NLP/opus-mt-en-es")# ------------------------------# Utilidades# ------------------------------def clean_text(text):text = unicodedata.normalize("NFC", text)lines = text.splitlines()cleaned_lines = [line.strip() for line in lines if line.strip()]return "\n".join(cleaned_lines)def translate_text(text):if len(text.strip()) < 5:return textchunks = [text[i:i+500] for i in range(0, len(text), 500)]3 unmodified linestranslated.append(result[0]["translation_text"])return "\n".join(translated)# ------------------------------# OCR con Typhoon# ------------------------------def run_typhoon_ocr(image_path, task_type="default"):messages = prepare_ocr_messages(pdf_or_image_path=image_path,task_type=task_type,target_image_dim=1800,target_text_length=8000,page_num=1)response = openai.chat.completions.create(model=TYPHOON_MODEL,messages=messages,max_tokens=16384,extra_body={"repetition_penalty": 1.2,"temperature": 0.1,"top_p": 0.6,},)result = response.choices[0].message.contenttry:json_data = json.loads(result)natural_text = json_data.get("natural_text", "").replace("<figure>", "").replace("</figure>", "")except Exception:natural_text = resultreturn natural_text# ------------------------------# Extracción de imágenes embebidas# ------------------------------def extract_embedded_images(page, page_number, seen_xrefs):image_paths = []blocks = []for img_index, img in enumerate(page.get_images(full=True)):xref = img[0]if xref in seen_xrefs:continueseen_xrefs.add(xref)base_image = page.parent.extract_image(xref)image_bytes = base_image["image"]ext = base_image["ext"]image_path = f"/tmp/embedded_p{page_number + 1}_{img_index + 1}.{ext}"with open(image_path, "wb") as f:f.write(image_bytes)image_paths.append(image_path)blocks.append(f"\n")return blocks, image_paths# ------------------------------# Segmentación de regiones visuales# ------------------------------def extract_visual_regions(image, page_number):results = []np_img = np.array(image.convert("RGB"))gray = cv2.cvtColor(np_img, cv2.COLOR_RGB2GRAY)_, binary = cv2.threshold(gray, 220, 255, cv2.THRESH_BINARY_INV)closed = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_RECT, (15, 15)))num_labels, labels, stats, _ = cv2.connectedComponentsWithStats(closed, connectivity=8)for i in range(1, num_labels):x, y, w, h, area = stats[i]if area > 2000 and 0.3 < (w / float(h)) < 3.5:bbox = (x, y, x + w, y + h)crop = image.crop(bbox)crop_path = f"/tmp/visual_crop_p{page_number + 1}_{i}.jpg"crop.save(crop_path)results.append(crop_path)return results# ------------------------------# Procesamiento principal# ------------------------------def process_document(input_file, task_type, page_number):if not input_file:return None, "No file uploaded", Nonetemp_path = input_file.nameext = os.path.splitext(temp_path)[-1].lower()markdown_output = ""all_images = []seen_xrefs = set()if ext in [".png", ".jpg", ".jpeg"]:# Imagen únicatext = run_typhoon_ocr(temp_path, task_type)translated = translate_text(text)markdown_output += f"## Resultado OCR\n\n{translated}\n"return markdown_output, [], Nonedoc = fitz.open(temp_path)for i, page in enumerate(doc):if (i + 1) != page_number:continuemarkdown_output += f"\n## Página {i + 1}\n\n"text = page.get_text("text").strip()if len(text) > 30:# texto nativotranslated = translate_text(clean_text(text))markdown_output += translated + "\n"else:# escaneado -> render + OCRpix = page.get_pixmap(dpi=300)img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)image_path = f"/tmp/ocr_page_{i + 1}.jpg"img.save(image_path)all_images.append(image_path)markdown_output += f"\n\n"ocr_text = run_typhoon_ocr(image_path, task_type)translated = translate_text(ocr_text)markdown_output += translated + "\n"# Visual cropscrops = extract_visual_regions(img, i)for crop_path in crops:all_images.append(crop_path)markdown_output += f"\n"# Extraer imágenes embebidasblocks, embedded_images = extract_embedded_images(page, i, seen_xrefs)for block in blocks:markdown_output += blockall_images.extend(embedded_images)markdown_output += "\n---\n\n"# Guardar resultadomarkdown_path = "/tmp/resultado.md"with open(markdown_path, "w", encoding="utf-8") as f:f.write(markdown_output)return markdown_output.strip(), all_images, markdown_path# ------------------------------# Gradio UI# ------------------------------theme = gr.themes.Soft(primary_hue="indigo", secondary_hue="rose", neutral_hue="stone")with gr.Blocks(theme=theme) as demo:gr.Markdown("# Typhoon OCR + Imagen Extraction")with gr.Row():with gr.Column(scale=1):input_file = gr.File(label="Upload PDF or Image", file_types=[".pdf", ".png", ".jpg", ".jpeg"])task_dropdown = gr.Radio(["default", "structure"], label="Select Task", value="default")page_number = gr.Number(label="Page Number (PDF only)", value=1, minimum=1, step=1)run_button = gr.Button("Run OCR")with gr.Column(scale=2):markdown_output = gr.Textbox(label="Generated Markdown", lines=25, interactive=True)gallery_output = gr.Gallery(label="Extracted Images", type="file")download_md = gr.File(label="Download Markdown File")run_button.click(fn=process_document,inputs=[input_file, task_dropdown, page_number],outputs=[markdown_output, gallery_output, download_md])demo.launch()
app.py+162-148