AI_DETECTOR_SOTA / scripts /build_features.py
simonlesaumon's picture
Upload folder using huggingface_hub
eb72d30 verified
Raw
History Blame Contribute Delete
11.3 kB
import os
import re
import sys
import yaml
import argparse
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
import joblib
# French stopwords list
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 = ".,!?;:-()\"'«»"
def load_config(config_path):
with open(config_path, "r", encoding="utf-8") as f:
return yaml.safe_load(f)
def tokenize(text):
"""Simple French word tokenizer."""
# Replace punctuation with spaces except internal apostrophes
text_clean = re.sub(r"[^\w\d'\-]", " ", text.lower())
words = text_clean.split()
return words
def get_sentences(text):
"""Simple sentence segmenter."""
# Split sentences by period, exclamation, question mark, or newline
sentences = re.split(r"(?<=[.!?])\s+|\n+", text)
# Remove empty sentences
sentences = [s.strip() for s in sentences if s.strip()]
return sentences
def extract_stylometric_features(text, connecteurs_list):
"""Extracts stylometric, lexical, and syntactic features from a French text."""
features = {}
# Raw Text Stats
features["num_chars"] = len(text)
words = tokenize(text)
features["num_words"] = len(words)
sentences = get_sentences(text)
features["num_sentences"] = len(sentences)
# Sentence lengths (word counts)
sent_lens = [len(tokenize(s)) for s in sentences if len(tokenize(s)) > 0]
if sent_lens:
features["avg_sentence_len"] = np.mean(sent_lens)
features["std_sentence_len"] = np.std(sent_lens) if len(sent_lens) > 1 else 0.0
else:
features["avg_sentence_len"] = 0.0
features["std_sentence_len"] = 0.0
# Word lengths
word_lens = [len(w) for w in words]
if word_lens:
features["avg_word_len"] = np.mean(word_lens)
long_words = sum(1 for l in word_lens if l > 6)
features["ratio_long_words"] = long_words / len(words)
else:
features["avg_word_len"] = 0.0
features["ratio_long_words"] = 0.0
# Punctuation and symbols
punc_count = sum(1 for c in text if c in PUNCTUATION_CHARS)
features["ratio_punctuation"] = punc_count / len(text) if len(text) > 0 else 0.0
uppercase_count = sum(1 for c in text if c.isupper())
features["freq_uppercase"] = uppercase_count / len(text) if len(text) > 0 else 0.0
digit_count = sum(1 for c in text if c.isdigit())
features["freq_digits"] = digit_count / len(text) if len(text) > 0 else 0.0
# Non-alphanumeric, non-punctuation, non-space characters
symbol_count = sum(1 for c in text if not c.isalnum() and c not in PUNCTUATION_CHARS and not c.isspace())
features["freq_symbols"] = symbol_count / len(text) if len(text) > 0 else 0.0
# Lexical Features
if words:
unique_words = set(words)
features["vocabulary_diversity"] = len(unique_words) / len(words)
# Hapax legomena
word_counts = {}
for w in words:
word_counts[w] = word_counts.get(w, 0) + 1
hapaxes = sum(1 for w, c in word_counts.items() if c == 1)
features["hapax_ratio"] = hapaxes / len(words)
# Stopwords
stop_count = sum(1 for w in words if w in STOPWORDS)
features["stopword_ratio"] = stop_count / len(words)
# Connectors
connector_count = 0
text_lower = text.lower()
for conn in connecteurs_list:
# Match whole phrase/word using regex word boundaries (need to escape connecteurs)
pattern = r'\b' + re.escape(conn) + r'\b'
matches = re.findall(pattern, text_lower)
connector_count += len(matches)
features["connector_ratio"] = connector_count / len(words)
# Repetition ratio of content words (non-stopwords)
content_words = [w for w in words if w not in STOPWORDS]
if content_words:
content_counts = {}
for w in content_words:
content_counts[w] = content_counts.get(w, 0) + 1
features["repetition_ratio"] = (len(content_words) - len(content_counts)) / len(content_words)
else:
features["repetition_ratio"] = 0.0
else:
features["vocabulary_diversity"] = 0.0
features["hapax_ratio"] = 0.0
features["stopword_ratio"] = 0.0
features["connector_ratio"] = 0.0
features["repetition_ratio"] = 0.0
# Syntax-like Proxy Features
# Count typical conjunctions and subordinators that indicate phrase complexity
subordinators = ["que", "qui", "dont", "où", "lequel", "laquelle", "lesquels", "auxquels", "quand", "comme", "si", "car", "puisque", "lorsque"]
sub_count = sum(1 for w in words if w in subordinators)
features["syntactic_complexity_score"] = sub_count / len(sentences) if len(sentences) > 0 else 0.0
# Sentences structure distribution
features["ratio_interrogative"] = sum(1 for s in sentences if s.endswith("?")) / len(sentences) if len(sentences) > 0 else 0.0
features["ratio_exclamative"] = sum(1 for s in sentences if s.endswith("!")) / len(sentences) if len(sentences) > 0 else 0.0
features["ratio_declarative"] = 1.0 - (features["ratio_interrogative"] + features["ratio_exclamative"])
# Verb tense approximations (simple counts of suffix occurrences)
# imparfait endings: ais, ait, ions, iez, aient
imparfait = len(re.findall(r'\b\w+(?:ais|ait|ions|iez|aient)\b', text_lower))
# futur endings: rai, ras, ra, rons, rez, ront
futur = len(re.findall(r'\b\w+(?:rai|ras|ra|rons|rez|ront)\b', text_lower))
# conditional endings: rais, rait, rions, riez, raient
conditional = len(re.findall(r'\b\w+(?:rais|rait|rions|riez|raient)\b', text_lower))
total_verbs_est = imparfait + futur + conditional + 1 # avoid division by zero
features["imparfait_ratio"] = imparfait / total_verbs_est
features["futur_ratio"] = futur / total_verbs_est
features["conditional_ratio"] = conditional / total_verbs_est
return features
def main():
parser = argparse.ArgumentParser(description="Feature engineering 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)
raw_dir = config["paths"]["raw_dir"]
processed_dir = config["paths"]["processed_dir"]
os.makedirs(processed_dir, exist_ok=True)
os.makedirs(config["paths"]["models_dir"], exist_ok=True)
connecteurs = config["features"]["connecteurs"]
# 1. Process Training Data
print("Loading raw training datasets...")
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("Error: Raw training data not found! Please run 'python scripts/collect_data.py' first.")
sys.exit(1)
df_human = pd.read_csv(human_path)
df_ai = pd.read_csv(ai_path)
# Concatenate training corpora
df_train = pd.concat([df_human, df_ai], ignore_index=True)
print(f"Total training data size: {len(df_train)} rows.")
# Extract stylometric features
print("Extracting stylometric, lexical, and syntactic features for training set...")
stylometric_features = []
for text in df_train["text"]:
stylometric_features.append(extract_stylometric_features(text, connecteurs))
df_sty = pd.DataFrame(stylometric_features)
df_train_feats = pd.concat([df_train, df_sty], axis=1)
# N-gram feature extraction using TF-IDF (word 1-2 and char 3-4 grams)
print("Fitting TF-IDF Vectorizers for word and character n-grams...")
# Word n-grams
word_vectorizer = TfidfVectorizer(
ngram_range=tuple(config["features"]["ngram_word_range"]),
max_features=config["features"]["top_n_ngrams"] // 2,
stop_words=None # We want function words / stopwords in n-grams!
)
word_tfidf = word_vectorizer.fit_transform(df_train_feats["text"])
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)
# Character n-grams
char_vectorizer = TfidfVectorizer(
analyzer='char',
ngram_range=tuple(config["features"]["ngram_char_range"]),
max_features=config["features"]["top_n_ngrams"] // 2
)
char_tfidf = char_vectorizer.fit_transform(df_train_feats["text"])
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)
# Combine everything
df_train_final = pd.concat([df_train_feats, df_word_ngrams, df_char_ngrams], axis=1)
# Save vectorizers for inference
joblib.dump(word_vectorizer, os.path.join(config["paths"]["models_dir"], "word_vectorizer.pkl"))
joblib.dump(char_vectorizer, os.path.join(config["paths"]["models_dir"], "char_vectorizer.pkl"))
print("Vectorizers saved.")
# Save final processed training dataset
train_output = os.path.join(processed_dir, "train_features.csv")
df_train_final.to_csv(train_output, index=False)
print(f"Processed training dataset saved to {train_output}")
# 2. Process Recent Debates Data
print("Loading recent debates for inference...")
recent_path = os.path.join(raw_dir, "recent_debates.csv")
if os.path.exists(recent_path):
df_recent = pd.read_csv(recent_path)
print("Extracting features for recent debates...")
recent_sty_list = []
for text in df_recent["text"]:
recent_sty_list.append(extract_stylometric_features(text, connecteurs))
df_recent_sty = pd.DataFrame(recent_sty_list)
df_recent_feats = pd.concat([df_recent, df_recent_sty], axis=1)
# Transform n-grams using fitted vectorizers
recent_word_tfidf = word_vectorizer.transform(df_recent_feats["text"])
df_recent_word_ngrams = pd.DataFrame(recent_word_tfidf.toarray(), columns=word_cols)
recent_char_tfidf = char_vectorizer.transform(df_recent_feats["text"])
df_recent_char_ngrams = pd.DataFrame(recent_char_tfidf.toarray(), columns=char_cols)
# Combine
df_recent_final = pd.concat([df_recent_feats, df_recent_word_ngrams, df_recent_char_ngrams], axis=1)
# Save processed recent debates
recent_output = os.path.join(processed_dir, "recent_features.csv")
df_recent_final.to_csv(recent_output, index=False)
print(f"Processed recent debates dataset saved to {recent_output}")
else:
print("No recent debates dataset found in raw directory to process.")
print("Feature engineering completed successfully.")
if __name__ == "__main__":
main()