Download scripts/make_plots.py from simonlesaumon/AI_DETECTOR_SOTA: direct link, hf CLI and curl.
- Browser
- Download file 17.4 kB
-
https://huggingface.co/datasets/simonlesaumon/AI_DETECTOR_SOTA/resolve/main/scripts/make_plots.py
- Command line
-
hf download hf://datasets/simonlesaumon/AI_DETECTOR_SOTA/scripts/make_plots.py
-
curl -L -o make_plots.py https://huggingface.co/datasets/simonlesaumon/AI_DETECTOR_SOTA/resolve/main/scripts/make_plots.py
17.4 kB
| import os | |
| import sys | |
| import yaml | |
| import argparse | |
| import pandas as pd | |
| import numpy as np | |
| import matplotlib.pyplot as plt | |
| import seaborn as sns | |
| import joblib | |
| def load_config(config_path): | |
| with open(config_path, "r", encoding="utf-8") as f: | |
| return yaml.safe_load(f) | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Generate visualization plots for AI text detection.") | |
| parser.add_argument("--config", default="configs/config.yaml", help="Path to config file") | |
| args = parser.parse_args() | |
| config = load_config(args.config) | |
| output_dir = config["paths"]["output_dir"] | |
| reports_dir = config["paths"]["reports_dir"] | |
| models_dir = config["paths"]["models_dir"] | |
| plots_dir = os.path.join(reports_dir, "plots") | |
| os.makedirs(plots_dir, exist_ok=True) | |
| os.makedirs(output_dir, exist_ok=True) | |
| # Load predictions | |
| preds_path = os.path.join(output_dir, "recent_debates_predictions_v2.csv") | |
| if not os.path.exists(preds_path): | |
| preds_path = os.path.join(output_dir, "recent_debates_predictions.csv") | |
| if not os.path.exists(preds_path): | |
| print(f"Error: Predictions file not found. Please run inference first.") | |
| sys.exit(1) | |
| df = pd.read_csv(preds_path) | |
| df["date"] = pd.to_datetime(df["date"]) | |
| df["year"] = df["date"].dt.year | |
| # Set premium aesthetic style | |
| sns.set_theme(style="whitegrid") | |
| plt.rcParams["figure.facecolor"] = "#fbfbfb" | |
| plt.rcParams["axes.facecolor"] = "#ffffff" | |
| plt.rcParams["font.sans-serif"] = ["DejaVu Sans", "Helvetica", "Arial"] | |
| plt.rcParams["font.family"] = "sans-serif" | |
| colors_palette = ["#3f51b5", "#e91e63", "#00bcd4", "#ff9800", "#4caf50", "#9c27b0"] | |
| sns.set_palette(colors_palette) | |
| # --- Plot 1: AI Suspicion Over Time (2004-2026, Weekly & Log Scale) --- | |
| print("Generating Plot 1: AI Suspicion Over Time (Weekly & Log Scale)...") | |
| plt.figure(figsize=(12, 6)) | |
| # Calculate weekly starting date | |
| df["week_start"] = df["date"] - pd.to_timedelta(df["date"].dt.weekday, unit='D') | |
| weekly_avg = df.groupby("week_start")["prob_ai"].agg(["mean", "count"]).reset_index() | |
| weekly_avg.columns = ["week_start", "prob_ai_mean", "speech_count"] | |
| # Epsilon for log scale | |
| weekly_avg["prob_ai_plot"] = weekly_avg["prob_ai_mean"] + 1e-4 | |
| sns.lineplot(data=weekly_avg, x="week_start", y="prob_ai_plot", color="#3f51b5", linewidth=1.5, alpha=0.8) | |
| plt.scatter(weekly_avg["week_start"], weekly_avg["prob_ai_plot"], s=weekly_avg["speech_count"]*2, color="#3f51b5", alpha=0.6, label="Moyenne hebdo (taille = nb de discours)") | |
| # Add a red dashed line at 2022-11-30 to show release of ChatGPT | |
| chatgpt_release = pd.to_datetime("2022-11-30") | |
| plt.axvline(x=chatgpt_release, color="#e91e63", linestyle="--", alpha=0.8, linewidth=1.5, label="Sortie de ChatGPT (Fin 2022)") | |
| plt.title("Évolution hebdomadaire du score moyen de suspicion d'IA (Échelle Log, 2004-2026)", fontsize=14, fontweight="bold", pad=15) | |
| plt.xlabel("Date", fontsize=12) | |
| plt.ylabel("Score de suspicion moyen (Probabilité d'IA + 1e-4)", fontsize=12) | |
| # Log scale | |
| plt.yscale("log") | |
| plt.ylim(0.5e-4, 1.2) | |
| plt.yticks([1e-4, 1e-3, 1e-2, 1e-1, 1.0], ["0.0001 (Humain)", "0.001", "0.01", "0.1", "1.0 (IA)"]) | |
| plt.legend(loc="upper left", frameon=True) | |
| plt.tight_layout() | |
| plot1_path = os.path.join(plots_dir, "suspicion_over_time.png") | |
| plt.savefig(plot1_path, dpi=300) | |
| plt.savefig(os.path.join(output_dir, "suspicion_over_time.png"), dpi=300) | |
| plt.close() | |
| # --- Plot 2: Probability Distribution Histogram --- | |
| print("Generating Plot 2: Probability Distribution...") | |
| plt.figure(figsize=(10, 5.5)) | |
| if "actual_label" in df.columns: | |
| # If we have actual labels, plot separate distributions | |
| sns.kdeplot(data=df[df["actual_label"] == 0], x="prob_ai", fill=True, label="Discours Humain", color="#3f51b5", alpha=0.5, bw_adjust=0.5) | |
| sns.kdeplot(data=df[df["actual_label"] == 1], x="prob_ai", fill=True, label="Discours IA", color="#e91e63", alpha=0.5, bw_adjust=0.5) | |
| plt.title("Distribution des scores de suspicion (Humain vs Synthétique)", fontsize=14, fontweight="bold", pad=15) | |
| else: | |
| sns.histplot(data=df, x="prob_ai", bins=30, kde=True, color="#3f51b5", alpha=0.7) | |
| plt.title("Distribution générale des scores de suspicion d'IA", fontsize=14, fontweight="bold", pad=15) | |
| plt.xlabel("Score de suspicion (Probabilité d'IA)", fontsize=12) | |
| plt.ylabel("Densité", fontsize=12) | |
| plt.xlim(-0.05, 1.05) | |
| plt.legend(loc="upper right", frameon=True) | |
| plt.tight_layout() | |
| plot2_path = os.path.join(plots_dir, "probability_distribution.png") | |
| plt.savefig(plot2_path, dpi=300) | |
| plt.savefig(os.path.join(output_dir, "probability_distribution.png"), dpi=300) | |
| plt.close() | |
| # --- Plot 3: Suspicion Score by Political Party --- | |
| print("Generating Plot 3: Suspicion Score by Party...") | |
| plt.figure(figsize=(10, 5.5)) | |
| party_avg = df.groupby("party")["prob_ai"].mean().reset_index().sort_values(by="prob_ai", ascending=False) | |
| sns.barplot(data=party_avg, x="prob_ai", y="party", palette="viridis") | |
| plt.axvline(x=df["prob_ai"].mean(), color="#e91e63", linestyle=":", alpha=0.8, linewidth=1.5, label="Moyenne générale") | |
| plt.title("Score moyen de suspicion d'IA par groupe politique", fontsize=14, fontweight="bold", pad=15) | |
| plt.xlabel("Score de suspicion moyen", fontsize=12) | |
| plt.ylabel("Groupe politique", fontsize=12) | |
| plt.xlim(0, max(party_avg["prob_ai"].max() + 0.05, 0.5)) | |
| plt.legend(loc="lower right", frameon=True) | |
| plt.tight_layout() | |
| plot3_path = os.path.join(plots_dir, "suspicion_by_party.png") | |
| plt.savefig(plot3_path, dpi=300) | |
| plt.savefig(os.path.join(output_dir, "suspicion_by_party.png"), dpi=300) | |
| plt.close() | |
| # --- Plot 4: Suspicion Score by Document Type --- | |
| print("Generating Plot 4: Suspicion Score by Document Type...") | |
| plt.figure(figsize=(10, 5.5)) | |
| doc_avg = df.groupby("document_type")["prob_ai"].mean().reset_index().sort_values(by="prob_ai", ascending=False) | |
| sns.barplot(data=doc_avg, x="prob_ai", y="document_type", palette="rocket") | |
| plt.axvline(x=df["prob_ai"].mean(), color="#3f51b5", linestyle=":", alpha=0.8, linewidth=1.5, label="Moyenne générale") | |
| plt.title("Score moyen de suspicion d'IA par type de document", fontsize=14, fontweight="bold", pad=15) | |
| plt.xlabel("Score de suspicion moyen", fontsize=12) | |
| plt.ylabel("Type de document", fontsize=12) | |
| plt.xlim(0, max(doc_avg["prob_ai"].max() + 0.05, 0.5)) | |
| plt.legend(loc="lower right", frameon=True) | |
| plt.tight_layout() | |
| plot4_path = os.path.join(plots_dir, "suspicion_by_doc_type.png") | |
| plt.savefig(plot4_path, dpi=300) | |
| plt.savefig(os.path.join(output_dir, "suspicion_by_doc_type.png"), dpi=300) | |
| plt.close() | |
| # --- Plot 5: Top 10 Coefficients for IA vs Human --- | |
| # Load model to extract coefficients/importances | |
| model_pkg_path = os.path.join(models_dir, "best_detector_v2.pkl") | |
| is_v2 = os.path.exists(model_pkg_path) | |
| if not is_v2: | |
| model_pkg_path = os.path.join(models_dir, "best_detector.pkl") | |
| if os.path.exists(model_pkg_path): | |
| print(f"Generating Plot 5: Top Features from {os.path.basename(model_pkg_path)}...") | |
| pkg = joblib.load(model_pkg_path) | |
| if is_v2: | |
| xgb_raw = pkg["xgb_raw"] | |
| stylometric_cols = pkg["stylometric_cols"] | |
| importances = xgb_raw.feature_importances_ | |
| 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 longueur des phrases", | |
| 'slv_normalized': "Complexité lexicale (SLV)", | |
| 'avg_word_len': "Longueur moyenne des mots", | |
| 'ratio_long_words': "Ratio de mots longs (>6 chars)", | |
| '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" | |
| } | |
| friendly_names = [COLS_MAP_V2.get(col, col) for col in stylometric_cols] | |
| # Slice features to match coefficients length | |
| sty_importances = importances[:len(stylometric_cols)] | |
| imp_df = pd.DataFrame({"feature": friendly_names, "importance": sty_importances}) | |
| imp_df = imp_df.sort_values(by="importance", ascending=False).head(10).sort_values(by="importance", ascending=True) | |
| plt.figure(figsize=(10, 6)) | |
| colors = ["#3f51b5"] * len(imp_df) | |
| bars = plt.barh(imp_df["feature"], imp_df["importance"], color=colors, alpha=0.85) | |
| # Label bars | |
| for bar in bars: | |
| width = bar.get_width() | |
| plt.text(width + 0.001, bar.get_y() + bar.get_height()/2, f'{width:.4f}', | |
| va='center', ha='left', fontsize=10, fontweight='bold', | |
| color='#333333') | |
| plt.title("Top 10 des caractéristiques stylométriques les plus discriminantes (Importance XGBoost)", fontsize=14, fontweight="bold", pad=15) | |
| plt.xlabel("Importance relative (Gain de pureté)", fontsize=12) | |
| plt.ylabel("Caractéristique", fontsize=12) | |
| plt.tight_layout() | |
| plot5_path = os.path.join(plots_dir, "top_features.png") | |
| plt.savefig(plot5_path, dpi=300) | |
| plt.savefig(os.path.join(output_dir, "top_features.png"), dpi=300) | |
| plt.close() | |
| else: | |
| model = pkg["model"] | |
| model_key = pkg["model_key"] | |
| if "logistic_regression" in model_key or "hybrid" in model_key: | |
| coefs = model.coef_[0] | |
| cols = pkg["stylometric_cols"] if model_key == "logistic_regression_sty" else (pkg["ngram_cols"] if model_key == "logistic_regression_ng" else pkg["hybrid_cols"]) | |
| cols = cols[:len(coefs)] | |
| word_vectorizer = joblib.load(pkg["vectorizer_words_path"]) | |
| char_vectorizer = joblib.load(pkg["vectorizer_chars_path"]) | |
| feature_names = [] | |
| for f in cols: | |
| if f.startswith("ngram_word_"): | |
| idx = int(f.split("_")[-1]) | |
| feature_names.append(f"Word: '{word_vectorizer.get_feature_names_out()[idx]}'") | |
| elif f.startswith("ngram_char_"): | |
| idx = int(f.split("_")[-1]) | |
| feature_names.append(f"Char: '{char_vectorizer.get_feature_names_out()[idx]}'") | |
| else: | |
| feature_names.append(f) | |
| coef_df = pd.DataFrame({"feature": feature_names, "coef": coefs}) | |
| coef_df = coef_df.sort_values(by="coef", ascending=False) | |
| top_ai = coef_df.head(5) | |
| top_human = coef_df.tail(5) | |
| top_plot = pd.concat([top_ai, top_human]).sort_values(by="coef", ascending=True) | |
| plt.figure(figsize=(10, 6)) | |
| colors = ["#3f51b5" if val < 0 else "#e91e63" for val in top_plot["coef"]] | |
| bars = plt.barh(top_plot["feature"], top_plot["coef"], color=colors, alpha=0.85) | |
| plt.axvline(x=0, color="#222222", linewidth=1.0) | |
| for bar in bars: | |
| width = bar.get_width() | |
| label_x = width + (0.05 if width >= 0 else -0.55) | |
| align = 'left' if width >= 0 else 'right' | |
| plt.text(label_x, bar.get_y() + bar.get_height()/2, f'{width:.3f}', | |
| va='center', ha=align, fontsize=10, fontweight='bold', | |
| color='#333333') | |
| plt.title("Top 10 des caractéristiques discriminantes (Coefficients de Régression)", fontsize=14, fontweight="bold", pad=15) | |
| plt.xlabel("Importance du coefficient (négatif = Humain, positif = IA)", fontsize=12) | |
| plt.ylabel("Caractéristique", fontsize=12) | |
| plt.text(0.95, 0.05, "Indique Style IA →", transform=plt.gca().transAxes, color="#e91e63", fontweight="bold", ha="right", fontsize=11) | |
| plt.text(0.05, 0.05, "← Indique Style Humain", transform=plt.gca().transAxes, color="#3f51b5", fontweight="bold", ha="left", fontsize=11) | |
| plt.tight_layout() | |
| plot5_path = os.path.join(plots_dir, "top_features.png") | |
| plt.savefig(plot5_path, dpi=300) | |
| plt.savefig(os.path.join(output_dir, "top_features.png"), dpi=300) | |
| plt.close() | |
| # --- Plotly Interactive HTML Map --- | |
| print("Generating Plotly Interactive Explorer (interactive_map.html)...") | |
| import plotly.express as px | |
| # Create copy of dataframe to avoid modifying original | |
| df_plotly = df.copy() | |
| df_plotly["date_str"] = df_plotly["date"].dt.strftime("%Y-%m-%d") | |
| # Epsilon for log scale | |
| df_plotly["prob_ai_plot"] = df_plotly["prob_ai"] + 1e-4 | |
| # Clean text for hover tooltip (max 200 chars) | |
| df_plotly["snippet"] = df_plotly["text"].apply(lambda t: (t[:200] + "...") if isinstance(t, str) and len(t) > 200 else str(t)) | |
| # Map predictions to human readable labels | |
| df_plotly["type_predit"] = df_plotly["prediction"].map({0: "Humain", 1: "IA"}) | |
| fig_interactive = px.scatter( | |
| df_plotly, | |
| 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 du modèle", | |
| "speaker": "Député / Orateur", | |
| "document_type": "Type de document", | |
| "prob_ai": "Probabilité d'IA", | |
| "type_predit": "Classification", | |
| "date_str": "Date", | |
| "snippet": "Extrait du texte" | |
| }, | |
| title="Explorateur Interactif de Détection d'IA dans les Débats Parlementaires Français (2004-2026)" | |
| ) | |
| # Customize layout and add custom log ticks | |
| fig_interactive.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"), | |
| hoverlabel=dict( | |
| bgcolor="white", | |
| font_size=12, | |
| font_family="Arial" | |
| ), | |
| legend_title_text="Groupe politique" | |
| ) | |
| # Save the interactive chart as HTML | |
| html_out_path = os.path.join(output_dir, "interactive_map.html") | |
| fig_interactive.write_html(html_out_path) | |
| # Save to plots dir as well | |
| fig_interactive.write_html(os.path.join(plots_dir, "interactive_map.html")) | |
| print(f"Plotly interactive map saved to {html_out_path}") | |
| print(f"All plots saved in {plots_dir} and duplicate copies in {output_dir}.") | |
| if __name__ == "__main__": | |
| main() | |