| import os |
| import sys |
| import yaml |
| import pandas as pd |
| import numpy as np |
| import joblib |
| import gradio as gr |
| import plotly.express as px |
| import plotly.graph_objects as go |
| from datetime import datetime |
|
|
| |
| sys.path.append(os.path.dirname(os.path.abspath(__file__))) |
| from build_features_v2 import extract_sota_features, STYLOMETRIC_COLS_V2 |
| from text_generator import PARTIES |
| from models_v2 import SOTAHybridDetector |
| from camembert_encoder import CamemBERTEncoder |
|
|
| def load_config(config_path="configs/config.yaml"): |
| with open(config_path, "r", encoding="utf-8") as f: |
| return yaml.safe_load(f) |
|
|
| |
| config = load_config() |
| output_dir = config["paths"]["output_dir"] |
| models_dir = config["paths"]["models_dir"] |
|
|
| |
| preds_path = os.path.join(output_dir, "recent_debates_predictions_v2.csv") |
| if not os.path.exists(preds_path): |
| print(f"Predictions v2 not found at {preds_path}. Trying fallback...") |
| preds_path = os.path.join(output_dir, "recent_debates_predictions.csv") |
|
|
| if not os.path.exists(preds_path): |
| df_preds = pd.DataFrame(columns=["date", "speaker", "party", "prob_ai", "prediction", "text", "document_type", "confidence_score"]) |
| else: |
| df_preds = pd.read_csv(preds_path) |
| df_preds["date"] = pd.to_datetime(df_preds["date"]) |
|
|
| |
| COLS_MAP_V2 = { |
| 'num_chars': "Nombre de caractères", |
| 'num_words': "Nombre de mots", |
| 'num_sentences': "Nombre de phrases", |
| 'avg_sentence_len': "Longueur moyenne des phrases", |
| 'std_sentence_len': "Écart-type de la longueur des phrases", |
| 'slv_normalized': "Complexité lexicale normalisée (SLV)", |
| 'avg_word_len': "Longueur moyenne des mots", |
| 'ratio_long_words': "Ratio de mots longs (>6 caractères)", |
| 'vocabulary_diversity': "Diversité lexicale (TTR)", |
| 'hapax_ratio': "Ratio d'Hapax (mots uniques)", |
| 'yules_k': "Richesse lexicale (Yule's K)", |
| 'maas_index': "Indice Maas", |
| 'information_entropy': "Entropie de l'information", |
| 'brunet_w': "Indice de Brunet W", |
| 'ratio_punctuation': "Ratio de ponctuation", |
| 'freq_uppercase': "Fréquence des majuscules", |
| 'freq_digits': "Fréquence des chiffres", |
| 'connector_ratio': "Ratio de connecteurs logiques", |
| 'connector_diversity': "Diversité des connecteurs", |
| 'repetition_ratio': "Ratio de répétitions lexicales", |
| 'stopword_ratio': "Ratio de mots vides (stopwords)", |
| 'mean_polarity_diff': "Polarité moyenne (positif/négatif)", |
| 'syntactic_complexity_score': "Complexité syntaxique (subordonnées)", |
| 'ratio_interrogative': "Ratio de phrases interrogatives", |
| 'ratio_exclamative': "Ratio de phrases exclamatives", |
| 'ratio_declarative': "Ratio de phrases déclaratives", |
| 'imparfait_ratio': "Ratio de verbes à l'imparfait", |
| 'futur_ratio': "Ratio de verbes au futur", |
| 'conditional_ratio': "Ratio de verbes au conditionnel", |
| 'passive_voice_ratio': "Ratio de tournures passives" |
| } |
|
|
| |
| model_pkg_path = os.path.join(models_dir, "best_detector_v2.pkl") |
| if os.path.exists(model_pkg_path): |
| print(f"Loading SOTA v2 model from {model_pkg_path}...") |
| pkg = joblib.load(model_pkg_path) |
| detector = pkg["model"] |
| model_name = pkg["model_name"] |
| xgb_raw = pkg["xgb_raw"] |
| scalers = pkg["scalers"] |
| stylometric_cols = pkg["stylometric_cols"] |
| friendly_feature_names = [COLS_MAP_V2.get(col, col) for col in stylometric_cols] |
| |
| |
| encoder = CamemBERTEncoder() |
| else: |
| pkg = None |
| detector = None |
| xgb_raw = None |
| encoder = None |
| friendly_feature_names = [] |
| print("Model package best_detector_v2.pkl not found. Run train_on_lucie_historical.py first.") |
|
|
| def detect_live_text(input_text): |
| """Predicts if the pasted text is AI-generated and returns metrics & explanation.""" |
| if pkg is None or xgb_raw is None or encoder is None: |
| return "Erreur : Modèle SOTA v2 ou encodeur CamemBERT non chargé.", None, None, None |
| |
| if not input_text or len(input_text.strip()) < 10: |
| return "Veuillez entrer un texte plus long (au moins 10 caractères).", 0.0, 0.0, [] |
| |
| text_cleaned = " ".join(input_text.replace("’", "'").replace("œ", "oe").split()) |
| |
| |
| connecteurs = config.get("features", {}).get("connecteurs", [ |
| "en effet", "par conséquent", "en outre", "néanmoins", "toutefois", "cependant" |
| ]) |
| sty_dict = extract_sota_features(text_cleaned, connecteurs) |
| df_sty = pd.DataFrame([sty_dict]) |
| X_sty = df_sty[stylometric_cols].values |
| |
| |
| X_emb = encoder.encode_single(text_cleaned).reshape(1, -1) |
| |
| |
| X_sty_scaled = scalers["sty"].transform(X_sty) |
| X_emb_scaled = scalers["emb"].transform(X_emb) |
| X_combined = np.hstack([X_sty_scaled, X_emb_scaled]) |
| |
| |
| prob_ai = float(xgb_raw.predict_proba(X_combined)[0][1]) |
| confidence = 2.0 * abs(prob_ai - 0.5) |
| prediction = 1 if prob_ai >= 0.5 else 0 |
| |
| verdict = "🤖 TEXTE SUSPECTÉ GÉNÉRÉ PAR IA" if prediction == 1 else "✍️ TEXTE SUSPECTÉ HUMAIN" |
| |
| |
| import shap |
| explainer = shap.TreeExplainer(xgb_raw) |
| shap_values = explainer.shap_values(X_combined) |
| |
| |
| sv_sty = shap_values[0][:len(stylometric_cols)] |
| |
| explanation_list = [] |
| feat_contrib = list(zip(friendly_feature_names, sv_sty)) |
| |
| feat_contrib_sorted = sorted(feat_contrib, key=lambda x: abs(x[1]), reverse=True) |
| |
| for name, score in feat_contrib_sorted[:10]: |
| direction = "⚠️ Indique IA" if score > 0 else "🍀 Indique Humain" |
| explanation_list.append({"Caractéristique": name, "Impact": f"{direction} ({score:+.3f})"}) |
| |
| explanation_df = pd.DataFrame(explanation_list) if explanation_list else pd.DataFrame(columns=["Caractéristique", "Impact"]) |
| return verdict, prob_ai, confidence, explanation_df |
|
|
| def make_interactive_chart(party_filter, doc_filter): |
| if df_preds.empty: |
| return go.Figure() |
| |
| df_filtered = df_preds.copy() |
| if party_filter != "Tous": |
| df_filtered = df_filtered[df_filtered["party"] == party_filter] |
| if doc_filter != "Tous": |
| df_filtered = df_filtered[df_filtered["document_type"] == doc_filter] |
| |
| df_filtered["prob_ai_plot"] = df_filtered["prob_ai"] + 1e-4 |
| df_filtered["snippet"] = df_filtered["text"].apply(lambda t: (t[:150] + "...") if isinstance(t, str) and len(t) > 150 else str(t)) |
| df_filtered["type_predit"] = df_filtered["prediction"].map({0: "Humain", 1: "IA"}) |
| df_filtered["date_str"] = df_filtered["date"].dt.strftime("%Y-%m-%d") |
| |
| fig = px.scatter( |
| df_filtered, |
| x="date", |
| y="prob_ai_plot", |
| color="party", |
| size="confidence_score", |
| opacity=0.6, |
| hover_data={ |
| "date_str": True, |
| "speaker": True, |
| "party": True, |
| "document_type": True, |
| "prob_ai": ":.4f", |
| "confidence_score": ":.4f", |
| "type_predit": True, |
| "snippet": True, |
| "date": False, |
| "prob_ai_plot": False |
| }, |
| labels={ |
| "date": "Date de l'intervention", |
| "prob_ai_plot": "Score de suspicion (Échelle Log)", |
| "party": "Groupe politique", |
| "confidence_score": "Confiance" |
| }, |
| title="Explorateur Temporel des Discours (2004-2026)" |
| ) |
| |
| fig.update_layout( |
| template="plotly_white", |
| yaxis=dict( |
| type="log", |
| tickvals=[1e-4, 1e-3, 1e-2, 1e-1, 1.0], |
| ticktext=["0.0001 (Humain)", "0.001", "0.01", "0.1", "1.0 (IA)"], |
| title="Score de suspicion d'IA (Échelle Log)" |
| ), |
| xaxis=dict(title="Date de l'intervention"), |
| legend_title_text="Groupe politique" |
| ) |
| return fig |
|
|
| def make_weekly_chart(): |
| if df_preds.empty: |
| return go.Figure() |
| |
| df_weekly = df_preds.copy() |
| df_weekly["week_start"] = df_weekly["date"] - pd.to_timedelta(df_weekly["date"].dt.weekday, unit='D') |
| weekly_avg = df_weekly.groupby("week_start")["prob_ai"].agg(["mean", "count"]).reset_index() |
| weekly_avg.columns = ["week_start", "prob_ai_mean", "speech_count"] |
| |
| weekly_avg["prob_ai_plot"] = weekly_avg["prob_ai_mean"] + 1e-4 |
| |
| fig = go.Figure() |
| fig.add_trace(go.Scatter( |
| x=weekly_avg["week_start"], |
| y=weekly_avg["prob_ai_plot"], |
| mode="lines+markers", |
| name="Moyenne hebdomadaire", |
| line=dict(color="#3f51b5", width=2), |
| marker=dict(size=weekly_avg["speech_count"]/2 + 3, color="#3f51b5", opacity=0.8), |
| hovertemplate="Semaine: %{x}<br>Score de suspicion moyen: %{y:.4f}<br>Nombre de discours: %{marker.size}<extra></extra>" |
| )) |
| |
| fig.add_shape( |
| type="line", |
| x0="2022-11-30", y0=1e-4, x1="2022-11-30", y1=1.0, |
| line=dict(color="#e91e63", width=1.5, dash="dash"), |
| ) |
| fig.add_annotation( |
| x="2022-11-30", y=0.5, |
| text="Sortie de ChatGPT (Fin 2022)", |
| showarrow=True, |
| arrowhead=1, |
| ax=-100, ay=-30, |
| arrowcolor="#e91e63", |
| font=dict(color="#e91e63") |
| ) |
| |
| fig.update_layout( |
| template="plotly_white", |
| yaxis=dict( |
| type="log", |
| tickvals=[1e-4, 1e-3, 1e-2, 1e-1, 1.0], |
| ticktext=["0.0001 (Humain)", "0.001", "0.01", "0.1", "1.0 (IA)"], |
| title="Score de suspicion moyen (Log)" |
| ), |
| xaxis=dict(title="Semaine"), |
| title="Tendance hebdomadaire du score de suspicion d'IA (2004-2026)" |
| ) |
| return fig |
|
|
| def get_party_leaderboard(): |
| if df_preds.empty: |
| return pd.DataFrame(), go.Figure() |
| df_post = df_preds[df_preds["date"] >= "2023-01-01"].copy() |
| stats = df_post.groupby("party").agg( |
| speech_count=("prob_ai", "count"), |
| mean_suspicion=("prob_ai", "mean"), |
| ai_ratio=("prediction", "mean") |
| ).reset_index().sort_values(by="mean_suspicion", ascending=False) |
| |
| stats_show = stats.copy() |
| stats_show["mean_suspicion"] = stats_show["mean_suspicion"].round(4) |
| stats_show["ai_ratio"] = (stats_show["ai_ratio"] * 100).round(2).astype(str) + "%" |
| stats_show.columns = ["Groupe Politique", "Nombre de discours", "Score suspicion moyen", "Proportion rédigée par IA"] |
| |
| fig = px.bar( |
| stats, |
| x="mean_suspicion", |
| y="party", |
| color="mean_suspicion", |
| orientation="h", |
| color_continuous_scale="Viridis", |
| labels={"mean_suspicion": "Suspicion moyenne", "party": "Groupe politique"}, |
| title="Score moyen de suspicion par groupe politique" |
| ) |
| fig.update_layout(showlegend=False, coloraxis_showscale=False) |
| return stats_show, fig |
|
|
| def get_speaker_leaderboard(): |
| if df_preds.empty: |
| return pd.DataFrame(), go.Figure() |
| df_post = df_preds[df_preds["date"] >= "2023-01-01"].copy() |
| stats = df_post.groupby("speaker").agg( |
| speech_count=("prob_ai", "count"), |
| mean_suspicion=("prob_ai", "mean"), |
| ai_ratio=("prediction", "mean") |
| ).reset_index().sort_values(by="mean_suspicion", ascending=False).head(10) |
| |
| stats_show = stats.copy() |
| stats_show["mean_suspicion"] = stats_show["mean_suspicion"].round(4) |
| stats_show["ai_ratio"] = (stats_show["ai_ratio"] * 100).round(2).astype(str) + "%" |
| stats_show.columns = ["Député / Orateur", "Nombre de discours", "Score suspicion moyen", "Proportion rédigée par IA"] |
| |
| fig = px.bar( |
| stats, |
| x="mean_suspicion", |
| y="speaker", |
| color="mean_suspicion", |
| orientation="h", |
| color_continuous_scale="Plasma", |
| labels={"mean_suspicion": "Suspicion moyenne", "speaker": "Orateur"}, |
| title="Top 10 des orateurs les plus suspects" |
| ) |
| fig.update_layout(showlegend=False, coloraxis_showscale=False) |
| return stats_show, fig |
|
|
| def search_records(query_speaker, query_party): |
| if df_preds.empty: |
| return pd.DataFrame() |
| |
| df_filtered = df_preds.copy() |
| if query_speaker: |
| df_filtered = df_filtered[df_filtered["speaker"].str.contains(query_speaker, case=False, na=False)] |
| if query_party != "Tous": |
| df_filtered = df_filtered[df_filtered["party"] == query_party] |
| |
| df_show = df_filtered[["date", "speaker", "party", "document_type", "prob_ai", "prediction", "text"]].copy() |
| df_show["date"] = df_show["date"].dt.strftime("%Y-%m-%d") |
| df_show["prediction"] = df_show["prediction"].map({0: "Humain", 1: "IA"}) |
| df_show.columns = ["Date", "Député", "Groupe", "Type", "Score IA", "Classification", "Texte"] |
| return df_show.head(100) |
|
|
| |
| with gr.Blocks(title="Détecteur d'IA Parlementaire") as demo: |
| gr.HTML(""" |
| <div style="text-align: center; padding: 1.5rem; background: linear-gradient(135deg, #3f51b5, #e91e63); color: white; border-radius: 10px; margin-bottom: 2rem;"> |
| <h1 style="margin: 0; font-size: 2.2rem; font-weight: 800;">Détecteur de Textes Parlementaires Générés par IA</h1> |
| <p style="margin: 5px 0 0 0; font-size: 1.1rem; opacity: 0.9;">Analyse stylométrique et temporelle continue (2004-2026) sur données réelles d'Hugging Face</p> |
| </div> |
| """) |
| |
| with gr.Tabs(): |
| |
| with gr.TabItem("🔍 Détecteur en Direct"): |
| gr.Markdown("### Testez l'écriture d'un discours en collant son contenu ci-dessous :") |
| with gr.Row(): |
| with gr.Column(scale=2): |
| input_box = gr.Textbox( |
| label="Texte politique / Discours en français", |
| placeholder="Saisissez ou collez l'intervention d'un député ici...", |
| lines=12 |
| ) |
| btn_predict = gr.Button("Analyser le texte", variant="primary") |
| with gr.Column(scale=1): |
| output_verdict = gr.Textbox(label="Verdict de classification", interactive=False) |
| output_score = gr.Label(label="Score de suspicion (Probabilité d'IA)") |
| output_confidence = gr.Slider(label="Niveau de confiance du modèle", minimum=0, maximum=1, value=0, interactive=False) |
| |
| gr.Markdown("---") |
| gr.Markdown("### 🔍 Pourquoi cette décision ? (Coefficients les plus influents)") |
| output_explanation = gr.DataFrame(headers=["Caractéristique", "Impact"], datatype=["str", "str"], wrap=True) |
| |
| btn_predict.click( |
| fn=detect_live_text, |
| inputs=input_box, |
| outputs=[output_verdict, output_score, output_confidence, output_explanation] |
| ) |
| |
| |
| with gr.TabItem("📈 Tendances Temporelles & Cartographie"): |
| gr.Markdown("### Analyse continue hebdomadaire avec échelle logarithmique") |
| with gr.Row(): |
| with gr.Column(): |
| party_filter = gr.Dropdown(choices=["Tous"] + PARTIES, value="Tous", label="Filtrer par Groupe Politique") |
| with gr.Column(): |
| doc_filter = gr.Dropdown(choices=["Tous", "intervention_seance", "prise_position", "explication_vote", "amendement", "reponse_debat", "discours_groupe"], value="Tous", label="Filtrer par Type de Document") |
| |
| with gr.Row(): |
| with gr.Column(): |
| chart_scatter = gr.Plot(label="Cartographie interactive des points (Tous les discours)") |
| |
| gr.Markdown("---") |
| with gr.Row(): |
| chart_line = gr.Plot(label="Tendance Moyenne Hebdomadaire (Log Scale)") |
| |
| party_filter.change(fn=make_interactive_chart, inputs=[party_filter, doc_filter], outputs=chart_scatter) |
| doc_filter.change(fn=make_interactive_chart, inputs=[party_filter, doc_filter], outputs=chart_scatter) |
| |
| demo.load(fn=make_interactive_chart, inputs=[party_filter, doc_filter], outputs=chart_scatter) |
| demo.load(fn=make_weekly_chart, inputs=None, outputs=chart_line) |
| |
| |
| with gr.TabItem("🏆 Classements (Post-2022)"): |
| gr.Markdown("### 📊 Classements de suspicion d'utilisation de l'IA (Période 2023-2026)") |
| with gr.Row(): |
| with gr.Column(): |
| gr.Markdown("#### 🏛️ Classement des Groupes Politiques") |
| output_party_leaderboard = gr.DataFrame(datatype=["str", "int", "str", "str"]) |
| chart_party_leaderboard = gr.Plot() |
| with gr.Column(): |
| gr.Markdown("#### 👤 Top 10 des Députés les plus suspects") |
| output_speaker_leaderboard = gr.DataFrame(datatype=["str", "int", "str", "str"]) |
| chart_speaker_leaderboard = gr.Plot() |
| |
| |
| demo.load(fn=get_party_leaderboard, inputs=None, outputs=[output_party_leaderboard, chart_party_leaderboard]) |
| demo.load(fn=get_speaker_leaderboard, inputs=None, outputs=[output_speaker_leaderboard, chart_speaker_leaderboard]) |
| |
| |
| with gr.TabItem("🗄️ Explorateur des Discours"): |
| gr.Markdown("### Parcourez les 3 000 interventions récentes scorées par le pipeline") |
| with gr.Row(): |
| with gr.Column(): |
| search_speaker = gr.Textbox(placeholder="Rechercher par nom de député...", label="Orateur") |
| with gr.Column(): |
| search_party = gr.Dropdown(choices=["Tous"] + PARTIES, value="Tous", label="Groupe Politique") |
| |
| btn_search = gr.Button("Rechercher", variant="secondary") |
| |
| gr.Markdown("#### Résultats (Top 100 max) :") |
| output_table = gr.DataFrame(wrap=True) |
| |
| btn_search.click( |
| fn=search_records, |
| inputs=[search_speaker, search_party], |
| outputs=output_table |
| ) |
| |
| demo.load(fn=search_records, inputs=[search_speaker, search_party], outputs=output_table) |
|
|
| if __name__ == "__main__": |
| print("Launching Gradio application in share mode...") |
| demo.launch(server_name="0.0.0.0", server_port=7860, share=True, theme=gr.themes.Soft()) |
|
|