| |
| |
| """ |
| build_features_v2.py — Module d'extraction de features SOTA pour la détection de texte IA en français. |
| |
| Ce module calcule 30 features stylométriques avancées couvrant : |
| - Structure du texte (8 features) |
| - Richesse lexicale profonde (6 features) |
| - Discours et style (8 features) |
| - Syntaxe et grammaire (8 features) |
| |
| Utilisable : |
| - En tant que module importable : `from build_features_v2 import extract_sota_features` |
| - En tant que script CLI autonome : `python scripts/build_features_v2.py` |
| |
| Auteur : Pipeline de détection IA parlementaire française |
| """ |
|
|
| import os |
| import re |
| import sys |
| import math |
| import yaml |
| import argparse |
| from collections import Counter |
|
|
| import numpy as np |
| import pandas as pd |
| from sklearn.feature_extraction.text import TfidfVectorizer |
| import joblib |
| from tqdm import tqdm |
|
|
| |
| |
| |
|
|
| |
| 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' |
| ] |
|
|
| |
| STOPWORDS = { |
| "le", "la", "les", "de", "des", "du", "d'", "l'", "un", "une", "et", "en", "que", "qui", |
| "pour", "dans", "ce", "ces", "se", "par", "sur", "ou", "a", "au", "aux", "est", "sont", |
| "ont", "aussi", "avec", "mais", "pas", "plus", "ne", "je", "tu", "il", "nous", "vous", |
| "ils", "elle", "elles", "on", "y", "en", "qu'", "ceux", "celles", "ceci", "cela", "c'" |
| } |
|
|
| |
| PUNCTUATION_CHARS = ".,!?;:-()\"'«»" |
|
|
| |
| MOTS_POSITIFS = { |
| "progrès", "excellent", "réussite", "succès", "améliorer", "positif", |
| "formidable", "bravo", "bénéfique", "favorable", "opportunité", "espoir", |
| "avancée", "victoire", "satisfaisant", "encourageant", "remarquable", |
| "efficace", "innovation", "croissance", "bon", "bonne", "bien", |
| "meilleur", "soutien", "confiance", "prospérité", "féliciter" |
| } |
|
|
| MOTS_NEGATIFS = { |
| "échec", "problème", "crise", "danger", "grave", "inquiétant", |
| "catastrophe", "menace", "dégradation", "détérioration", "néfaste", |
| "inacceptable", "scandale", "régression", "pire", "risque", "malheureux", |
| "défaillance", "préoccupant", "alarmant", "difficile", "mauvais", |
| "mauvaise", "pénurie", "injustice", "souffrance", "déficit", "déclin" |
| } |
|
|
| |
| SUBORDINATEURS = { |
| "que", "qui", "dont", "où", "lequel", "laquelle", "lesquels", |
| "auxquels", "quand", "comme", "si", "car", "puisque", "lorsque" |
| } |
|
|
|
|
| |
| |
| |
|
|
| def load_config(config_path): |
| """Charge la configuration depuis un fichier YAML.""" |
| with open(config_path, "r", encoding="utf-8") as f: |
| return yaml.safe_load(f) |
|
|
|
|
| def tokenize(text): |
| """Tokeniseur simple pour le français — identique à build_features.py.""" |
| |
| text_clean = re.sub(r"[^\w\d'\-]", " ", text.lower()) |
| words = text_clean.split() |
| return words |
|
|
|
|
| def get_sentences(text): |
| """Segmenteur de phrases simple — identique à build_features.py.""" |
| |
| sentences = re.split(r"(?<=[.!?])\s+|\n+", text) |
| |
| sentences = [s.strip() for s in sentences if s.strip()] |
| return sentences |
|
|
|
|
| |
| |
| |
|
|
| def extract_sota_features(text, connecteurs_list): |
| """ |
| Extrait 30 features stylométriques SOTA à partir d'un texte français. |
| |
| Paramètres |
| ---------- |
| text : str |
| Le texte à analyser. |
| connecteurs_list : list[str] |
| Liste des connecteurs discursifs (depuis la configuration). |
| |
| Retourne |
| -------- |
| dict |
| Dictionnaire avec exactement 30 clés correspondant à STYLOMETRIC_COLS_V2. |
| """ |
| |
| if not text or not isinstance(text, str) or len(text.strip()) == 0: |
| return {col: 0.0 for col in STYLOMETRIC_COLS_V2} |
|
|
| |
| |
| |
|
|
| features = {} |
| text_lower = text.lower() |
|
|
| |
| features["num_chars"] = len(text) |
|
|
| |
| words = tokenize(text) |
| n_words = len(words) |
| features["num_words"] = n_words |
|
|
| |
| sentences = get_sentences(text) |
| n_sentences = len(sentences) |
| features["num_sentences"] = n_sentences |
|
|
| |
| sent_lens = [len(tokenize(s)) for s in sentences] |
| sent_lens = [sl for sl in sent_lens if sl > 0] |
|
|
| if sent_lens: |
| mu = np.mean(sent_lens) |
| sigma = np.std(sent_lens) if len(sent_lens) > 1 else 0.0 |
| features["avg_sentence_len"] = float(mu) |
| features["std_sentence_len"] = float(sigma) |
| |
| slv = sigma ** 2 |
| features["slv_normalized"] = float(slv / (mu ** 2 + 1e-8)) |
| else: |
| features["avg_sentence_len"] = 0.0 |
| features["std_sentence_len"] = 0.0 |
| features["slv_normalized"] = 0.0 |
|
|
| |
| if n_words > 0: |
| word_lens = [len(w) for w in words] |
| features["avg_word_len"] = float(np.mean(word_lens)) |
| long_words = sum(1 for wl in word_lens if wl > 6) |
| features["ratio_long_words"] = long_words / n_words |
| else: |
| features["avg_word_len"] = 0.0 |
| features["ratio_long_words"] = 0.0 |
|
|
| |
| |
| |
|
|
| if n_words > 0: |
| word_counts = Counter(words) |
| V = len(word_counts) |
| N = n_words |
|
|
| |
| features["vocabulary_diversity"] = V / N |
|
|
| |
| hapaxes = sum(1 for _w, c in word_counts.items() if c == 1) |
| features["hapax_ratio"] = hapaxes / N |
|
|
| |
| |
| |
| freq_spectrum = Counter(word_counts.values()) |
| somme = sum(i * i * fi for i, fi in freq_spectrum.items()) |
| features["yules_k"] = float(10000.0 * (-1.0 / N + somme / (N * N))) |
|
|
| |
| |
| if V > 0 and N > 1: |
| ln_N = math.log(N) |
| ln_V = math.log(V) |
| features["maas_index"] = float((ln_N - ln_V) / (ln_N ** 2 + 1e-8)) |
| else: |
| features["maas_index"] = 0.0 |
|
|
| |
| |
| if V > 0: |
| features["brunet_w"] = float(N ** (V ** (-0.172))) |
| else: |
| features["brunet_w"] = 0.0 |
| else: |
| features["vocabulary_diversity"] = 0.0 |
| features["hapax_ratio"] = 0.0 |
| features["yules_k"] = 0.0 |
| features["maas_index"] = 0.0 |
| features["brunet_w"] = 0.0 |
|
|
| |
| if len(sent_lens) > 1: |
| |
| sl_array = np.array(sent_lens) |
| |
| n_bins = max(2, int(np.ceil(np.log2(len(sl_array)) + 1))) |
| counts, _ = np.histogram(sl_array, bins=n_bins) |
| |
| probs = counts[counts > 0] / counts.sum() |
| features["information_entropy"] = float(-np.sum(probs * np.log2(probs))) |
| elif len(sent_lens) == 1: |
| |
| features["information_entropy"] = 0.0 |
| else: |
| features["information_entropy"] = 0.0 |
|
|
| |
| |
| |
|
|
| n_chars = len(text) if len(text) > 0 else 1 |
|
|
| |
| punc_count = sum(1 for c in text if c in PUNCTUATION_CHARS) |
| features["ratio_punctuation"] = punc_count / n_chars |
|
|
| |
| upper_count = sum(1 for c in text if c.isupper()) |
| features["freq_uppercase"] = upper_count / n_chars |
|
|
| |
| digit_count = sum(1 for c in text if c.isdigit()) |
| features["freq_digits"] = digit_count / n_chars |
|
|
| |
| if n_words > 0 and connecteurs_list: |
| connector_count = 0 |
| connectors_found = set() |
| for conn in connecteurs_list: |
| pattern = r'\b' + re.escape(conn) + r'\b' |
| matches = re.findall(pattern, text_lower) |
| if matches: |
| connector_count += len(matches) |
| connectors_found.add(conn) |
| features["connector_ratio"] = connector_count / n_words |
| |
| features["connector_diversity"] = len(connectors_found) / len(connecteurs_list) |
| else: |
| features["connector_ratio"] = 0.0 |
| features["connector_diversity"] = 0.0 |
|
|
| |
| if n_words > 0: |
| content_words = [w for w in words if w not in STOPWORDS] |
| if content_words: |
| content_counts = Counter(content_words) |
| |
| features["repetition_ratio"] = (len(content_words) - len(content_counts)) / len(content_words) |
| else: |
| features["repetition_ratio"] = 0.0 |
| else: |
| features["repetition_ratio"] = 0.0 |
|
|
| |
| if n_words > 0: |
| stop_count = sum(1 for w in words if w in STOPWORDS) |
| features["stopword_ratio"] = stop_count / n_words |
| else: |
| features["stopword_ratio"] = 0.0 |
|
|
| |
| if n_sentences >= 2: |
| |
| polarities = [] |
| for s in sentences: |
| s_words = set(tokenize(s)) |
| pos = len(s_words & MOTS_POSITIFS) |
| neg = len(s_words & MOTS_NEGATIFS) |
| total_sent_words = len(tokenize(s)) |
| |
| if total_sent_words > 0: |
| polarities.append((pos - neg) / total_sent_words) |
| else: |
| polarities.append(0.0) |
| |
| diffs = [abs(polarities[i + 1] - polarities[i]) for i in range(len(polarities) - 1)] |
| features["mean_polarity_diff"] = float(np.mean(diffs)) |
| elif n_sentences == 1: |
| features["mean_polarity_diff"] = 0.0 |
| else: |
| features["mean_polarity_diff"] = 0.0 |
|
|
| |
| |
| |
|
|
| |
| sub_count = sum(1 for w in words if w in SUBORDINATEURS) |
| features["syntactic_complexity_score"] = sub_count / n_sentences if n_sentences > 0 else 0.0 |
|
|
| |
| if n_sentences > 0: |
| interro = sum(1 for s in sentences if s.rstrip().endswith("?")) |
| exclam = sum(1 for s in sentences if s.rstrip().endswith("!")) |
| features["ratio_interrogative"] = interro / n_sentences |
| features["ratio_exclamative"] = exclam / n_sentences |
| features["ratio_declarative"] = 1.0 - features["ratio_interrogative"] - features["ratio_exclamative"] |
| |
| features["ratio_declarative"] = max(0.0, features["ratio_declarative"]) |
| else: |
| features["ratio_interrogative"] = 0.0 |
| features["ratio_exclamative"] = 0.0 |
| features["ratio_declarative"] = 0.0 |
|
|
| |
| |
| imparfait = len(re.findall(r'\b\w+(?:ais|ait|ions|iez|aient)\b', text_lower)) |
| |
| futur = len(re.findall(r'\b\w+(?:rai|ras|ra|rons|rez|ront)\b', text_lower)) |
| |
| conditional = len(re.findall(r'\b\w+(?:rais|rait|rions|riez|raient)\b', text_lower)) |
|
|
| |
| total_verbs_est = imparfait + futur + conditional + 1 |
| features["imparfait_ratio"] = imparfait / total_verbs_est |
| features["futur_ratio"] = futur / total_verbs_est |
| features["conditional_ratio"] = conditional / total_verbs_est |
|
|
| |
| |
| passive_pattern = r'\b(?:est|sont|a\s+été|ont\s+été|fut|furent|sera|seront)\s+\w+(?:é|ée|és|ées|i|is|it|u|us|ue|ues|ert|erts|erte|ertes|int|ints|inte|intes)\b' |
| passive_count = len(re.findall(passive_pattern, text_lower)) |
| features["passive_voice_ratio"] = passive_count / n_sentences if n_sentences > 0 else 0.0 |
|
|
| return features |
|
|
|
|
| |
| |
| |
|
|
| def main(): |
| """ |
| Point d'entrée CLI : traite les corpus bruts, extrait les features SOTA, |
| ajuste les vectoriseurs TF-IDF et sauvegarde les résultats. |
| """ |
| parser = argparse.ArgumentParser( |
| description="Extraction de features SOTA v2 pour la détection de texte IA en français." |
| ) |
| parser.add_argument( |
| "--config", default="configs/config.yaml", |
| help="Chemin vers le fichier de configuration YAML" |
| ) |
| args = parser.parse_args() |
|
|
| |
| config = load_config(args.config) |
| raw_dir = config["paths"]["raw_dir"] |
| processed_dir = config["paths"]["processed_dir"] |
| models_dir = config["paths"]["models_dir"] |
| os.makedirs(processed_dir, exist_ok=True) |
| os.makedirs(models_dir, exist_ok=True) |
|
|
| connecteurs = config["features"]["connecteurs"] |
|
|
| |
| |
| |
|
|
| print("=" * 70) |
| print(" BUILD FEATURES V2 — Extraction SOTA") |
| print("=" * 70) |
| print() |
|
|
| print("📂 Chargement des corpus d'entraînement bruts...") |
| human_path = os.path.join(raw_dir, "human_corpus.csv") |
| ai_path = os.path.join(raw_dir, "ai_corpus.csv") |
|
|
| if not os.path.exists(human_path) or not os.path.exists(ai_path): |
| print("❌ Erreur : données brutes introuvables !") |
| print(" Veuillez exécuter 'python scripts/collect_data.py' au préalable.") |
| sys.exit(1) |
|
|
| df_human = pd.read_csv(human_path) |
| df_ai = pd.read_csv(ai_path) |
|
|
| |
| df_train = pd.concat([df_human, df_ai], ignore_index=True) |
| print(f" → {len(df_human)} textes humains + {len(df_ai)} textes IA = {len(df_train)} total") |
| print() |
|
|
| |
| print("🔬 Extraction des 30 features stylométriques SOTA (entraînement)...") |
| train_features_list = [] |
| for text in tqdm(df_train["text"], desc=" Features entraînement", unit="texte"): |
| |
| if not isinstance(text, str): |
| text = str(text) if pd.notna(text) else "" |
| train_features_list.append(extract_sota_features(text, connecteurs)) |
|
|
| df_sty = pd.DataFrame(train_features_list) |
| df_train_feats = pd.concat([df_train.reset_index(drop=True), df_sty], axis=1) |
| print(f" → {len(STYLOMETRIC_COLS_V2)} features extraites avec succès.") |
| print() |
|
|
| |
| print("📊 Ajustement des vectoriseurs TF-IDF n-grammes...") |
|
|
| |
| texts_for_tfidf = df_train_feats["text"].fillna("").astype(str) |
|
|
| |
| word_vectorizer = TfidfVectorizer( |
| ngram_range=(1, 2), |
| max_features=50, |
| stop_words=None |
| ) |
| word_tfidf = word_vectorizer.fit_transform(texts_for_tfidf) |
| word_cols = [f"ngram_word_{i}" for i in range(word_tfidf.shape[1])] |
| df_word_ngrams = pd.DataFrame(word_tfidf.toarray(), columns=word_cols) |
|
|
| |
| char_vectorizer = TfidfVectorizer( |
| analyzer='char', |
| ngram_range=(3, 4), |
| max_features=50 |
| ) |
| char_tfidf = char_vectorizer.fit_transform(texts_for_tfidf) |
| char_cols = [f"ngram_char_{i}" for i in range(char_tfidf.shape[1])] |
| df_char_ngrams = pd.DataFrame(char_tfidf.toarray(), columns=char_cols) |
|
|
| print(f" → Mots : {word_tfidf.shape[1]} features n-grammes") |
| print(f" → Chars : {char_tfidf.shape[1]} features n-grammes") |
| print() |
|
|
| |
| word_vec_path = os.path.join(models_dir, "word_vectorizer_v2.pkl") |
| char_vec_path = os.path.join(models_dir, "char_vectorizer_v2.pkl") |
| joblib.dump(word_vectorizer, word_vec_path) |
| joblib.dump(char_vectorizer, char_vec_path) |
| print(f"💾 Vectoriseurs sauvegardés :") |
| print(f" → {word_vec_path}") |
| print(f" → {char_vec_path}") |
| print() |
|
|
| |
| df_train_final = pd.concat( |
| [df_train_feats.reset_index(drop=True), |
| df_word_ngrams.reset_index(drop=True), |
| df_char_ngrams.reset_index(drop=True)], |
| axis=1 |
| ) |
|
|
| train_output = os.path.join(processed_dir, "train_features_v2.csv") |
| df_train_final.to_csv(train_output, index=False) |
| print(f"✅ Dataset d'entraînement sauvegardé : {train_output}") |
| print(f" → {df_train_final.shape[0]} lignes × {df_train_final.shape[1]} colonnes") |
| print() |
|
|
| |
| |
| |
|
|
| print("📂 Chargement des débats récents pour inférence...") |
| recent_path = os.path.join(raw_dir, "recent_debates.csv") |
|
|
| if os.path.exists(recent_path): |
| df_recent = pd.read_csv(recent_path) |
| print(f" → {len(df_recent)} textes de débats récents") |
| print() |
|
|
| |
| print("🔬 Extraction des features SOTA (débats récents)...") |
| recent_features_list = [] |
| for text in tqdm(df_recent["text"], desc=" Features récents", unit="texte"): |
| if not isinstance(text, str): |
| text = str(text) if pd.notna(text) else "" |
| recent_features_list.append(extract_sota_features(text, connecteurs)) |
|
|
| df_recent_sty = pd.DataFrame(recent_features_list) |
| df_recent_feats = pd.concat( |
| [df_recent.reset_index(drop=True), df_recent_sty], |
| axis=1 |
| ) |
|
|
| |
| recent_texts = df_recent_feats["text"].fillna("").astype(str) |
|
|
| recent_word_tfidf = word_vectorizer.transform(recent_texts) |
| df_recent_word_ngrams = pd.DataFrame(recent_word_tfidf.toarray(), columns=word_cols) |
|
|
| recent_char_tfidf = char_vectorizer.transform(recent_texts) |
| df_recent_char_ngrams = pd.DataFrame(recent_char_tfidf.toarray(), columns=char_cols) |
|
|
| |
| df_recent_final = pd.concat( |
| [df_recent_feats.reset_index(drop=True), |
| df_recent_word_ngrams.reset_index(drop=True), |
| df_recent_char_ngrams.reset_index(drop=True)], |
| axis=1 |
| ) |
|
|
| recent_output = os.path.join(processed_dir, "recent_features_v2.csv") |
| df_recent_final.to_csv(recent_output, index=False) |
| print(f"✅ Dataset débats récents sauvegardé : {recent_output}") |
| print(f" → {df_recent_final.shape[0]} lignes × {df_recent_final.shape[1]} colonnes") |
| else: |
| print("⚠️ Aucun fichier de débats récents trouvé dans le répertoire brut.") |
| print(f" Chemin attendu : {recent_path}") |
|
|
| print() |
| print("=" * 70) |
| print(" ✅ Extraction de features v2 terminée avec succès !") |
| print("=" * 70) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|