Download scripts/evaluate_dataset.py from simonlesaumon/AI_DETECTOR_SOTA: direct link, hf CLI and curl.
- Browser
- Download file 7.8 kB
-
https://huggingface.co/datasets/simonlesaumon/AI_DETECTOR_SOTA/resolve/main/scripts/evaluate_dataset.py
- Command line
-
hf download hf://datasets/simonlesaumon/AI_DETECTOR_SOTA/scripts/evaluate_dataset.py
-
curl -L -o evaluate_dataset.py https://huggingface.co/datasets/simonlesaumon/AI_DETECTOR_SOTA/resolve/main/scripts/evaluate_dataset.py
7.8 kB
| #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| """ | |
| evaluate_dataset.py — Script d'évaluation du détecteur SOTA v2 sur le corpus public 'DiscoursPublics' de Hugging Face. | |
| Ce script charge le dataset 'OpenLLM-France/Lucie-Training-Dataset' (config 'DiscoursPublics'), | |
| extrait un échantillon représentatif, applique le modèle hybride v2, | |
| puis calcule la proportion de discours flagués comme IA, agrégée par année. | |
| """ | |
| import os | |
| import sys | |
| import time | |
| import re | |
| import argparse | |
| import yaml | |
| import joblib | |
| import numpy as np | |
| import pandas as pd | |
| from datasets import load_dataset | |
| from joblib import Parallel, delayed | |
| from tqdm import tqdm | |
| sys.path.append(os.path.dirname(os.path.abspath(__file__))) | |
| from build_features_v2 import extract_sota_features, STYLOMETRIC_COLS_V2 | |
| from camembert_encoder import CamemBERTEncoder | |
| def load_config(config_path="configs/config.yaml"): | |
| if os.path.exists(config_path): | |
| with open(config_path, "r", encoding="utf-8") as f: | |
| return yaml.safe_load(f) | |
| return {"paths": {"models_dir": "models", "output_dir": "output"}} | |
| def parse_french_date_to_year(date_str): | |
| """Extrait l'année à 4 chiffres à partir d'une date textuelle en français (ex. '18 mai 1987').""" | |
| if not isinstance(date_str, str): | |
| return None | |
| date_str = date_str.lower().strip() | |
| match = re.search(r'\b(19\d{2}|20\d{2})\b', date_str) | |
| if match: | |
| return int(match.group(1)) | |
| return None | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Evaluate SOTA v2 model on Lucie DiscoursPublics dataset.") | |
| parser.add_argument("--sample_size", type=int, default=20000, help="Number of speeches to sample (0 for all)") | |
| parser.add_argument("--config", default="configs/config.yaml", help="Path to config file") | |
| args = parser.parse_args() | |
| config = load_config(args.config) | |
| models_dir = config.get("paths", {}).get("models_dir", "models") | |
| output_dir = config.get("paths", {}).get("output_dir", "output") | |
| os.makedirs(output_dir, exist_ok=True) | |
| # 1. Load SOTA v2 Model | |
| model_path = os.path.join(models_dir, "best_detector_v2.pkl") | |
| if not os.path.exists(model_path): | |
| print(f"Error: Model file {model_path} not found. Train the model first.") | |
| sys.exit(1) | |
| print("Loading SOTA v2 model package...") | |
| pkg = joblib.load(model_path) | |
| xgb_raw = pkg["xgb_raw"] | |
| scalers = pkg["scalers"] | |
| print(f"Loaded: {pkg['model_name']}") | |
| # 2. Load dataset | |
| print("\nLoading dataset 'OpenLLM-France/Lucie-Training-Dataset' (config: DiscoursPublics) from Hugging Face...") | |
| dataset = load_dataset("OpenLLM-France/Lucie-Training-Dataset", name="DiscoursPublics", split="train") | |
| n_total = len(dataset) | |
| print(f"Loaded {n_total} speeches.") | |
| # Create DataFrame to work with metadata | |
| df_raw = pd.DataFrame({ | |
| "date": dataset["date"], | |
| "author": dataset["author"], | |
| "title": dataset["title"], | |
| "text": dataset["text"] | |
| }) | |
| # Clean text inputs | |
| df_raw["text"] = df_raw["text"].fillna("").astype(str) | |
| # Parse years | |
| df_raw["year"] = df_raw["date"].apply(parse_french_date_to_year) | |
| # Filter out empty years or empty texts | |
| df_clean = df_raw[(df_raw["text"].str.strip().str.len() > 10) & (df_raw["year"].notna())].copy() | |
| df_clean["year"] = df_clean["year"].astype(int) | |
| print(f"Cleaned dataset has {len(df_clean)} speeches with valid years.") | |
| # Sample if requested | |
| if args.sample_size > 0 and args.sample_size < len(df_clean): | |
| print(f"Sampling {args.sample_size} speeches randomly (seed=42)...") | |
| df = df_clean.sample(n=args.sample_size, random_state=42).reset_index(drop=True) | |
| else: | |
| df = df_clean.reset_index(drop=True) | |
| print("Using the full cleaned dataset.") | |
| print("\nDistribution of sampled speeches by year:") | |
| year_counts = df["year"].value_counts().sort_index() | |
| for y, count in year_counts.items(): | |
| print(f" {y}: {count} speeches") | |
| # 3. Extract Stylometrics | |
| print("\n🔬 Step 1/3: Extracting 30 stylometric features (CPU Parallel)...") | |
| connecteurs = config.get("features", {}).get("connecteurs", [ | |
| "en effet", "par conséquent", "en outre", "néanmoins", "toutefois", "cependant" | |
| ]) | |
| start_time = time.time() | |
| sty_dicts = Parallel(n_jobs=-1)( | |
| delayed(extract_sota_features)(text, connecteurs) for text in tqdm(df["text"], desc="Stylometrics") | |
| ) | |
| df_sty = pd.DataFrame(sty_dicts) | |
| sty_elapsed = time.time() - start_time | |
| print(f"Stylometrics extraction completed in {sty_elapsed:.1f}s ({len(df)/sty_elapsed:.2f} texts/s)") | |
| # 4. Extract CamemBERT Embeddings | |
| print("\n🧠 Step 2/3: Extracting CamemBERT embeddings (GPU)...") | |
| encoder = CamemBERTEncoder(device="cuda") | |
| start_time = time.time() | |
| embeddings = encoder.encode_batch(df["text"].tolist(), batch_size=128) | |
| emb_elapsed = time.time() - start_time | |
| print(f"CamemBERT encoding completed in {emb_elapsed:.1f}s ({len(df)/emb_elapsed:.2f} texts/s)") | |
| # 5. Scale and Concat | |
| print("\n⚙️ Step 3/3: Scaling and running XGBoost classification...") | |
| X_sty = df_sty[STYLOMETRIC_COLS_V2].values | |
| X_sty_scaled = scalers["sty"].transform(X_sty) | |
| X_emb_scaled = scalers["emb"].transform(embeddings) | |
| X_combined = np.hstack([X_sty_scaled, X_emb_scaled]) | |
| # Run prediction | |
| prob_ai = xgb_raw.predict_proba(X_combined)[:, 1] | |
| predictions = (prob_ai >= 0.5).astype(int) | |
| df["prob_ai"] = prob_ai | |
| df["prediction_ai"] = predictions | |
| # Save detailed predictions | |
| preds_out_path = os.path.join(output_dir, "lucie_speeches_predictions.csv") | |
| df[["date", "author", "title", "year", "prob_ai", "prediction_ai"]].to_csv(preds_out_path, index=False) | |
| print(f"Detailed predictions saved to {preds_out_path}") | |
| # 6. Aggregate results by year | |
| print("\n" + "=" * 70) | |
| print("ANALYSIS RESULTS BY YEAR (LUCIE DISCOURSPUBLICS)") | |
| print("=" * 70) | |
| summary = df.groupby("year").agg( | |
| total_speeches=("prediction_ai", "count"), | |
| flagged_ai=("prediction_ai", "sum"), | |
| mean_prob_ai=("prob_ai", "mean") | |
| ).reset_index() | |
| summary["pct_flagged_ai"] = (summary["flagged_ai"] / summary["total_speeches"]) * 100 | |
| # Sort and save summary | |
| summary = summary.sort_values(by="year") | |
| summary_path = os.path.join(output_dir, "lucie_speeches_summary_by_year.csv") | |
| summary.to_csv(summary_path, index=False) | |
| print(f"Yearly summary saved to {summary_path}\n") | |
| # Display table in output | |
| print(f"{'Year':<6} | {'Total Speeches':<15} | {'Flagged AI':<12} | {'% Flagged':<10} | {'Mean Prob AI':<12}") | |
| print("-" * 65) | |
| for _, row in summary.iterrows(): | |
| print(f"{int(row['year']):<6} | {int(row['total_speeches']):<15} | {int(row['flagged_ai']):<12} | {row['pct_flagged_ai']:<9.2f}% | {row['mean_prob_ai']:<12.4f}") | |
| # Overall summary metrics | |
| pre_2022 = df[df["year"] < 2022] | |
| post_2022 = df[df["year"] >= 2022] | |
| print("\n" + "=" * 70) | |
| print("SUMMARY METRICS") | |
| print("=" * 70) | |
| if len(pre_2022) > 0: | |
| pre_flagged = pre_2022["prediction_ai"].sum() | |
| pre_pct = (pre_flagged / len(pre_2022)) * 100 | |
| print(f"Pre-2022 False Positive Rate (All human speeches): {pre_pct:.2f}% ({pre_flagged}/{len(pre_2022)})") | |
| if len(post_2022) > 0: | |
| post_flagged = post_2022["prediction_ai"].sum() | |
| post_pct = (post_flagged / len(post_2022)) * 100 | |
| print(f"Post-2022 Flagged AI Rate (Speeches with potential AI support): {post_pct:.2f}% ({post_flagged}/{len(post_2022)})") | |
| print("\n✅ Evaluation complete!") | |
| if __name__ == "__main__": | |
| main() | |