AI_DETECTOR_SOTA / scripts /infer_v2.py
simonlesaumon's picture
Upload folder using huggingface_hub
eb72d30 verified
Raw
History Blame Contribute Delete
7.86 kB
import os
import sys
import yaml
import argparse
import pandas as pd
import numpy as np
import joblib
import shap
from sklearn.metrics import f1_score, accuracy_score
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from models_v2 import SOTAHybridDetector
STYLOMETRIC_COLS_V2 = [
'num_chars', 'num_words', 'num_sentences', 'avg_sentence_len', 'std_sentence_len',
'slv_normalized', 'avg_word_len', 'ratio_long_words',
'vocabulary_diversity', 'hapax_ratio', 'yules_k', 'maas_index',
'information_entropy', 'brunet_w',
'ratio_punctuation', 'freq_uppercase', 'freq_digits',
'connector_ratio', 'connector_diversity', 'repetition_ratio',
'stopword_ratio', 'mean_polarity_diff',
'syntactic_complexity_score', 'ratio_interrogative', 'ratio_exclamative',
'ratio_declarative', 'imparfait_ratio', 'futur_ratio',
'conditional_ratio', 'passive_voice_ratio'
]
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="Inférence SOTA v2 sur les débats récents avec explications SHAP.")
parser.add_argument("--config", default="configs/config.yaml", help="Chemin vers le fichier de config")
args = parser.parse_args()
config = load_config(args.config)
processed_dir = config["paths"]["processed_dir"]
models_dir = config["paths"]["models_dir"]
output_dir = config["paths"]["output_dir"]
os.makedirs(output_dir, exist_ok=True)
# 1. Load Model Package
model_path = os.path.join(models_dir, "best_detector_v2.pkl")
if not os.path.exists(model_path):
print(f"ERREUR: Modèle v2 introuvable à {model_path}. Lancez train_sota_v2.py d'abord.")
sys.exit(1)
pkg = joblib.load(model_path)
detector = pkg["model"]
xgb_raw = pkg["xgb_raw"]
scalers = pkg["scalers"]
friendly_sty = pkg["friendly_names_sty"]
print(f"Modèle chargé: {pkg['model_name']}")
# 2. Load Recent Features
recent_sty_path = os.path.join(processed_dir, "recent_features_v2.csv")
recent_emb_path = os.path.join(processed_dir, "recent_embeddings_camembert.csv")
if not os.path.exists(recent_sty_path) or not os.path.exists(recent_emb_path):
print("ERREUR: Features récentes introuvables. Lancez build_features_v2.py et camembert_encoder.py.")
sys.exit(1)
df_sty = pd.read_csv(recent_sty_path)
df_emb = pd.read_csv(recent_emb_path)
print(f"Débats récents chargés: {len(df_sty)} textes")
# 3. Prepare Features
X_sty = df_sty[STYLOMETRIC_COLS_V2].values
emb_cols = pkg["emb_cols"]
X_emb = df_emb[emb_cols].values
# Scale and combine
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])
# 4. Predict
print("Inférence en cours...")
prob_ai = xgb_raw.predict_proba(X_combined)[:, 1]
predictions = (prob_ai >= 0.5).astype(int)
confidence = 2.0 * np.abs(prob_ai - 0.5)
df_sty["prob_ai"] = prob_ai
df_sty["prob_human"] = 1.0 - prob_ai
df_sty["prediction"] = predictions
df_sty["confidence_score"] = confidence
# 5. SHAP Explanations (on a subsample for speed)
print("Calcul des explications SHAP locales...")
explainer = shap.TreeExplainer(xgb_raw)
# For each prediction, get the top contributing stylometric feature
all_feature_names = STYLOMETRIC_COLS_V2 + emb_cols
n_sty = len(STYLOMETRIC_COLS_V2)
top_ai_features = []
top_human_features = []
shap_explanations = []
# Process in chunks for memory
chunk_size = 500
for start in range(0, len(X_combined), chunk_size):
end = min(start + chunk_size, len(X_combined))
chunk_shap = explainer.shap_values(X_combined[start:end])
for i in range(chunk_shap.shape[0]):
sv = chunk_shap[i]
# Focus on stylometric features only for interpretability
sv_sty = sv[:n_sty]
top_ai_idx = np.argmax(sv_sty)
top_human_idx = np.argmin(sv_sty)
top_ai_features.append(friendly_sty[top_ai_idx])
top_human_features.append(friendly_sty[top_human_idx])
# Build explanation string
sorted_idx = np.argsort(np.abs(sv_sty))[::-1][:3]
parts = []
for idx in sorted_idx:
direction = "→IA" if sv_sty[idx] > 0 else "→Humain"
parts.append(f"{friendly_sty[idx]} ({sv_sty[idx]:+.3f} {direction})")
shap_explanations.append(" | ".join(parts))
df_sty["explanation_top_ai_feature"] = top_ai_features
df_sty["explanation_top_human_feature"] = top_human_features
df_sty["shap_explanation"] = shap_explanations
# 6. Save predictions
cols_to_save = [
"date", "speaker", "party", "chamber", "document_type", "legislature",
"prob_ai", "prob_human", "confidence_score", "prediction",
"explanation_top_ai_feature", "explanation_top_human_feature", "shap_explanation"
]
if "actual_label" in df_sty.columns:
cols_to_save.append("actual_label")
if "ai_model" in df_sty.columns:
cols_to_save.append("ai_model")
df_out = df_sty[cols_to_save + ["text"]]
preds_path = os.path.join(output_dir, "recent_debates_predictions_v2.csv")
df_out.to_csv(preds_path, index=False)
print(f"Prédictions sauvegardées dans {preds_path}")
# 7. Aggregate Stats
df_sty["date_dt"] = pd.to_datetime(df_sty["date"])
df_sty["year"] = df_sty["date_dt"].dt.year
df_sty["week"] = df_sty["date_dt"] - pd.to_timedelta(df_sty["date_dt"].dt.weekday, unit='D')
# Weekly
week_stats = df_sty.groupby("week")["prob_ai"].agg(["count", "mean", "std"]).reset_index()
week_stats.columns = ["week", "speech_count", "mean_ai_suspicion", "std_ai_suspicion"]
week_stats = week_stats.sort_values(by="week")
week_stats_save = week_stats.copy()
week_stats_save["week"] = week_stats_save["week"].dt.strftime("%Y-%m-%d")
week_stats_save.to_csv(os.path.join(output_dir, "stats_by_week_v2.csv"), index=False)
print(f"Stats hebdomadaires: {len(week_stats)} semaines")
# By Deputy
deputy_stats = df_sty.groupby("speaker")["prob_ai"].agg(["count", "mean", "std"]).reset_index()
deputy_stats.columns = ["speaker", "speech_count", "mean_ai_suspicion", "std_ai_suspicion"]
deputy_stats = deputy_stats.sort_values(by="mean_ai_suspicion", ascending=False)
deputy_stats.to_csv(os.path.join(output_dir, "stats_by_deputy_v2.csv"), index=False)
# By Party
party_stats = df_sty.groupby("party")["prob_ai"].agg(["count", "mean", "std"]).reset_index()
party_stats.columns = ["party", "speech_count", "mean_ai_suspicion", "std_ai_suspicion"]
party_stats = party_stats.sort_values(by="mean_ai_suspicion", ascending=False)
party_stats.to_csv(os.path.join(output_dir, "stats_by_party_v2.csv"), index=False)
# By Doc Type
doc_stats = df_sty.groupby("document_type")["prob_ai"].agg(["count", "mean", "std"]).reset_index()
doc_stats.columns = ["document_type", "speech_count", "mean_ai_suspicion", "std_ai_suspicion"]
doc_stats.to_csv(os.path.join(output_dir, "stats_by_doc_type_v2.csv"), index=False)
# Accuracy if labels exist
if "actual_label" in df_sty.columns:
actuals = df_sty["actual_label"].values
acc = accuracy_score(actuals, predictions)
f1 = f1_score(actuals, predictions, zero_division=0)
print(f"\nÉvaluation vs ground-truth: Accuracy={acc:.4f} | F1={f1:.4f}")
print(f"\n✅ Inférence SOTA v2 terminée avec succès.")
if __name__ == "__main__":
main()