Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files30 unmodified lines313233343435363637383910 unmodified lines505152535354555656 unmodified lines1131141151161171181191201211221231241251261271281291301311321331221341351361371381281391301311321331341401411421431441457 unmodified lines15315415515615715815916016116216316416516615415515615715815916016116216316416716816914 unmodified lines1841851861851871881891 unmodified line19119219319319419519619719719819920020120220420320420520820620720820921021421121221321421522021621721821922022622122222322423022522622723422822923623023123924023223323423512 unmodified lines2482492502592512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822662832842682852862702872882892909 unmodified lines30030130228630330430530630730830929331031129629729829930030130230331231331431531630531731830730830931031131231331431531631731831932032132232332432532632732832933033133233331932032132232332432533833934034134234334434534634732632732832935133033133235433333435735835936036136236336433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736830 unmodified lines width: 100%; } .stTabs [data-baseweb="tab"] { font-size: 1rem; font-size: 0.95rem; font-weight: 600; padding: 0.5rem 1rem; padding: 0.4rem 0.6rem; }</style>""", unsafe_allow_html=True)10 unmodified linesst.markdown("---")
# ------------------------------------------------------------------ ## Fonctions utilitaires# Utilitaires# ------------------------------------------------------------------ #
DATE_RE = re.compile(r'\b(\d{1,2}[/\-\.]\d{1,2}[/\-\.]\d{2,4})\b')56 unmodified lines df["date_aff"] = df[date_col].astype(str) if date_col else datetime.now().strftime("%d/%m/%Y") return df
def parse_csv_bytes(data): for enc in ["utf-8", "latin-1"]: try: texte = data.decode(enc) df = parse_csv_texte(texte) if df is not None: return df, None except: continue return None, "Impossible de lire ce fichier CSV."
def lire_pdf_bytes(data): try: import pdfplumber rows = [] textes_bruts = [] with pdfplumber.open(io.BytesIO(data)) as pdf: for page in pdf.pages: # Essai extraction tableaux tables = page.extract_tables() for table in tables: for row in table: if row and any(cell for cell in row if cell): rows.append(row) # Si pas de tableau, texte brut if not tables: texte = page.extract_text() if texte: df = parse_texte_brut(texte) if df is not None: return df, None t = page.extract_text() if t: textes_bruts.append(t)
if rows: headers = [str(h).strip().lower() if h else "col"+str(i) for i, h in enumerate(rows[0])]7 unmodified lines df["date_aff"] = df[date_col].astype(str) if date_col else datetime.now().strftime("%d/%m/%Y") return df, None
if textes_bruts: df = parse_texte_brut("\n".join(textes_bruts)) if df is not None: return df, None
return None, "Aucune donnée trouvée dans ce PDF." except ImportError: return None, "pdfplumber non installé." except Exception as e: return None, "Erreur : " + str(e)
def lire_csv_bytes(data): for enc in ["utf-8", "latin-1"]: try: texte = data.decode(enc) df = parse_csv_texte(texte) if df is not None: return df, None except: continue return None, "Impossible de lire ce fichier CSV."
def normaliser(df, source): df = df.copy() if "date_aff" not in df.columns:14 unmodified lines pdf.ln(6) pdf.line(10, pdf.get_y(), 200, pdf.get_y()) pdf.ln(6)
pdf.set_font("Helvetica", "B", 15) pdf.cell(0, 10, "FACTURE", ln=1, align="C") num_fact = "FACT-" + datetime.now().strftime("%Y%m") + "-" + str(numero).zfill(4)1 unmodified line pdf.cell(0, 6, "N : " + num_fact, ln=1, align="C") pdf.cell(0, 6, "Date : " + str(row.get("date_aff", datetime.now().strftime("%d/%m/%Y"))), ln=1, align="C") pdf.ln(8)
pdf.set_font("Helvetica", "B", 11) pdf.cell(0, 8, "Facture a : " + str(row["client"]), ln=1) pdf.ln(6)
pdf.set_fill_color(240, 240, 240) pdf.set_font("Helvetica", "B", 10) pdf.cell(100, 9, "Description", 1, fill=True) pdf.cell(45, 9, "Montant HT", 1, align="R", fill=True) pdf.cell(45, 9, "TVA " + str(tva_rate) + "%", 1, align="R", fill=True) pdf.ln(9)
montant_ht = round(row["montant"] / (1 + tva_rate / 100), 2) if tva_rate > 0 else round(row["montant"], 2) montant_tva = round(row["montant"] - montant_ht, 2) montant_ttc = round(row["montant"], 2)
pdf.set_font("Helvetica", "", 10) pdf.cell(100, 9, "Prestation de services", 1) pdf.cell(45, 9, str(montant_ht) + " EUR", 1, align="R") pdf.cell(45, 9, str(montant_tva) + " EUR", 1, align="R") pdf.ln(12)
pdf.set_font("Helvetica", "B", 12) pdf.set_fill_color(220, 240, 220) pdf.cell(145, 11, "TOTAL TTC", 1, fill=True) pdf.cell(45, 11, str(montant_ttc) + " EUR", 1, align="R", fill=True) pdf.ln(20)
pdf.set_font("Helvetica", "I", 9) pdf.set_text_color(120, 120, 120) pdf.cell(0, 6, "Facture payable sous 30 jours. Merci pour votre confiance.", ln=1) return bytes(pdf.output())
def afficher_resultats(encaissements):def afficher_resultats(encaissements, cle): st.markdown("---") st.success("💰 " + str(len(encaissements)) + " encaissements détectés") st.subheader("Sélectionnez les lignes")
selections = [] for i, row in encaissements.iterrows(): label = "[" + str(row["source"]) + "] " + str(row["client"]) + " — " + str(round(row["montant"], 2)) + " € (" + str(row["date_aff"]) + ")" if st.checkbox(label, value=True, key="chk_" + str(i)): if st.checkbox(label, value=True, key=cle + "_chk_" + str(i)): selections.append(i)
st.markdown("---") st.write(str(len(selections)) + " facture(s) sélectionnée(s)")
if st.button("🚀 Générer " + str(len(selections)) + " facture(s)", type="primary", use_container_width=True): if st.button("🚀 Générer " + str(len(selections)) + " facture(s)", type="primary", use_container_width=True, key=cle + "_gen"): if not selections: st.warning("Veuillez sélectionner au moins une ligne.") else:12 unmodified lines data=zip_buffer.getvalue(), file_name="factures_" + datetime.now().strftime("%Y%m%d_%H%M") + ".zip", mime="application/zip", use_container_width=True use_container_width=True, key=cle + "_dl" )
def multi_texte_ui(cle_base, placeholder): if cle_base + "_nb" not in st.session_state: st.session_state[cle_base + "_nb"] = 1 textes = [] for i in range(st.session_state[cle_base + "_nb"]): t = st.text_area( "Relevé " + str(i + 1), height=150, key=cle_base + "_txt_" + str(i), placeholder=placeholder ) textes.append(t) col1, col2 = st.columns(2) with col1: if st.button("➕ Ajouter un relevé", use_container_width=True, key=cle_base + "_add"): st.session_state[cle_base + "_nb"] += 1 st.rerun() with col2: if st.session_state[cle_base + "_nb"] > 1: if st.button("➖ Supprimer le dernier", use_container_width=True, key=cle_base + "_del"): st.session_state[cle_base + "_nb"] -= 1 st.rerun() return textes
# ------------------------------------------------------------------ ## Onglets# ------------------------------------------------------------------ #
tab1, tab2 = st.tabs(["📁 Upload fichier (PC)", "📋 Copier-coller (Mobile)"])tab1, tab2, tab3 = st.tabs(["📁 Upload PC", "📋 Texte PDF mobile", "📊 CSV mobile"])
# --- Onglet 1 : Upload ---# --- Onglet 1 : Upload fichier (PC) ---with tab1: st.caption("Déposez un ou plusieurs fichiers PDF ou CSV") st.caption("Glissez-déposez vos fichiers PDF ou CSV (sur PC uniquement)") uploaded_files = st.file_uploader( "Choisissez vos relevés", type=["pdf", "csv"],9 unmodified lines if nom.lower().endswith(".pdf"): df, err = lire_pdf_bytes(data) else: df, err = lire_csv_bytes(data) df, err = parse_csv_bytes(data) if err: st.warning("⚠️ " + nom + " : " + err) elif df is not None: df = normaliser(df, nom) tous_df.append(df) st.success("✅ " + nom + " : " + str(len(df)) + " lignes")
if tous_df: combined = pd.concat(tous_df, ignore_index=True) encaissements = combined[combined["montant"] > 0].copy().reset_index(drop=True) if encaissements.empty: st.warning("Aucun encaissement trouvé.") else: st.session_state["enc_upload"] = encaissements
if "enc_upload" in st.session_state: afficher_resultats(st.session_state["enc_upload"]) enc = combined[combined["montant"] > 0].copy().reset_index(drop=True) st.session_state["enc_upload"] = enc if not enc.empty else None if st.session_state.get("enc_upload") is not None: afficher_resultats(st.session_state["enc_upload"], "upload")
# --- Onglet 2 : Copier-coller ---# --- Onglet 2 : Texte brut PDF (Mobile) ---with tab2: st.caption("Sur mobile : ouvrez votre PDF → Sélectionner tout → Copier → Collez ici")
if "nb_rel" not in st.session_state: st.session_state["nb_rel"] = 1
textes = [] for i in range(st.session_state["nb_rel"]): t = st.text_area( "Relevé " + str(i + 1), height=150, key="txt_" + str(i), placeholder="Collez le texte de votre relevé ici...\n\nEx:\n02/01/2024 VIR DUPONT MARTIN 1 250,00\n05/01/2024 VIR LEBLANC SARL 890,50" ) textes.append(t)
col1, col2 = st.columns(2) with col1: if st.button("➕ Ajouter", use_container_width=True): st.session_state["nb_rel"] += 1 st.rerun() with col2: if st.session_state["nb_rel"] > 1: if st.button("➖ Supprimer", use_container_width=True): st.session_state["nb_rel"] -= 1 st.rerun()
if st.button("📊 Analyser le texte", type="secondary", use_container_width=True, key="btn_texte"): st.caption("Ouvrez votre PDF → Sélectionner tout → Copier → Collez ici") textes = multi_texte_ui("pdf", "Collez le texte de votre relevé PDF ici...\n\nEx:\n02/01/2024 VIR DUPONT MARTIN 1 250,00\n05/01/2024 VIR LEBLANC SARL 890,50") if st.button("📊 Analyser le texte PDF", type="secondary", use_container_width=True, key="btn_pdf"): tous_df = [] for i, texte in enumerate(textes): if not texte.strip(): continue # Essai CSV puis texte brut df = None premiere = texte.strip().split("\n")[0] if ";" in premiere or premiere.count(",") > 2: try: df = parse_csv_texte(texte) except: pass if df is None: df = parse_texte_brut(texte) df = parse_texte_brut(texte) if df is not None and not df.empty: df = normaliser(df, "Relevé " + str(i + 1)) tous_df.append(df) st.success("✅ Relevé " + str(i + 1) + " : " + str(len(df)) + " lignes trouvées") st.success("✅ Relevé " + str(i + 1) + " : " + str(len(df)) + " lignes") else: st.warning("Relevé " + str(i + 1) + " : aucune ligne date+montant trouvée.")
if tous_df: combined = pd.concat(tous_df, ignore_index=True) encaissements = combined[combined["montant"] > 0].copy().reset_index(drop=True) if encaissements.empty: st.warning("Aucun encaissement trouvé.") else: st.session_state["enc_texte"] = encaissements
if "enc_texte" in st.session_state: afficher_resultats(st.session_state["enc_texte"]) enc = combined[combined["montant"] > 0].copy().reset_index(drop=True) st.session_state["enc_pdf"] = enc if not enc.empty else None if st.session_state.get("enc_pdf") is not None: afficher_resultats(st.session_state["enc_pdf"], "pdf")
# --- Onglet 3 : CSV texte (Mobile) ---with tab3: st.caption("Ouvrez votre fichier CSV → Copiez le contenu → Collez ici") with st.expander("💡 Format CSV attendu"): st.code("Date;Libelle;Montant\n02/01/2024;VIR DUPONT MARTIN;1250,00\n05/01/2024;VIR LEBLANC SARL;890,50", language="text") textes_csv = multi_texte_ui("csv", "Collez ici le contenu de votre fichier CSV...\n\nEx:\nDate;Libelle;Montant\n02/01/2024;VIR DUPONT;1250,00") if st.button("📊 Analyser le CSV", type="secondary", use_container_width=True, key="btn_csv"): tous_df = [] for i, texte in enumerate(textes_csv): if not texte.strip(): continue try: df = parse_csv_texte(texte) if df is not None and not df.empty: df = normaliser(df, "CSV " + str(i + 1)) tous_df.append(df) st.success("✅ CSV " + str(i + 1) + " : " + str(len(df)) + " lignes") else: st.warning("CSV " + str(i + 1) + " : colonne montant introuvable.") except Exception as e: st.warning("CSV " + str(i + 1) + " : erreur — " + str(e)) if tous_df: combined = pd.concat(tous_df, ignore_index=True) enc = combined[combined["montant"] > 0].copy().reset_index(drop=True) st.session_state["enc_csv"] = enc if not enc.empty else None if st.session_state.get("enc_csv") is not None: afficher_resultats(st.session_state["enc_csv"], "csv")
st.caption("FactureAuto — Hugging Face Spaces")src/streamlit_app.py+98-96