File size: 11,301 Bytes
eb72d30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
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()