Spaces:
Sleeping
Sleeping
File size: 14,648 Bytes
f3c876b a83f165 f3c876b a83f165 f3c876b a83f165 f3c876b a83f165 f3c876b a83f165 f3c876b a83f165 f3c876b a83f165 f3c876b a83f165 f3c876b a83f165 f3c876b a83f165 f3c876b 416f9a8 f3c876b a83f165 0128913 a83f165 f3c876b a83f165 f3c876b a83f165 f3c876b 416f9a8 a83f165 f3c876b a83f165 f3c876b 416f9a8 f3c876b a83f165 416f9a8 a83f165 f3c876b 416f9a8 f3c876b a83f165 416f9a8 a83f165 f3c876b 416f9a8 455224e af24194 455224e 0bdd895 455224e af24194 455224e af24194 455224e af24194 455224e af24194 455224e 416f9a8 0128913 416f9a8 a83f165 f3c876b 416f9a8 a83f165 416f9a8 a83f165 416f9a8 a83f165 416f9a8 a83f165 416f9a8 a83f165 416f9a8 a83f165 416f9a8 a83f165 416f9a8 a83f165 416f9a8 a83f165 416f9a8 a83f165 416f9a8 a83f165 416f9a8 0128913 416f9a8 f3c876b a83f165 f3c876b a83f165 f3c876b a83f165 f3c876b a83f165 f3c876b a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 0128913 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 0128913 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 0128913 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 f3c876b a83f165 f3c876b f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f4b9df5 a83f165 f3c876b a83f165 f4b9df5 a83f165 f3c876b f4b9df5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 | """
=============================================================
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()
|