| import os |
| import sys |
| import yaml |
| import argparse |
| import pandas as pd |
| import numpy as np |
| import joblib |
| from sklearn.metrics import f1_score |
| sys.path.append(os.path.dirname(os.path.abspath(__file__))) |
| from models import SOTAStackingDetector |
|
|
| def load_config(config_path): |
| with open(config_path, "r", encoding="utf-8") as f: |
| return yaml.safe_load(f) |
|
|
| def get_local_explanation(model_key, model, X_scaled, feature_names): |
| """Calculates local explanations (which features pushed the prediction towards AI or Human).""" |
| if "logistic_regression" in model_key or "hybrid" in model_key: |
| coefs = model.coef_[0] |
| |
| num_coefs = len(coefs) |
| X_scaled_subset = X_scaled[:, :num_coefs] |
| |
| |
| contributions = X_scaled_subset * coefs |
| |
| top_ai_idx = np.argmax(contributions, axis=1) |
| top_human_idx = np.argmin(contributions, axis=1) |
| |
| top_ai_feats = [feature_names[idx] for idx in top_ai_idx] |
| top_human_feats = [feature_names[idx] for idx in top_human_idx] |
| |
| return top_ai_feats, top_human_feats |
| else: |
| |
| |
| return ["global_importance"] * X_scaled.shape[0], ["global_importance"] * X_scaled.shape[0] |
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="Run inference on recent debates to detect potential AI content.") |
| parser.add_argument("--config", default="configs/config.yaml", help="Path to config file") |
| 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) |
| |
| |
| model_pkg_path = os.path.join(models_dir, "best_detector.pkl") |
| if not os.path.exists(model_pkg_path): |
| print(f"Error: Trained model package not found at {model_pkg_path}. Please run train_detector.py first.") |
| sys.exit(1) |
| |
| pkg = joblib.load(model_pkg_path) |
| model = pkg["model"] |
| model_key = pkg["model_key"] |
| model_name = pkg["model_name"] |
| scalers = pkg["scalers"] |
| |
| print(f"Loaded best model: {model_name} ({model_key})") |
| |
| |
| recent_path = os.path.join(processed_dir, "recent_features.csv") |
| if not os.path.exists(recent_path): |
| print(f"Error: Processed recent debates features not found at {recent_path}. Please run build_features.py first.") |
| sys.exit(1) |
| |
| df_recent = pd.read_csv(recent_path) |
| print(f"Loaded {len(df_recent)} recent speeches for inference.") |
| |
| |
| if model_key == "logistic_regression_sty": |
| cols_to_use = pkg["stylometric_cols"] |
| scaler = scalers["sty"] |
| elif model_key == "logistic_regression_ng": |
| cols_to_use = pkg["ngram_cols"] |
| scaler = None |
| elif model_key == "xgb_sty": |
| cols_to_use = pkg["stylometric_cols"] |
| scaler = None |
| elif model_key == "hybrid": |
| cols_to_use = pkg["hybrid_cols"] |
| scaler = scalers["hybrid"] |
| else: |
| raise ValueError(f"Unknown model key {model_key}") |
| |
| |
| X = df_recent[cols_to_use].values |
| if scaler is not None: |
| X_scaled = scaler.transform(X) |
| else: |
| X_scaled = X |
| |
| |
| print("Running model inference...") |
| prob_ai = model.predict_proba(X_scaled)[:, 1] |
| predictions = model.predict(X_scaled) |
| |
| |
| prob_human = 1.0 - prob_ai |
| confidence = 2.0 * np.abs(prob_ai - 0.5) |
| |
| |
| df_recent["prob_ai"] = prob_ai |
| df_recent["prob_human"] = prob_human |
| df_recent["prediction"] = predictions |
| df_recent["confidence_score"] = confidence |
| |
| |
| |
| word_vectorizer = joblib.load(pkg["vectorizer_words_path"]) |
| char_vectorizer = joblib.load(pkg["vectorizer_chars_path"]) |
| |
| friendly_feature_names = [] |
| for f in cols_to_use: |
| if f.startswith("ngram_word_"): |
| idx = int(f.split("_")[-1]) |
| friendly_feature_names.append(f"Word n-gram: '{word_vectorizer.get_feature_names_out()[idx]}'") |
| elif f.startswith("ngram_char_"): |
| idx = int(f.split("_")[-1]) |
| friendly_feature_names.append(f"Char n-gram: '{char_vectorizer.get_feature_names_out()[idx]}'") |
| else: |
| friendly_feature_names.append(f) |
| |
| top_ai_feats, top_human_feats = get_local_explanation(model_key, model, X_scaled, friendly_feature_names) |
| df_recent["explanation_top_ai_feature"] = top_ai_feats |
| df_recent["explanation_top_human_feature"] = top_human_feats |
| |
| |
| predictions_path = os.path.join(output_dir, "recent_debates_predictions.csv") |
| |
| 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" |
| ] |
| if "actual_label" in df_recent.columns: |
| cols_to_save.append("actual_label") |
| if "ai_model" in df_recent.columns: |
| cols_to_save.append("ai_model") |
| |
| df_recent_out = df_recent[cols_to_save + ["text"]] |
| df_recent_out.to_csv(predictions_path, index=False) |
| print(f"Saved inference predictions to {predictions_path}") |
| |
| |
| df_recent["date_dt"] = pd.to_datetime(df_recent["date"]) |
| df_recent["year"] = df_recent["date_dt"].dt.year |
| df_recent["week"] = df_recent["date_dt"] - pd.to_timedelta(df_recent["date_dt"].dt.weekday, unit='D') |
| |
| print("\n--- Aggregating suspicion scores ---") |
| |
| |
| year_stats = df_recent.groupby("year")["prob_ai"].agg(["count", "mean", "std"]).reset_index() |
| year_stats.columns = ["year", "speech_count", "mean_ai_suspicion", "std_ai_suspicion"] |
| year_stats.to_csv(os.path.join(output_dir, "stats_by_year.csv"), index=False) |
| print("\nSuspicion Score by Year (recent period):") |
| print(year_stats.to_string(index=False)) |
| |
| |
| week_stats = df_recent.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.csv"), index=False) |
| print(f"\nSaved weekly aggregated suspicion scores to {os.path.join(output_dir, 'stats_by_week.csv')} ({len(week_stats)} weeks)") |
| |
| |
| deputy_stats = df_recent.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.csv"), index=False) |
| print("\nTop 5 Deputies by AI Suspicion Score:") |
| print(deputy_stats.head(5).to_string(index=False)) |
| |
| |
| party_stats = df_recent.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.csv"), index=False) |
| print("\nSuspicion Score by Political Party:") |
| print(party_stats.to_string(index=False)) |
| |
| |
| doc_stats = df_recent.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 = doc_stats.sort_values(by="mean_ai_suspicion", ascending=False) |
| doc_stats.to_csv(os.path.join(output_dir, "stats_by_doc_type.csv"), index=False) |
| print("\nSuspicion Score by Document Type:") |
| print(doc_stats.to_string(index=False)) |
| |
| |
| if "actual_label" in df_recent.columns: |
| actuals = df_recent["actual_label"].values |
| acc = (predictions == actuals).mean() |
| f1 = f1_score(actuals, predictions, zero_division=0) |
| print(f"\nInference evaluation against ground-truth labels:") |
| print(f"Accuracy: {acc:.4f} | F1-Score: {f1:.4f}") |
| |
| print("\nInference step completed successfully.") |
|
|
| if __name__ == "__main__": |
| main() |
|
|