Spaces:
Sleeping
Sleeping
Update app.py
Browse files6 unmodified lines78910111213147 unmodified lines22232425262728293031323332 unmodified lines666768697071727 unmodified lines80818283848586878889909192939495967 unmodified lines10410510610710810911024 unmodified lines13513613713813914014114 unmodified lines1561571581591601611621631641651663 unmodified lines17017117217317417517617717817918018123 unmodified lines2052062072086 unmodified linesimport base64import osimport unicodedata# NUEVO: Traducciónfrom transformers import pipeline# Inicializa el pipeline de traducción EN->ES una sola vez7 unmodified linescleaned_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)]32 unmodified linesgray = 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):7 unmodified lines# ---------- 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 = 17 unmodified linesfor 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))24 unmodified linesis_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 = y14 unmodified linestext = 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)3 unmodified linesmarkdown_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):23 unmodified linessubmit_btn.click(fn=convert, inputs=[pdf_input], outputs=[markdown_output, gallery_output, download_md])demo.launch()6 unmodified lines789101112137 unmodified lines2122232425262728293031323334353637383940414243444546474849505152535455565758596061626332 unmodified lines969798991001017 unmodified lines1091101111121131147 unmodified lines12212312412512612712824 unmodified lines15315415515615715815916016114 unmodified lines1761771781791801811821831843 unmodified lines18818919019119219319419519619719819920023 unmodified lines2242252262276 unmodified linesimport base64import osimport unicodedataimport refrom transformers import pipeline# Inicializa el pipeline de traducción EN->ES una sola vez7 unmodified linescleaned_lines = [line.strip() for line in lines if line.strip()]return "\n".join(cleaned_lines)def fix_common_ocr_errors(text):text = text.replace(" e ", " • ") # cuando OCR confunde viñetas con "e"text = re.sub(r'\bposibl\b', 'posible', text, flags=re.IGNORECASE)text = re.sub(r'\binstatar\b', 'instalar', text)text = re.sub(r'\bfuncionación\b', 'función taller', text)text = re.sub(r'\boptar\b', 'opta', text)text = re.sub(r'ICACIONES\b', 'APLICACIONES', text)text = re.sub(r'Lar\b', 'la', text)text = re.sub(r'([a-zA-Z])-\n([a-zA-Z])', r'\1\2', text) # une palabras partidas por saltoreturn textdef format_text_to_markdown(text):lines = text.splitlines()final_lines = []for line in lines:line = line.strip()if not line:continueif re.match(r"^(posible causa|causa):", line, re.IGNORECASE):final_lines.append("### 🛑 Posible causa")final_lines.append("")final_lines.append(re.sub(r"^(posible causa|causa):", "", line, flags=re.IGNORECASE).strip())elif re.match(r"^(posible solución|solución):", line, re.IGNORECASE):final_lines.append("### ✅ Posible solución")final_lines.append("")final_lines.append(re.sub(r"^(posible solución|solución):", "", line, flags=re.IGNORECASE).strip())elif re.match(r"^descripción del problema", line, re.IGNORECASE):final_lines.append("### 📝 Descripción del problema")elif re.match(r"^\d+\.", line):final_lines.append("- " + line)elif re.match(r"^•\s*", line):final_lines.append("- " + line)else:final_lines.append(line)return "\n".join(final_lines)def translate_text(text):if len(text.strip()) < 5:return textchunks = [text[i:i+500] for i in range(0, len(text), 500)]32 unmodified linesgray = 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):7 unmodified lines# ---------- Extracción de texto + imágenes ----------def extract_text_markdown(doc, image_paths, page_index, seen_xrefs):markdown_output = f"\n## Página {page_index + 1}\n\n"image_counter = 17 unmodified linesfor line in b["lines"]:line_y = line["bbox"][1]line_text = " ".join([span["text"] for span in line["spans"]]).strip()line_text = clean_ocr_text(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))24 unmodified linesis_header = font_size >= 14if previous_y is not None and abs(y - previous_y) > 10:markdown_output += "\n"fixed = fix_common_ocr_errors(text.strip())formatted = format_text_to_markdown(fixed)translated = translate_text(formatted)markdown_output += f"\n### {translated}\n" if is_header else translated + "\n"previous_y = y14 unmodified linestext = page.get_text("text").strip()if len(text) > 30:extracted = extract_text_markdown([page], image_paths, page_num, seen_xrefs)markdown_output += extracted + "\n"else:markdown_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)3 unmodified linesmarkdown_output += f"\n"try:ocr_text = pytesseract.image_to_string(img, lang="spa", config="--oem 3 --psm 6")except pytesseract.TesseractError:ocr_text = ""ocr_text_clean = clean_ocr_text(fix_common_ocr_errors(ocr_text))formatted = format_text_to_markdown(ocr_text_clean)translated = translate_text(formatted)markdown_output += translated + "\n"crops = extract_visual_regions(img)for i, crop in enumerate(crops):23 unmodified linessubmit_btn.click(fn=convert, inputs=[pdf_input], outputs=[markdown_output, gallery_output, download_md])demo.launch()
app.py+47-28