lmb-fe/functions_ui.py
2026-03-13 23:54:16 +01:00

134 lines
4.7 KiB
Python

import pandas as pd
import streamlit as st
from functions import do_login, generate_pdf_download
def open_csv_file(file_path):
"""Apre un file CSV e restituisce una connessione DuckDB in-memory."""
import duckdb
con = duckdb.connect(database=":memory:")
con.execute(f"CREATE TABLE index AS SELECT * FROM read_csv_auto('{file_path}')")
return con
def search_cas_inci(input, type="cas"):
"""Cerca un numero CAS o INCI nel file CSV. Ritorna lista di tuple (casNo, inciName)."""
con = open_csv_file("streamlit\data.csv")
if type == "cas":
query = f"SELECT * FROM index WHERE casNo LIKE '%{input}%'"
else:
query = f"SELECT * FROM index WHERE inciName ILIKE '%{input}%'"
results = con.execute(query).fetchdf()
if not results.empty:
return list(zip(results["casNo"].tolist(), results["inciName"].tolist()))
return []
def search_cir(input_text: str) -> list[tuple]:
"""Cerca nel CIR database per nome ingrediente o INCI. Ritorna lista di (name, inci, url)."""
con = open_csv_file("streamlit\cir-reports.csv")
query = f"""
SELECT
"tablescraper-selected-row" AS ingredient_name,
"tablescraper-selected-row 2" AS inci_name,
"tablescraper-selected-row href" AS url
FROM index
WHERE (
"tablescraper-selected-row" ILIKE '%{input_text}%'
OR "tablescraper-selected-row 2" ILIKE '%{input_text}%'
)
AND "tablescraper-selected-row" != 'Ingredient Name as Used:'
AND "tablescraper-selected-row href" != ''
LIMIT 20
"""
results = con.execute(query).fetchdf()
if not results.empty:
return list(zip(
results["ingredient_name"].tolist(),
results["inci_name"].tolist(),
results["url"].tolist(),
))
return []
def download_pdf(casNo, origin, link):
"""Mostra i pulsanti per generare e scaricare un PDF dall'API."""
if st.button("Generate PDF", key=f"gen_{casNo}_{origin}"):
with st.spinner("Fetching PDF..."):
pdf_data = generate_pdf_download(cas=casNo, origin=origin, link=link)
st.download_button(
label="Download PDF",
data=pdf_data,
file_name=f"{casNo}_{origin}.pdf",
mime="application/pdf",
key=f"dl_{casNo}_{origin}",
)
def show_login_page():
"""Mostra il form di login."""
_, col, _ = st.columns([1, 1, 1])
with col:
st.title("LMB App")
st.caption("Accedi per continuare")
with st.form("login_form"):
email = st.text_input("Email", placeholder="utente@esempio.it")
password = st.text_input("Password", type="password")
submitted = st.form_submit_button("Accedi", use_container_width=True, type="primary")
if submitted:
if not email or not password:
st.warning("Inserisci email e password.")
else:
with st.spinner("Autenticazione in corso..."):
if do_login(email, password):
st.rerun()
def display_orderData(order_data: dict):
"""Mostra un riepilogo leggibile dell'ordine (non JSON)."""
st.markdown("### Riepilogo Ordine")
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Cliente", order_data["client_name"])
with col2:
st.metric("Prodotto", order_data["product_name"])
with col3:
st.metric("Preset Esposizione", order_data["preset_esposizione"])
ingredients = order_data.get("ingredients", [])
total_pct = sum(i["percentage"] for i in ingredients)
col4, col5, col6 = st.columns(3)
with col4:
st.metric("Numero ingredienti", len(ingredients))
with col5:
st.metric("Percentuale totale", f"{total_pct:.6f}%")
with col6:
n_col = sum(1 for i in ingredients if i["is_colorante"])
n_skip = sum(1 for i in ingredients if i["skip_tox"])
parts = []
if n_col > 0:
parts.append(f"{n_col} colorante/i")
if n_skip > 0:
parts.append(f"{n_skip} senza tox")
st.metric("Flag attivi", ", ".join(parts) if parts else "Nessuno")
st.markdown("**Ingredienti:**")
display_rows = [
{
"INCI": i["inci"] if i["inci"] else "-",
"CAS": i["cas"] if i["cas"] else "-",
"Percentuale (%)": f"{i['percentage']:.6f}",
"Colorante": "Si" if i["is_colorante"] else "-",
"Salta Tox": "Si" if i["skip_tox"] else "-",
}
for i in ingredients
]
st.dataframe(pd.DataFrame(display_rows), width="stretch", hide_index=True)
if __name__ == "__main__":
data = search_cas_inci("102242-62-6")
print(data)