import streamlit as st
import pandas as pd
import os
from calculator import CorruptoCalculator
import database
# Load merged data (Static + Dynamic)
POLITICIANS = database.get_all_politicians()
st.set_page_config(
page_title="Le Corruptomètre",
page_icon="⚖️",
layout="wide"
)
# --- Sidebar ---
# --- Sidebar ---
with st.sidebar:
st.header("🤖 Configuration IA")
# Check for secret token (Public Mode)
hf_token = os.environ.get("HF_TOKEN")
# Try secrets if not in env
if not hf_token:
try:
if "HF_TOKEN" in st.secrets:
hf_token = st.secrets["HF_TOKEN"]
except Exception:
pass
if hf_token:
st.success("✅ Mode Public Activé")
st.caption("L'IA est offerte par l'hébergeur.")
else:
# Fallback to manual input
hf_token = st.text_input("Hugging Face Token", type="password", help="Pour l'analyse IA avancée")
if hf_token:
st.success("Token détecté !")
else:
st.info("Sans token, l'analyse sera basique.")
# --- CSS Styles ---
st.markdown("""
""", unsafe_allow_html=True)
# --- Helper Function ---
def get_all_scores():
results = []
for name, data in POLITICIANS.items():
score, _ = CorruptoCalculator.calculate_score(data["casseroles"])
grade, color = CorruptoCalculator.get_grade(score)
results.append({
"Nom": name,
"Parti": data["party"],
"Score": score,
"Note": grade,
"Color": color,
"Casseroles": len(data["casseroles"])
})
return pd.DataFrame(results)
def display_politician_report(report):
"""
Reusable function to display the full report of a politician.
"""
c1, c2 = st.columns([1, 2])
with c1:
st.markdown(f"""
{report['grade']}
Score: {report['score']}
""", unsafe_allow_html=True)
with c2:
st.subheader(f"{report['name']}")
# --- ALERTE TRAHISON ---
is_traitor = any(c['label'] == "Vente d'industrie stratégique (Trahison)" for c in report['casseroles_details'])
if is_traitor:
st.error("🚨 ALERTE : TRAHISON DE FRANCE DÉTECTÉE 🚨")
st.markdown("""
Vente d'intérêts souverains
""", unsafe_allow_html=True)
# -----------------------
if report.get('is_live'):
st.warning("⚠️ Données Web (Non vérifiées)")
st.caption("Ce score est estimé via une recherche en direct.")
st.badge(report['party'])
if not report['casseroles_details']:
if report.get('is_live'):
st.info("ℹ️ Aucune casserole flagrante trouvée sur le web.")
else:
st.success("✅ Aucune casserole majeure détectée (pour l'instant...)")
else:
st.warning(f"⚠️ {report['casseroles_count']} casseroles détectées")
for item in report['casseroles_details']:
points_color = "#ff4b4b" if item['points'] > 0 else "#28a745"
points_sign = "+" if item['points'] > 0 else ""
st.markdown(f"""
{item['label']}
{points_sign}{item['points']} pts
""", unsafe_allow_html=True)
# --- AI ANALYSIS DISPLAY ---
if report.get('ai_analysis'):
st.markdown("---")
st.subheader("🤖 Analyse de l'Intelligence Artificielle")
ai = report['ai_analysis']
gravite_color = "#28a745" # Green
if ai['gravite'] > 7: gravite_color = "#8B0000" # Dark Red
elif ai['gravite'] > 4: gravite_color = "#FFA500" # Orange
st.markdown(f"""
{ai['type']} (Gravité IA: {ai['gravite']}/10)
"{ai['resume']}"
""", unsafe_allow_html=True)
# --- Main Layout ---
st.title("⚖️ Le Corruptomètre")
st.markdown("### L'outil implacable pour mesurer la « qualité » de nos élus.")
# Tabs
tab1, tab2, tab3, tab4 = st.tabs(["🔍 Recherche Individuelle", "🏆 Palmarès (Leaderboard)", "📢 Signaler", "ℹ️ À propos"])
# --- TAB 1: Recherche ---
with tab1:
st.subheader("🔍 Recherche Rapide")
col_input, col_result = st.columns([1, 2])
with col_input:
search_query = st.text_input("Entrez un nom :", placeholder="Ex: Bayrou, Marine Le Pen...")
st.caption("Appuyez sur Entrée pour valider.")
with col_result:
if search_query:
with st.spinner("🕵️♂️ Investigation en cours sur le web..."):
report = CorruptoCalculator.generate_politician_report(search_query, POLITICIANS, api_token=hf_token)
if report:
display_politician_report(report)
else:
st.error(f"❌ Aucun résultat trouvé pour '{search_query}'. Essayez un autre nom.")
else:
st.info("👈 Entrez un nom à gauche pour lancer l'analyse.")
# --- TAB 2: Leaderboard ---
with tab2:
df = get_all_scores()
st.subheader("📊 Le Classement Général")
sort_order = st.radio("Trier par :", ["Les Pires (Score élevé)", "Les Meilleurs (Score faible)"], horizontal=True)
ascending = True if "Meilleurs" in sort_order else False
df_sorted = df.sort_values(by="Score", ascending=ascending)
# Top 3 Display
top_cols = st.columns(3)
for i in range(3):
if i < len(df_sorted):
row = df_sorted.iloc[i]
with top_cols[i]:
st.markdown(f"""
#{i+1} {row['Nom']}
{row['Parti']}
{row['Note']}
Score: {row['Score']} | 🥘 {row['Casseroles']}
""", unsafe_allow_html=True)
st.divider()
# Check if a politician is selected
if 'selected_politician' in st.session_state:
if st.button("⬅️ Retour au classement"):
del st.session_state['selected_politician']
st.rerun()
st.divider()
st.subheader(f"🔎 Détails pour {st.session_state['selected_politician']}")
report = CorruptoCalculator.generate_politician_report(st.session_state['selected_politician'], POLITICIANS)
if report:
display_politician_report(report)
else:
# Full List with Buttons
st.markdown("### 📋 Liste Complète")
# Headers
h1, h2, h3, h4, h5 = st.columns([2, 2, 1, 1, 1])
h1.markdown("**Nom**")
h2.markdown("**Parti**")
h3.markdown("**Note**")
h4.markdown("**Score**")
h5.markdown("**Action**")
st.divider()
for index, row in df_sorted.iterrows():
c1, c2, c3, c4, c5 = st.columns([2, 2, 1, 1, 1])
c1.write(f"**{row['Nom']}**")
c2.write(row['Parti'])
c3.markdown(f"{row['Note']}", unsafe_allow_html=True)
c4.write(f"{row['Score']}")
if c5.button("Voir fiche", key=f"btn_{index}"):
st.session_state['selected_politician'] = row['Nom']
st.rerun()
# --- TAB 3: Signaler ---
with tab3:
st.header("📢 Signaler une casserole")
st.markdown("Vous avez repéré une affaire manquante ? Dites-le nous !")
with st.form("report_form"):
col_a, col_b = st.columns(2)
with col_a:
st.text_input("Nom du politique")
st.selectbox("Type d'affaire", list(CorruptoCalculator.CRITERIA.keys()) + ["Autre"])
with col_b:
st.text_input("Lien vers la source (Article, Jugement...)")
st.date_input("Date des faits")
st.text_area("Description courte")
submitted = st.form_submit_button("Envoyer le signalement")
if submitted:
st.success("Merci ! Votre signalement a été enregistré et sera vérifié par notre équipe (ou une IA).")
# --- TAB 4: À propos ---
with tab4:
st.markdown("### Le Barème")
st.table({
"Critère": [v["label"] for v in CorruptoCalculator.CRITERIA.values()],
"Points": [v["points"] for v in CorruptoCalculator.CRITERIA.values()]
})
st.caption("Données fictives et approximatives pour démonstration.")