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
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
import os
import sys
import yaml
import argparse
import pandas as pd
import numpy as np
import requests
import random
from datetime import datetime, timedelta

# Import text generator
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from text_generator import generate_speech, PARTIES, SPEAKERS, CHAMBERS

def load_config(config_path):
    with open(config_path, "r", encoding="utf-8") as f:
        return yaml.safe_load(f)

def clean_and_normalize(text):
    """Cleans text by normalizing whitespace, typography, accents, and punctuation."""
    if not isinstance(text, str):
        return ""
    # Normalize typography
    text = text.replace("’", "'").replace("œ", "oe").replace("æ", "ae")
    # Normalize whitespaces
    text = " ".join(text.split())
    return text

def map_row_to_schema(row, seed_idx):
    """Maps a raw row from agokrani/fr-political-speeches to the pipeline schema."""
    text_clean = clean_and_normalize(row["text"])
    
    # Derive chamber
    src_lower = str(row["source"]).lower()
    url_lower = str(row.get("source_url", "")).lower()
    role_lower = str(row.get("speaker_role", "")).lower()
    
    if "senat" in src_lower or "senat" in url_lower or "sénat" in role_lower:
        chamber = "Sénat"
    else:
        chamber = "Assemblée nationale"
        
    # Derive party based on role or name, otherwise fallback
    party = "Non spécifié"
    role_check = role_lower if pd.notna(role_lower) else ""
    spk_check = str(row["speaker"]).lower() if pd.notna(row["speaker"]) else ""
    
    if "la france insoumise" in role_check or "lfi" in role_check or "mélenchon" in spk_check or "ruffin" in spk_check:
        party = "La France Insoumise"
    elif "socialiste" in role_check or "faure" in spk_check:
        party = "Socialistes"
    elif "écologiste" in role_check or "vert" in role_check:
        party = "Écologistes"
    elif "ump" in role_check or "républicains" in role_check or "wauquiez" in spk_check:
        party = "Les Républicains"
    elif "rassemblement national" in role_check or "rn" in role_check or "le pen" in spk_check:
        party = "Rassemblement National"
    elif "renaissance" in role_check or "lrem" in role_check or "majorité" in role_check or "darmanin" in spk_check:
        party = "Renaissance"
    elif "démocrate" in role_check or "modem" in role_check:
        party = "Démocrates"
    else:
        random.seed(seed_idx)
        party = random.choice(PARTIES)
        
    # Calculate legislature
    date_str = str(row["date"])
    try:
        dt = pd.to_datetime(date_str)
        year = dt.year
        date_formatted = dt.strftime("%Y-%m-%d")
    except:
        year = 2000
        date_formatted = "2000-01-01"
        
    if year >= 2022:
        leg = "16"
    elif year >= 2017:
        leg = "15"
    elif year >= 2012:
        leg = "14"
    elif year >= 2007:
        leg = "13"
    elif year >= 2002:
        leg = "12"
    elif year >= 1997:
        leg = "11"
    else:
        leg = str(random.randint(1, 10))
        
    # Map document type
    doc_type = "intervention_seance"
    st_lower = str(row.get("speech_type", "")).lower() if pd.notna(row.get("speech_type", "")) else ""
    title_check = str(row.get("title", "")).lower() if pd.notna(row.get("title", "")) else ""
    
    if "amendement" in st_lower or "amendement" in title_check:
        doc_type = "amendement"
    elif "déclaration" in st_lower or "prise de position" in st_lower:
        doc_type = "prise_position"
    elif "explication" in st_lower:
        doc_type = "explication_vote"
    elif "réponse" in st_lower:
        doc_type = "reponse_debat"
    elif "groupe" in st_lower:
        doc_type = "discours_groupe"
        
    return {
        "text": text_clean,
        "label_human_ai": 0,
        "source": row["source"] if pd.notna(row["source"]) else "Assemblée/Sénat",
        "speaker": row["speaker"] if pd.notna(row["speaker"]) else "Orateur inconnu",
        "party": party,
        "date": date_formatted,
        "chamber": chamber,
        "document_type": doc_type,
        "legislature": leg
    }

def generate_mock_human_corpus(sample_size, seed=42):
    """Generates a realistic mock corpus of human political speeches."""
    print(f"Generating mock human political corpus ({sample_size} samples)...")
    random.seed(seed)
    np.random.seed(seed)
    
    data = []
    start_date = datetime(1958, 1, 1)
    end_date = datetime(2022, 12, 31)
    date_range_days = (end_date - start_date).days
    
    doc_types = ["intervention_seance", "prise_position", "explication_vote", "amendement", "reponse_debat", "discours_groupe"]
    sources = ["french-political-speeches-1958-2022", "French Political Speeches (2000-2010)", "Sénat XML", "Assemblée nationale open-data"]
    
    for i in range(sample_size):
        date_speech = start_date + timedelta(days=random.randint(0, date_range_days))
        speaker = random.choice(SPEAKERS)
        party = random.choice(PARTIES)
        chamber = random.choice(CHAMBERS)
        doc_type = random.choice(doc_types)
        source = random.choice(sources)
        
        # Calculate legislature
        year = date_speech.year
        if year >= 2022:
            leg = "16"
        elif year >= 2017:
            leg = "15"
        elif year >= 2012:
            leg = "14"
        elif year >= 2007:
            leg = "13"
        elif year >= 2002:
            leg = "12"
        else:
            leg = str(random.randint(1, 11))
            
        speech_text = generate_speech(is_ai=False, seed=i)
        cleaned_text = clean_and_normalize(speech_text)
        
        data.append({
            "text": cleaned_text,
            "label_human_ai": 0,
            "source": source,
            "speaker": speaker,
            "party": party,
            "date": date_speech.strftime("%Y-%m-%d"),
            "chamber": chamber,
            "document_type": doc_type,
            "legislature": leg
        })
        
    return pd.DataFrame(data)

def generate_recent_debates_from_real(df_hf, sample_size=3000, seed=42):
    """Creates recent debates using real post-2003 human texts from HF dataset and injects post-2022 AI texts."""
    print(f"Creating recent debates from Hugging Face dataset (2003-2026) ({sample_size} samples)...")
    random.seed(seed + 100)
    np.random.seed(seed + 100)
    
    # Filter real speeches post 2003
    df_hf["parsed_date"] = pd.to_datetime(df_hf["date"], errors="coerce")
    df_recent_human = df_hf[df_hf["parsed_date"] >= "2003-01-01"].copy()
    
    if len(df_recent_human) < sample_size:
        print("Warning: not enough post-2003 real speeches, utilizing all of them and falling back for remaining.")
        df_sampled = df_recent_human
    else:
        df_sampled = df_recent_human.sample(n=sample_size, random_state=seed + 200)
        
    start_date_modern = datetime(2023, 1, 1)
    end_date_modern = datetime(2026, 5, 1)
    date_range_days_modern = (end_date_modern - start_date_modern).days
    
    start_date_hist = datetime(2004, 1, 1)
    end_date_hist = datetime(2022, 12, 31)
    date_range_days_hist = (end_date_hist - start_date_hist).days
    
    data = []

    for idx, (original_idx, row) in enumerate(df_sampled.iterrows()):
        mapped = map_row_to_schema(row, idx)
        
        # Spreading: project dates to cover the entire timeline continuously
        if random.random() < 0.20:
            # Project to modern era (2023-2026) where AI injection can happen
            random_days = random.randint(0, date_range_days_modern)
            dt_modern = start_date_modern + timedelta(days=random_days)
            mapped["date"] = dt_modern.strftime("%Y-%m-%d")
            mapped["legislature"] = "16"
        else:
            # Spread historical human debates uniformly across the 2004-2022 range
            random_days = random.randint(0, date_range_days_hist)
            dt_hist = start_date_hist + timedelta(days=random_days)
            mapped["date"] = dt_hist.strftime("%Y-%m-%d")
            
            # Map legislature based on year
            year = dt_hist.year
            if year >= 2022:
                mapped["legislature"] = "16"
            elif year >= 2017:
                mapped["legislature"] = "15"
            elif year >= 2012:
                mapped["legislature"] = "14"
            elif year >= 2007:
                mapped["legislature"] = "13"
            else:
                mapped["legislature"] = "12"
        
        dt = pd.to_datetime(mapped["date"])
        is_ai = False
        ai_model = "human"
        
        if dt.year >= 2023:
            # 15% probability of AI post 2022
            prob = 0.15
            if mapped["speaker"] == "Jean Dupuis" or "dupuis" in str(mapped["speaker"]).lower():
                prob = 0.40
            if mapped["party"] == "Démocrates":
                prob = 0.30
                
            if random.random() < prob:
                is_ai = True
                ai_model = random.choice(["gpt-4", "claude-3-opus", "qwen-72b", "gemma-7b"])
                
        if is_ai:
            speech_text = generate_speech(is_ai=True, ai_model=ai_model, doc_type=mapped["document_type"], seed=idx + 20000)
            mapped["text"] = clean_and_normalize(speech_text)
            mapped["actual_label"] = 1
            mapped["ai_model"] = ai_model
        else:
            mapped["actual_label"] = 0
            mapped["ai_model"] = "human"
            
        data.append(mapped)
        
    # Fill up to sample_size if needed
    current_len = len(data)
    if current_len < sample_size:
        print(f"Adding {sample_size - current_len} simulated recent speeches to reach sample size...")
        start_date = datetime(2003, 1, 1)
        end_date = datetime(2026, 5, 1)
        date_range_days = (end_date - start_date).days
        for i in range(sample_size - current_len):
            date_speech = start_date + timedelta(days=random.randint(0, date_range_days))
            speaker = random.choice(SPEAKERS)
            party = random.choice(PARTIES)
            chamber = random.choice(CHAMBERS)
            doc_type = random.choice(["intervention_seance", "prise_position", "explication_vote", "amendement"])
            
            is_ai = False
            ai_model = "human"
            if date_speech.year >= 2023:
                prob = 0.15
                if speaker == "Jean Dupuis":
                    prob = 0.40
                if party == "Démocrates":
                    prob = 0.30
                if random.random() < prob:
                    is_ai = True
                    ai_model = random.choice(["gpt-4", "claude-3-opus", "qwen-72b", "gemma-7b"])
                    
            leg = "16" if date_speech.year >= 2022 else ("15" if date_speech.year >= 2017 else ("14" if date_speech.year >= 2012 else "13"))
            speech_text = generate_speech(is_ai=is_ai, ai_model=ai_model, doc_type=doc_type, seed=i + 30000)
            cleaned = clean_and_normalize(speech_text)
            
            data.append({
                "text": cleaned,
                "label_human_ai": 0,
                "source": "simulated_debate",
                "speaker": speaker,
                "party": party,
                "date": date_speech.strftime("%Y-%m-%d"),
                "chamber": chamber,
                "document_type": doc_type,
                "legislature": leg,
                "actual_label": 1 if is_ai else 0,
                "ai_model": ai_model
            })
            
    return pd.DataFrame(data)

def generate_recent_debates_mock(sample_size=3000, seed=42):
    """Fallback generator for recent debates using mock logic."""
    print(f"Generating mock recent debates corpus for inference ({sample_size} samples)...")
    random.seed(seed + 100)
    np.random.seed(seed + 100)
    
    data = []
    start_date = datetime(2003, 1, 1)
    end_date = datetime(2026, 5, 1)
    date_range_days = (end_date - start_date).days
    doc_types = ["intervention_seance", "prise_position", "explication_vote", "amendement", "reponse_debat", "discours_groupe"]
    
    for i in range(sample_size):
        date_speech = start_date + timedelta(days=random.randint(0, date_range_days))
        speaker = random.choice(SPEAKERS)
        party = random.choice(PARTIES)
        chamber = random.choice(CHAMBERS)
        doc_type = random.choice(doc_types)
        
        is_ai = False
        ai_model = "human"
        
        if date_speech.year >= 2023:
            prob = 0.12
            if speaker == "Jean Dupuis":
                prob = 0.35
            if party == "Démocrates":
                prob = 0.25
            if random.random() < prob:
                is_ai = True
                ai_model = random.choice(["gpt-4", "claude-3-opus", "qwen-72b", "gemma-7b"])
                
        leg = "16" if date_speech.year >= 2022 else ("15" if date_speech.year >= 2017 else ("14" if date_speech.year >= 2012 else ("13" if date_speech.year >= 2007 else "12")))
        speech_text = generate_speech(is_ai=is_ai, ai_model=ai_model, doc_type=doc_type, seed=i + 5000)
        cleaned_text = clean_and_normalize(speech_text)
        
        data.append({
            "text": cleaned_text,
            "speaker": speaker,
            "party": party,
            "date": date_speech.strftime("%Y-%m-%d"),
            "chamber": chamber,
            "document_type": doc_type,
            "legislature": leg,
            "actual_label": 1 if is_ai else 0,
            "ai_model": ai_model
        })
        
    return pd.DataFrame(data)

def main():
    parser = argparse.ArgumentParser(description="Collect, ingest and clean French parliamentary speeches.")
    parser.add_argument("--config", default="configs/config.yaml", help="Path to config file")
    parser.add_argument("--mock", action="store_true", help="Force generating mock datasets")
    args = parser.parse_args()
    
    config = load_config(args.config)
    raw_dir = config["paths"]["raw_dir"]
    os.makedirs(raw_dir, exist_ok=True)
    
    use_mock = config["data_collection"]["use_mock"] or args.mock
    seed = config["data_collection"]["seed"]
    sample_size = config["data_collection"]["sample_size_human"]
    
    df_hf = None
    
    if not use_mock:
        try:
            print("Loading real human political speeches from Hugging Face (agokrani/fr-political-speeches)...")
            from datasets import load_dataset
            dataset = load_dataset("agokrani/fr-political-speeches", split="train")
            df_hf = dataset.to_pandas()
            print(f"Successfully downloaded {len(df_hf)} real speeches from Hugging Face.")
            
            # Map a sample of real speeches to training human corpus
            df_sampled = df_hf.sample(n=min(sample_size, len(df_hf)), random_state=seed)
            
            print("Mapping real dataset to unified schema...")
            data_mapped = []
            for i, (_, row) in enumerate(df_sampled.iterrows()):
                data_mapped.append(map_row_to_schema(row, i))
                
            df_human = pd.DataFrame(data_mapped)
            df_human.to_csv(os.path.join(raw_dir, "human_corpus.csv"), index=False)
            print(f"Saved real human training corpus to {os.path.join(raw_dir, 'human_corpus.csv')}")
            
        except Exception as e:
            print(f"Error downloading or processing from Hugging Face: {e}. Falling back to mock generation.")
            use_mock = True
            
    if use_mock:
        df_human = generate_mock_human_corpus(sample_size, seed)
        df_human.to_csv(os.path.join(raw_dir, "human_corpus.csv"), index=False)
        print(f"Saved mock human corpus to {os.path.join(raw_dir, 'human_corpus.csv')}")
        
    # Generate the AI synthetic corpus
    import subprocess
    script_dir = os.path.dirname(os.path.abspath(__file__))
    synthetic_script = os.path.join(script_dir, "generate_synthetic.py")
    print(f"Executing AI generation script: {synthetic_script}...")
    subprocess.run([sys.executable, synthetic_script, "--config", args.config], check=True)
        
    # Generate the recent debates corpus for inference
    if not use_mock and df_hf is not None:
        df_recent = generate_recent_debates_from_real(df_hf, sample_size=3000, seed=seed)
    else:
        df_recent = generate_recent_debates_mock(sample_size=3000, seed=seed)
        
    df_recent.to_csv(os.path.join(raw_dir, "recent_debates.csv"), index=False)
    print(f"Saved recent debates for inference to {os.path.join(raw_dir, 'recent_debates.csv')}")
    print("Ingestion step completed successfully.")

if __name__ == "__main__":
    main()