#!/usr/bin/env python3 import argparse import csv import json from pathlib import Path from typing import Dict, List, Optional, Tuple import numpy as np import orjson import soundfile as sf import xxhash from tqdm import tqdm def read_audio(path: Path) -> Tuple[np.ndarray, int]: data, sr = sf.read(str(path)) if data.ndim == 2: data = data.mean(axis=1) return data.astype(np.float32), sr def resample_if_needed(audio: np.ndarray, sr: int, target_sr: int = 16000) -> Tuple[np.ndarray, int]: if sr == target_sr: return audio, sr # simple linear resample via librosa if available, else fallback to naive try: import librosa audio = librosa.resample(audio, orig_sr=sr, target_sr=target_sr, res_type="kaiser_fast") return audio.astype(np.float32), target_sr except Exception: factor = target_sr / sr idx = (np.arange(int(len(audio) * factor)) / factor).astype(np.int64) idx = np.clip(idx, 0, len(audio) - 1) return audio[idx].astype(np.float32), target_sr def write_wav(path: Path, audio: np.ndarray, sr: int) -> None: path.parent.mkdir(parents=True, exist_ok=True) sf.write(str(path), audio, sr) def parse_gold_csv(csv_path: Path) -> List[Dict]: records: List[Dict] = [] with open(csv_path, newline="", encoding="utf-8") as f: header = f.readline().strip() f.seek(0) # Case 1: standard CSV with headers try: reader = csv.DictReader(f) # If header names are unknown, try flexible mapping for row in reader: candidates_text = ["text", "transcription", "utterance", "sentence"] candidates_start = ["start", "start_time", "start_sec", "begin", "onset", "xmin", "t_begin", "start_ms"] candidates_end = ["end", "end_time", "end_sec", "finish", "offset", "xmax", "t_end", "end_ms"] text = "" for k in candidates_text: if k in row and row[k]: text = row[k] break start = None end = None for k in candidates_start: if k in row and row[k] != "": start = row[k] break for k in candidates_end: if k in row and row[k] != "": end = row[k] break if start is None or end is None: continue try: start_s = float(start) end_s = float(end) except Exception: continue if end_s <= start_s: continue records.append({"start": start_s, "end": end_s, "text": (text or "").strip()}) if records: return records except Exception: pass # Case 2: simple rows without headers like: tier,start,end,label (gold_ipus or phon align) with open(csv_path, "r", encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue parts = [p.strip().strip('"\uFEFF') for p in line.split(",")] if len(parts) < 4: continue tier, s, e, label = parts[0], parts[1], parts[2], parts[3] # For IPUs, label == 'ipu' means speech; '#' is non-speech try: start_s = float(s) end_s = float(e) except Exception: continue if end_s <= start_s: continue lab = label.strip().lower() # Consider IPU or any non-silence marker (common: '#' for silence) if lab == "ipu" or lab == "speech" or lab not in ("#", "", "sil", "silence"): records.append({"start": start_s, "end": end_s, "text": ""}) return records def deterministic_id(s: str) -> str: return xxhash.xxh3_128_hexdigest(s.encode("utf-8")) def cap_chunks(start: float, end: float, max_seconds: float) -> List[Tuple[float, float]]: chunks: List[Tuple[float, float]] = [] t = start while t < end: ce = min(t + max_seconds, end) if ce - t >= 0.2: chunks.append((t, ce)) t = ce return chunks def main() -> None: parser = argparse.ArgumentParser(description="Import SUMM-RE gold CSVs into <=30s segments and JSONL.") parser.add_argument("--summre-root", required=True, help="Path to SUMM-RE-sm root containing audio_anonymized/ and gold_transcriptions/csv/") parser.add_argument("--out-audio", required=True, help="Target audio subfolder, e.g., audio/conferences") parser.add_argument("--out-transcripts", required=True, help="Target transcripts folder, e.g., transcripts") parser.add_argument("--max-seconds", type=float, default=30.0, help="Maximum segment length") parser.add_argument("--train-ratio", type=float, default=0.95, help="Train split ratio") args = parser.parse_args() root = Path(args.summre_root) audio_root = root / "SUMM-RE-sm" / "audio_anonymized" if (root / "SUMM-RE-sm").exists() else root / "audio_anonymized" if not audio_root.exists(): audio_root = root / "audio_anonymized" csv_root = None # Prefer gold_transcriptions/csv if exists, else gold_ipus candidates = [ root / "SUMM-RE-sm" / "gold_transcriptions" / "csv", root / "gold_transcriptions" / "csv", root / "SUMM-RE-sm" / "gold_ipus", root / "gold_ipus", ] for c in candidates: if c.exists(): csv_root = c break if not audio_root.exists() or csv_root is None: raise SystemExit(f"Expected subfolders not found: audio={audio_root} csv root missing") out_audio = Path(args.out_audio) out_audio.mkdir(parents=True, exist_ok=True) out_trans = Path(args.out_transcripts) out_trans.mkdir(parents=True, exist_ok=True) # Build map of audio files audio_map: Dict[str, Path] = {} for wav in audio_root.glob("*.wav"): audio_map[wav.stem] = wav train_out = out_trans / "train.jsonl" valid_out = out_trans / "valid.jsonl" train_f = open(train_out, "w", encoding="utf-8") valid_f = open(valid_out, "w", encoding="utf-8") total_segments = 0 train_count = 0 valid_count = 0 for cpath in tqdm(sorted(csv_root.glob("*.csv")), desc="Importing SUMM-RE"): base = cpath.stem # Heuristic: CSV filename matches audio stem prefix (e.g., 018a_EARZ_055_anon) candidates = [k for k in audio_map.keys() if k.startswith(base)] audio_path: Optional[Path] = None if base in audio_map: audio_path = audio_map[base] elif candidates: audio_path = audio_map[candidates[0]] # Additional heuristic: audio stems may include or exclude suffixes like -palign_anon if not audio_path: trim = base.replace("-palign", "").replace("_palign", "").replace("-anon", "").replace("_anon", "") candidates = [k for k in audio_map.keys() if k.startswith(trim)] if candidates: audio_path = audio_map[candidates[0]] if not audio_path or not audio_path.exists(): continue audio, sr = read_audio(audio_path) audio, sr = resample_if_needed(audio, sr, 16000) records = parse_gold_csv(cpath) for rec in records: for (s, e) in cap_chunks(rec["start"], rec["end"], args.max_seconds): si = int(s * sr) ei = int(e * sr) seg = audio[si:ei].copy() if len(seg) < int(0.2 * sr): continue seg_id = deterministic_id(f"{audio_path.stem}:{s:.2f}-{e:.2f}") out_wav = out_audio / f"{audio_path.stem}_{int(s*1000)}_{int(e*1000)}.wav" write_wav(out_wav, seg, sr) item = { "id": seg_id, "audio": str(out_wav.resolve()), "duration": float(len(seg)) / float(sr), "text": (rec["text"] or "").strip(), "source": "SUMM-RE", "speaker_role": "teacher", # par défaut "accent": "", "domain": "education", "quality": "clean", "category": "conferences", } # deterministic split by id hash h = int(seg_id[:8], 16) r = (h % 10000) / 10000.0 if r < args.train_ratio: train_f.write(orjson.dumps(item).decode("utf-8") + "\n") train_count += 1 else: valid_f.write(orjson.dumps(item).decode("utf-8") + "\n") valid_count += 1 total_segments += 1 train_f.close() valid_f.close() print(f"Imported segments: {total_segments} (train={train_count}, valid={valid_count})") if __name__ == "__main__": main()