Spaces:
Sleeping
Sleeping
Download src/streamlit_app.py from JulinTech/robo-previd: direct link, hf CLI and curl.
- Browser
- Download file 7.41 kB
-
https://huggingface.co/spaces/JulinTech/robo-previd/resolve/main/src/streamlit_app.py
- Command line
-
hf download hf://spaces/JulinTech/robo-previd/src/streamlit_app.py
-
curl -L -o streamlit_app.py https://huggingface.co/spaces/JulinTech/robo-previd/resolve/main/src/streamlit_app.py
7.41 kB
| import os | |
| # Caminho fixo para a pasta .streamlit no projeto | |
| custom_config_dir = os.path.join(os.path.dirname(__file__), ".streamlit") | |
| # Garante que a pasta existe | |
| os.makedirs(custom_config_dir, exist_ok=True) | |
| # Define as variáveis de ambiente para forçar o Streamlit usar essa pasta | |
| os.environ["STREAMLIT_CONFIG_DIR"] = custom_config_dir | |
| os.environ["STREAMLIT_RUNTIME_DIR"] = custom_config_dir | |
| import streamlit as st | |
| import pdfplumber | |
| import re | |
| from openpyxl import load_workbook | |
| from openpyxl.utils import get_column_letter | |
| # ---------------- CONFIG ---------------- | |
| ARQ_MODELO = "Base - 1º Grau Previd.xlsx" # modelo no repo | |
| SAIDA = "Base - 1º Grau Previd_preenchido.xlsx" | |
| UPLOAD_DIR = "/tmp" # pasta com permissão de escrita no Hugging Face | |
| # ---------------- utils ---------------- | |
| def normalize_code(s): | |
| if s is None: | |
| return "" | |
| return re.sub(r"\D", "", str(s)) | |
| def to_float(numstr): | |
| s = str(numstr).strip() | |
| if s == "": | |
| return 0.0 | |
| s = s.replace("R$", "").replace(" ", "") | |
| s = s.replace(".", "").replace(",", ".") | |
| try: | |
| return float(s) | |
| except: | |
| return 0.0 | |
| # ---------------- extração PDF1 ---------------- | |
| def extrair_rpps_previd_pdf1(pdf_path): | |
| dados = {} | |
| capturando = False | |
| bloco_capturado = False | |
| with pdfplumber.open(pdf_path) as pdf: | |
| for pagina in pdf.pages: | |
| texto = pagina.extract_text() or "" | |
| for linha in texto.split("\n"): | |
| if "RPPS - PREVID" in linha and not bloco_capturado: | |
| capturando = True | |
| continue | |
| if not capturando: | |
| continue | |
| if linha.strip() == "" or "TOTAIS" in linha: | |
| if "TOTAIS GRUPO" in linha or "TOTAL GERAL" in linha: | |
| capturando = False | |
| bloco_capturado = True | |
| continue | |
| m = re.match(r"^(\d{3,8}\s*-\s*[^0-9]+)(.*)$", linha) | |
| if m: | |
| chave = m.group(1).strip() | |
| valores_str = m.group(2).strip() | |
| nums = re.findall(r"-?[\d\.,]+", valores_str) | |
| valores = [to_float(n) for n in nums] | |
| while len(valores) < 7: | |
| valores.append(0.0) | |
| dados[chave] = valores[:7] | |
| return dados | |
| # ---------------- extração PDF2 ---------------- | |
| def extrair_rpps_previd_pdf2(pdf_path): | |
| dados = {} | |
| with pdfplumber.open(pdf_path) as pdf: | |
| capturando = False | |
| current_code = None | |
| for pagina in pdf.pages: | |
| texto = pagina.extract_text() or "" | |
| for linha in texto.split("\n"): | |
| if "RPPS - PREVID" in linha: | |
| capturando = True | |
| current_code = None | |
| continue | |
| if not capturando: | |
| continue | |
| if "TOTAL CENTRO DE CUSTO" in linha or "TOTAL GERAL" in linha: | |
| capturando = False | |
| current_code = None | |
| break | |
| mcode = re.match(r"^\s*(\d{2,8})\s*-\s*(.+)$", linha) | |
| if mcode: | |
| current_code = mcode.group(1).strip() | |
| nums = re.findall(r"-?[\d\.,]+", linha) | |
| if nums: | |
| candidatos = [n for n in nums if (',' in n or '.' in n)] | |
| raw = candidatos[-1] if candidatos else nums[-1] | |
| dados[current_code] = to_float(raw) | |
| current_code = None | |
| continue | |
| nums = re.findall(r"-?[\d\.,]+", linha) | |
| if nums and current_code: | |
| candidatos = [n for n in nums if (',' in n or '.' in n)] | |
| raw = candidatos[-1] if candidatos else nums[-1] | |
| dados[current_code] = to_float(raw) | |
| current_code = None | |
| continue | |
| return dados | |
| # ---------------- preencher Excel ---------------- | |
| def preencher_planilha(modelo_path, dados_pdf1, dados_pdf2): | |
| wb = load_workbook(modelo_path, keep_vba=True) | |
| # Aba PDF1 | |
| if "PDF1" not in wb.sheetnames: | |
| raise Exception("Aba 'PDF1' não encontrada no modelo.") | |
| ws_pdf1 = wb["PDF1"] | |
| for row in ws_pdf1.iter_rows(min_row=2, max_row=ws_pdf1.max_row): | |
| for cell in row: | |
| cell.value = None | |
| row_pdf1 = 2 | |
| for chave, valores in dados_pdf1.items(): | |
| ws_pdf1[f"A{row_pdf1}"] = chave | |
| for i, val in enumerate(valores): | |
| col = get_column_letter(2 + i) | |
| ws_pdf1[f"{col}{row_pdf1}"] = val | |
| row_pdf1 += 1 | |
| # Primeira aba → preenche P com base em O | |
| ws = wb[wb.sheetnames[0]] | |
| report = [] | |
| matched = 0 | |
| total_rows = 0 | |
| for row in range(2, 201): | |
| raw_cell = ws[f"O{row}"].value | |
| if raw_cell is None: | |
| continue | |
| total_rows += 1 | |
| codigo_o = normalize_code(str(raw_cell)) | |
| if codigo_o == "": | |
| report.append((row, raw_cell, codigo_o, False, None)) | |
| elif codigo_o in dados_pdf2: | |
| ws[f"P{row}"] = dados_pdf2[codigo_o] | |
| report.append((row, raw_cell, codigo_o, True, dados_pdf2[codigo_o])) | |
| matched += 1 | |
| else: | |
| report.append((row, raw_cell, codigo_o, False, None)) | |
| if "Relatorio_PDF2" in wb.sheetnames: | |
| del wb["Relatorio_PDF2"] | |
| rpt = wb.create_sheet("Relatorio_PDF2") | |
| headers = ["Row", "O_valor_original", "Codigo_normalizado", "Encontrou_no_PDF2", "Valor_PDF2"] | |
| rpt.append(headers) | |
| for linha in report: | |
| rpt.append(linha) | |
| out_path = os.path.join(UPLOAD_DIR, SAIDA) | |
| wb.save(out_path) | |
| return out_path, matched, total_rows | |
| # ---------------- STREAMLIT ---------------- | |
| st.set_page_config(page_title="Robô Previd", layout="centered") | |
| st.title("🤖 Robô Previd - Processamento de PDFs") | |
| st.markdown("Suba os dois PDFs (Consolidado e Consignado). O arquivo modelo deve estar presente no repositório do Space.") | |
| pdf1 = st.file_uploader("Envie o PDF 1 (Consolidado do 1º Grau)", type=["pdf"]) | |
| pdf2 = st.file_uploader("Envie o PDF 2 (Consignado detalhado do 1º Grau)", type=["pdf"]) | |
| if pdf1 and pdf2: | |
| st.info("Processando arquivos... aguarde alguns segundos.") | |
| try: | |
| # salva os arquivos no /tmp antes de abrir | |
| pdf1_path = os.path.join(UPLOAD_DIR, pdf1.name) | |
| pdf2_path = os.path.join(UPLOAD_DIR, pdf2.name) | |
| with open(pdf1_path, "wb") as f: | |
| f.write(pdf1.getbuffer()) | |
| with open(pdf2_path, "wb") as f: | |
| f.write(pdf2.getbuffer()) | |
| dados1 = extrair_rpps_previd_pdf1(pdf1_path) | |
| dados2 = extrair_rpps_previd_pdf2(pdf2_path) | |
| if not os.path.exists(ARQ_MODELO): | |
| st.error(f"Modelo não encontrado no repo: {ARQ_MODELO}") | |
| else: | |
| out_path, matched, total_rows = preencher_planilha(ARQ_MODELO, dados1, dados2) | |
| st.success("✅ Processado com sucesso!") | |
| st.write(f"PDF2: códigos encontrados = {matched} / {total_rows}") | |
| with open(out_path, "rb") as f: | |
| st.download_button("📥 Baixar planilha preenchida", f, file_name=SAIDA, mime="application/vnd.ms-excel.sheet.macroEnabled.12") | |
| except Exception as e: | |
| st.error(f"Erro ao processar: {e}") | |