""" ============================================================= EXTRACTOR DE MATERIALES N24 — PDFs → Excel (Web App) ============================================================= Servidor Gradio para Hugging Face Spaces. ============================================================= """ import gradio as gr import pdfplumber import re import os import tempfile import pandas as pd from openpyxl import Workbook from openpyxl.styles import Font, PatternFill, Alignment, Border, Side from openpyxl.utils import get_column_letter # ══════════════════════════════════════════════════════════════ # CATÁLOGO # ══════════════════════════════════════════════════════════════ def load_catalogo(catalogo_file): df = pd.read_excel(catalogo_file, dtype=str) df.columns = df.columns.str.strip() catalogo = {} for _, row in df.iterrows(): cod = str(row["Cod Mat"]).strip().zfill(8) desc = str(row["Descripción Material"]).strip() catalogo[cod] = desc return catalogo def get_desc(catalogo, cod_mat): return catalogo.get(str(cod_mat).strip().zfill(8), "") # ══════════════════════════════════════════════════════════════ # EXTRACCIÓN PDF # ══════════════════════════════════════════════════════════════ COD_RE = re.compile(r'\b(\d{7,8})\b') def extract_pdf(path, catalogo): meta = { "IDReg": "", "OS": "", "Terminal": "" } all_tables = [] with pdfplumber.open(path) as pdf: for page in pdf.pages: text = page.extract_text() or "" # ========================= # EXTRAER DATOS GENERALES # ========================= for line in text.splitlines(): l = line.strip() # ID REG if not meta["IDReg"]: m = re.search(r'ID\s*REG\s*:?\s*(\d+)', l, re.I) if m: meta["IDReg"] = m.group(1) # TERMINAL if not meta["Terminal"]: m = re.search(r'TERMINAL\s*:?\s*(\S+)', l, re.I) if m: meta["Terminal"] = m.group(1) # ========================= # OS o FOLIO # ========================= if not meta["OS"]: # Buscar primero "OS" m = re.search( r'\bOS\b\s*:?\s*([A-Z0-9/\-]+)', l, re.I ) # Si no encuentra OS, buscar FOLIO if not m: m = re.search( r'\bFOLIO\b\s*:?\s*([A-Z0-9/\-]+)', l, re.I ) # Guardar resultado if m: meta["OS"] = m.group(1).strip() # ========================= # EXTRAER TABLAS # ========================= tables = page.extract_tables() if tables: all_tables.extend(tables) seen = {} # ══════════════════════════════════════════════════════════ # RECORRER TABLAS # ══════════════════════════════════════════════════════════ for table in all_tables: if not table: continue for row in table: if not row: continue cells = [str(c).strip() if c else "" for c in row] cod_match = None cantidad = "" # ========================= # BUSCAR CODIGO MATERIAL # ========================= for i, cell in enumerate(cells): m = COD_RE.search(cell) if not m: continue cod_match = m.group(1).zfill(8) # ========================= # BUSCAR CANTIDAD # ========================= for j in range(i + 1, len(cells)): c = str(cells[j]).strip() # Ignorar vacíos if not c: continue # Solo enteros if re.fullmatch(r'\d+', c): valor = int(c) # Cantidades válidas if 0 < valor < 10000: cantidad = c break break # ══════════════════════════════════════════════ # OMITIR SI NO HAY CANTIDAD # ══════════════════════════════════════════════ if not cantidad: continue # OMITIR SI NO EXISTE EN CATÁLOGO desc = get_desc(catalogo, cod_match) if not desc: continue key = (meta["Terminal"], cod_match) if key not in seen: seen[key] = { "Cod Mat": cod_match, "Descripción Material": desc, "Cantidad": cantidad, "IDReg": meta["IDReg"], "OS": meta["OS"], "TERMINAL": meta["Terminal"], } return list(seen.values()), meta # ══════════════════════════════════════════════════════════════ # EXPORTAR EXCEL # ══════════════════════════════════════════════════════════════ def export_excel(all_rows, output_path): wb = Workbook() ws = wb.active ws.title = "Materiales Consolidado" header_font = Font( name="Calibri", bold=True, color="FFFFFF", size=11 ) header_fill = PatternFill( "solid", start_color="1F4E79" ) header_align = Alignment( horizontal="center", vertical="center", wrap_text=True ) data_font = Font( name="Calibri", size=10 ) alt_fill = PatternFill( "solid", start_color="D9E1F2" ) thin = Side( style="thin", color="BFBFBF" ) border = Border( left=thin, right=thin, top=thin, bottom=thin ) HEADERS = [ "Cod Mat", "Descripción Material", "Cantidad", "IDReg", "OS", "TERMINAL" ] COL_WIDTHS = [14, 52, 12, 12, 28, 18] # ENCABEZADOS for col_idx, (header, width) in enumerate(zip(HEADERS, COL_WIDTHS), start=1): cell = ws.cell(row=1, column=col_idx, value=header) cell.font = header_font cell.fill = header_fill cell.alignment = header_align cell.border = border ws.column_dimensions[get_column_letter(col_idx)].width = width ws.row_dimensions[1].height = 30 # DATOS for row_idx, r in enumerate(all_rows, start=2): use_alt = (row_idx % 2 == 0) for col_idx, key in enumerate(HEADERS, start=1): cell = ws.cell( row=row_idx, column=col_idx, value=r.get(key, "") ) cell.font = data_font cell.border = border cell.alignment = Alignment( horizontal="left" if col_idx == 2 else "center", vertical="center", wrap_text=(col_idx == 2) ) if use_alt: cell.fill = alt_fill ws.row_dimensions[row_idx].height = 18 ws.freeze_panes = "A2" wb.save(output_path) # ══════════════════════════════════════════════════════════════ # FUNCIÓN PRINCIPAL # ══════════════════════════════════════════════════════════════ def procesar(pdf_files, catalogo_file): if not pdf_files: return None, "⚠️ No subiste ningún PDF." if catalogo_file is None: return None, "⚠️ No subiste catálogo." try: catalogo = load_catalogo(catalogo_file) except Exception as e: return None, f"❌ Error catálogo: {e}" all_rows = [] log_lines = [ f"📂 PDFs recibidos: {len(pdf_files)}\n" ] for pdf_path in pdf_files: fname = os.path.basename(pdf_path) try: rows, meta = extract_pdf(pdf_path, catalogo) log_lines.append( f"✔ {fname}\n" f" IDReg={meta['IDReg']} " f"OS={meta['OS']} " f"Terminal={meta['Terminal']} " f"→ {len(rows)} materiales" ) all_rows.extend(rows) except Exception as e: log_lines.append( f"✘ ERROR en {fname}: {e}" ) log_lines.append( f"\n📊 Total filas generadas: {len(all_rows)}" ) if not all_rows: return ( None, "\n".join(log_lines) + "\n\n⚠️ No se encontraron materiales." ) # EXPORTAR with tempfile.NamedTemporaryFile( suffix=".xlsx", delete=False ) as tmp: output_path = tmp.name export_excel(all_rows, output_path) log_lines.append( "\n✅ Archivo generado con éxito." ) return output_path, "\n".join(log_lines) # ══════════════════════════════════════════════════════════════ # LOGIN # ══════════════════════════════════════════════════════════════ USUARIOS = { "admin": "C@rsoLPZ", "Julio": "1234567890", "Santana": "C@rso1234", } def check_login(usuario, password): return USUARIOS.get(usuario) == password # ══════════════════════════════════════════════════════════════ # INTERFAZ GRADIO # ══════════════════════════════════════════════════════════════ CSS = """ #title { text-align: center; margin-bottom: 4px; } #subtitle { text-align: center; color: #555; margin-bottom: 20px; } .gr-button-primary { background: #1F4E79 !important; } #login-box { max-width: 360px; margin: 80px auto; padding: 32px; border: 1px solid #ddd; border-radius: 12px; } """ with gr.Blocks(css=CSS, title="Extractor N24") as demo: logged_in = gr.State(False) # LOGIN with gr.Column( elem_id="login-box", visible=True ) as login_panel: gr.Markdown("## 🔐 Iniciar sesión") usr_input = gr.Textbox( label="Usuario" ) pwd_input = gr.Textbox( label="Contraseña", type="password" ) login_btn = gr.Button( "Entrar", variant="primary" ) login_err = gr.Markdown( "", visible=False ) # APP with gr.Column( visible=False ) as main_panel: gr.Markdown( "# 📄 Extractor de Materiales N24", elem_id="title" ) gr.Markdown( "Sube PDFs y catálogo Excel." ) with gr.Row(): with gr.Column(scale=1): pdf_input = gr.File( label="📑 PDFs", file_types=[".pdf"], file_count="multiple" ) catalogo_input = gr.File( label="📋 Catálogo", file_types=[".xlsx"], file_count="single" ) btn = gr.Button( "🚀 Procesar", variant="primary" ) with gr.Column(scale=1): output_file = gr.File( label="⬇️ Descargar" ) log_output = gr.Textbox( label="📝 Log", lines=18, interactive=False ) btn.click( fn=procesar, inputs=[pdf_input, catalogo_input], outputs=[output_file, log_output] ) # LOGIN LOGIC def do_login(usuario, password): if check_login(usuario, password): return ( gr.update(visible=False), gr.update(visible=True), gr.update(visible=False), True ) return ( gr.update(visible=True), gr.update(visible=False), gr.update( visible=True, value="❌ Usuario o contraseña incorrectos." ), False ) login_btn.click( fn=do_login, inputs=[usr_input, pwd_input], outputs=[ login_panel, main_panel, login_err, logged_in ], ) demo.launch()