Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files33 unmodified lines343536373839403 unmodified lines444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612741 unmodified lines16917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524633 unmodified lines""", unsafe_allow_html=True)st.title("📄 FactureAuto")st.caption("Relevés bancaires PDF → Factures PDF")with st.expander("🏢 Paramètres société", expanded=False):company_name = st.text_input("Nom de la société", "Ma Société SARL")3 unmodified linesst.markdown("---")def extraire_client(libelle):lib = str(libelle).upper()lib = re.sub(r'\b(VIR(EMENT)?|PRLV|SEPA|RECU|DE|LA|LE|LES|PAR|POUR|VIREMENT)\b', ' ', lib)match = re.search(r'([A-Z][A-Z\s]{3,})', lib)return match.group(1).strip()[:35] if match else "Client inconnu"def extraire_montant(valeur):if valeur is None:return Nones = str(valeur).replace("\xa0", "").replace(" ", "").replace(",", ".")s = re.sub(r'[^\d.\-]', '', s)try:return float(s)except:return Nonedef lire_pdf(fichier_bytes):try:import pdfplumberrows = []with pdfplumber.open(io.BytesIO(fichier_bytes)) as pdf:for page in pdf.pages: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)if not rows:return None, "Aucun tableau trouvé dans ce PDF. Essayez le mode texte brut."# Première ligne = en-têtesheaders = [str(h).strip().lower() if h else "col" + str(i) for i, h in enumerate(rows[0])]data = rows[1:]df = pd.DataFrame(data, columns=headers)return df, Noneexcept ImportError:return None, "pdfplumber non installé. Ajoutez 'pdfplumber' dans requirements.txt"except Exception as e:return None, "Erreur lecture PDF : " + str(e)def normaliser_df(df, source):montant_col = next((c for c in df.columns if any(k in c for k in ["montant", "amount", "credit", "crédit", "debit", "débit", "solde"])),None)if montant_col is None:# Cherche la colonne avec le plus de valeurs numériquesfor col in df.columns:vals = df[col].apply(extraire_montant).dropna()if len(vals) > len(df) * 0.5:montant_col = colbreakif montant_col is None:return None, "Colonne montant introuvable. Colonnes : " + str(list(df.columns))df["montant"] = df[montant_col].apply(extraire_montant)lib_col = next((c for c in df.columns if any(k in c for k in ["libelle", "libellé", "description", "label", "motif", "operation", "opération"])),None)date_col = next((c for c in df.columns if "date" in c or "jour" in c),None)df["client"] = df[lib_col].apply(extraire_client) if lib_col else "Client inconnu"df["date_aff"] = df[date_col].astype(str) if date_col else datetime.now().strftime("%d/%m/%Y")df["source"] = sourcereturn df, Nonedef generer_facture(row, numero):pdf = FPDF()pdf.add_page()pdf.set_font("Helvetica", "B", 18)pdf.cell(0, 12, company_name, ln=1, align="C")pdf.set_font("Helvetica", "", 10)41 unmodified linespdf.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())# --- Upload PDF ---st.subheader("📤 Chargez vos relevés bancaires (PDF)")uploaded_files = st.file_uploader("Déposez un ou plusieurs fichiers PDF",type=["pdf"],accept_multiple_files=True)if uploaded_files:tous_df = []for fichier in uploaded_files:with st.spinner("Lecture de " + fichier.name + "..."):df, err = lire_pdf(fichier.read())if err:st.warning("⚠️ " + fichier.name + " : " + err)continuedf, err2 = normaliser_df(df, fichier.name)if err2:st.warning("⚠️ " + fichier.name + " : " + err2)continuetous_df.append(df)st.success("✅ " + fichier.name + " lu avec succès")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 (montant positif) trouvé dans les fichiers.")st.stop()st.markdown("---")st.success("💰 " + str(len(encaissements)) + " encaissements trouvés au total")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)):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 not selections:st.warning("Veuillez sélectionner au moins une ligne.")else:zip_buffer = io.BytesIO()with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zip_file:for i, idx in enumerate(selections, start=1):row = encaissements.loc[idx].to_dict()pdf_bytes = generer_facture(row, i)client_safe = re.sub(r'[^A-Za-z0-9_-]', '_', str(row["client"])[:20])fname = "FACT_" + client_safe + "_" + datetime.now().strftime("%Y%m%d") + ".pdf"zip_file.writestr(fname, pdf_bytes)zip_buffer.seek(0)st.success("✅ " + str(len(selections)) + " facture(s) générée(s) !")st.download_button(label="📥 Télécharger les factures (ZIP)",data=zip_buffer.getvalue(),file_name="factures_" + datetime.now().strftime("%Y%m%d_%H%M") + ".zip",mime="application/zip",use_container_width=True)else:st.info("👆 Déposez un ou plusieurs relevés PDF pour commencer.")st.caption("FactureAuto — Version mobile Hugging Face")33 unmodified lines343536373839403 unmodified lines444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815941 unmodified lines20120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730833 unmodified lines""", unsafe_allow_html=True)st.title("📄 FactureAuto")st.caption("Relevés bancaires → Factures PDF")with st.expander("🏢 Paramètres société", expanded=False):company_name = st.text_input("Nom de la société", "Ma Société SARL")3 unmodified linesst.markdown("---")# ------------------------------------------------------------------ ## Parsing intelligent du texte brut copié depuis un PDF bancaire# ------------------------------------------------------------------ #DATE_RE = re.compile(r'\b(\d{1,2}[/\-\.]\d{1,2}[/\-\.]\d{2,4})\b')MONTANT_RE = re.compile(r'([+\-]?\s?\d{1,3}(?:[\s\u00a0]\d{3})*(?:[,\.]\d{1,2})?)\s*€?')def extraire_client(texte):t = str(texte).upper()t = re.sub(r'\b(VIR(EMENT)?|PRLV|SEPA|RECU|CARTE|CB|RETRAIT|AVOIR|REMISE|CHEQUE|CHQ)\b', ' ', t)t = re.sub(r'\d', ' ', t)match = re.search(r'([A-Z][A-Z\s\-]{3,})', t)return match.group(1).strip()[:40] if match else "Client inconnu"def parse_montant(s):s = str(s).replace('\u00a0', '').replace(' ', '').replace(',', '.')s = re.sub(r'[^\d.\-+]', '', s)try:return float(s)except:return Nonedef parse_texte_brut(texte):"""Accepte n'importe quel texte collé depuis un PDF bancaire.Cherche des lignes contenant une date ET un montant."""lignes = texte.strip().splitlines()resultats = []for ligne in lignes:ligne = ligne.strip()if not ligne:continue# Cherche une datedate_match = DATE_RE.search(ligne)if not date_match:continue# Cherche tous les montants sur la lignemontants = MONTANT_RE.findall(ligne)if not montants:continue# Prend le dernier montant trouvé (souvent le montant net)montant_str = montants[-1].replace(' ', '').replace('\u00a0', '')montant = parse_montant(montant_str)if montant is None:continuedate = date_match.group(1)# Libellé = tout ce qui reste après la datelibelle = ligne[date_match.end():].strip()# Retire le montant du libellélibelle = MONTANT_RE.sub('', libelle).strip(' €-+')client = extraire_client(libelle if libelle else ligne)resultats.append({"date_aff": date,"client": client,"libelle_brut": libelle or ligne,"montant": montant})return pd.DataFrame(resultats) if resultats else Nonedef parse_csv(texte):"""Fallback : si le texte ressemble à un CSV structuré."""buf = io.StringIO(texte.strip())premiere = texte.strip().split("\n")[0]sep = ";" if premiere.count(";") >= premiere.count(",") else ","df = pd.read_csv(buf, sep=sep, decimal=",")df.columns = [c.strip().lower() for c in df.columns]montant_col = next((c for c in df.columns if any(k in c for k in ["montant","amount","credit","debit"])), None)if not montant_col:return Nonedf["montant"] = df[montant_col].apply(lambda x: parse_montant(str(x)))lib_col = next((c for c in df.columns if any(k in c for k in ["libelle","libellé","description","label","motif","operation"])), None)date_col = next((c for c in df.columns if "date" in c or "jour" in c), None)df["client"] = df[lib_col].apply(extraire_client) if lib_col else "Client inconnu"df["date_aff"] = df[date_col].astype(str) if date_col else datetime.now().strftime("%d/%m/%Y")return dfdef analyser(texte, source):if not texte.strip():return None, "Texte vide"# Essaie CSV d'abordtry:premiere = texte.strip().split("\n")[0]if ";" in premiere or (premiere.count(",") > 2):df = parse_csv(texte)if df is not None:df["source"] = sourcereturn df, Noneexcept:pass# Sinon parsing texte brutdf = parse_texte_brut(texte)if df is not None and not df.empty:df["source"] = sourcereturn df, Nonereturn None, "Aucune ligne avec date + montant trouvée. Vérifiez le texte collé."def generer_facture(row, numero):pdf = FPDF()pdf.add_page()pdf.set_font("Helvetica", "B", 18)pdf.cell(0, 12, company_name, ln=1, align="C")pdf.set_font("Helvetica", "", 10)41 unmodified linespdf.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())# ------------------------------------------------------------------ ## Interface# ------------------------------------------------------------------ #st.subheader("📋 Collez votre relevé bancaire")st.caption("Ouvrez votre PDF bancaire → Sélectionnez tout → Copiez → Collez ici")with st.expander("💡 Comment copier depuis un PDF sur Android", expanded=False):st.markdown("""1. Ouvrez votre relevé PDF avec **Google Drive** ou **Adobe Acrobat**2. Appuyez longuement sur le texte → **Sélectionner tout**3. Copiez4. Revenez ici et collez dans le champ ci-dessous5. Appuyez sur **Analyser**""")if "nb_releves" not in st.session_state:st.session_state["nb_releves"] = 1textes = []for i in range(st.session_state["nb_releves"]):texte = st.text_area("Relevé " + str(i + 1),height=160,key="rel_" + str(i),placeholder="Collez ici le texte de votre relevé bancaire...\n\nEx:\n02/01/2024 VIR DUPONT MARTIN 1 250,00\n05/01/2024 VIR LEBLANC SARL 890,50")textes.append(texte)col1, col2 = st.columns(2)with col1:if st.button("➕ Ajouter un relevé", use_container_width=True):st.session_state["nb_releves"] += 1st.rerun()with col2:if st.session_state["nb_releves"] > 1:if st.button("➖ Supprimer le dernier", use_container_width=True):st.session_state["nb_releves"] -= 1st.rerun()st.markdown("---")if st.button("📊 Analyser", type="secondary", use_container_width=True):tous_df = []for i, texte in enumerate(textes):if not texte.strip():continuedf, err = analyser(texte, "Relevé " + str(i + 1))if err:st.warning("Relevé " + str(i + 1) + " : " + err)else:tous_df.append(df)st.success("✅ Relevé " + str(i + 1) + " : " + str(len(df)) + " lignes trouvées")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 (montant positif) détecté.")else:st.session_state["encaissements"] = encaissementsst.session_state["pret"] = Trueif st.session_state.get("pret") and "encaissements" in st.session_state:encaissements = st.session_state["encaissements"]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)):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 not selections:st.warning("Veuillez sélectionner au moins une ligne.")else:zip_buffer = io.BytesIO()with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zip_file:for i, idx in enumerate(selections, start=1):row = encaissements.loc[idx].to_dict()pdf_bytes = generer_facture(row, i)client_safe = re.sub(r'[^A-Za-z0-9_-]', '_', str(row["client"])[:20])fname = "FACT_" + client_safe + "_" + datetime.now().strftime("%Y%m%d") + ".pdf"zip_file.writestr(fname, pdf_bytes)zip_buffer.seek(0)st.success("✅ " + str(len(selections)) + " facture(s) générée(s) !")st.download_button(label="📥 Télécharger les factures (ZIP)",data=zip_buffer.getvalue(),file_name="factures_" + datetime.now().strftime("%Y%m%d_%H%M") + ".zip",mime="application/zip",use_container_width=True)st.caption("FactureAuto — Version mobile Hugging Face")
src/streamlit_app.py+188-126