DataOfParakeetTraining / dataset /clean_dataset.py
PranavRaut0902's picture
Add files using upload-large-folder tool
743efdb verified
Raw
History Blame Contribute Delete
7.05 kB
import csv
import re
import unicodedata
from pathlib import Path
# ── Paths ──────────────────────────────────────────────────────────────────────
BASE = Path(__file__).parent
INPUT_FILES = {
"train": BASE / "train.csv",
"test": BASE / "test.csv",
}
OUTPUT_FILES = {
"train": BASE / "train_cleaned.csv",
"test": BASE / "test_cleaned.csv",
}
# ── Metadata patterns to strip ─────────────────────────────────────────────────
METADATA_PATTERNS = [
r"Pass\s*Key\s*:\s*\d+",
r"PRINTED\s+BY[\w\s,\.]*",
r"Report\s+Date\s*:\s*[\d\-/]+\s*[\d:]+\s*[AP]M",
r"THIS\s+REPORT\s+HAS\s+BEEN[^.]*\.",
r"Reg\.?\s*No\.?\s*:\s*[\w/\-]+",
r"Thanks\s+for\s+reference[\w\s,\.]*",
r"={3,}.*", # === separators and everything after
r"\*{3,}.*", # *** separators
r"DISCLAIMER[^.]*\.",
r"This\s+report\s+is\s+confidential[^.]*\.",
r"For\s+clinical\s+use\s+only[^.]*\.",
]
# ── Word formation fixes (merged words) ───────────────────────────────────────
WORD_FIXES = {
r"foraminalnarrowing": "foraminal narrowing",
r"papyraceaon": "papyracea on",
r"Bilateralfronto": "Bilateral fronto",
r"bilateralfronto": "bilateral fronto",
r"Ethmoidappears": "Ethmoid appears",
r"ethmoidappears": "ethmoid appears",
r"thislevel": "this level",
r"\bL(\d)L(\d)\b": r"L\1-L\2", # L3L4 → L3-L4
r"\bL(\d)S(\d)\b": r"L\1-S\2", # L5S1 → L5-S1
}
# ── Non-ASCII normalisation map ────────────────────────────────────────────────
CHAR_MAP = {
"×": "x", # × multiplication sign
"–": "-", # – en-dash
"—": "-", # — em-dash
"’": "'", # ' right single quote
"‘": "'", # ' left single quote
"“": '"', # " left double quote
"”": '"', # " right double quote
"…": "...", # … ellipsis
"°": " degrees", # ° degree sign
}
# ── HTML / URL strip ───────────────────────────────────────────────────────────
HTML_PATTERN = re.compile(r"<[^>]+>")
URL_PATTERN = re.compile(r"https?://\S+|www\.\S+")
MULTI_SPACE = re.compile(r" +")
MULTI_DOT = re.compile(r"\.{2,}")
MULTI_SLASH = re.compile(r"/{2,}")
def strip_metadata(text: str) -> str:
for pat in METADATA_PATTERNS:
text = re.sub(pat, "", text, flags=re.IGNORECASE)
return text
def fix_word_formation(text: str) -> str:
for pat, replacement in WORD_FIXES.items():
text = re.sub(pat, replacement, text)
return text
def normalise_chars(text: str) -> str:
for char, replacement in CHAR_MAP.items():
text = text.replace(char, replacement)
# drop any remaining non-ASCII that slipped through
text = text.encode("ascii", errors="ignore").decode("ascii")
return text
def clean_text(text: str) -> str:
text = strip_metadata(text)
text = HTML_PATTERN.sub("", text)
text = URL_PATTERN.sub("", text)
text = fix_word_formation(text)
text = normalise_chars(text)
text = MULTI_DOT.sub(".", text)
text = MULTI_SLASH.sub("/", text)
text = MULTI_SPACE.sub(" ", text)
text = text.lower()
return text.strip()
def process(split: str):
src = INPUT_FILES[split]
dst = OUTPUT_FILES[split]
stats = {
"total": 0,
"duplicates": 0,
"metadata_fixed": 0,
"word_fix": 0,
"char_normalised": 0,
"too_short": 0,
"too_long": 0,
"kept": 0,
}
seen_transcriptions: set[str] = set()
rows_out: list[dict] = []
orphaned_audio: list[Path] = []
with src.open(newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
rows = list(reader)
stats["total"] = len(rows)
for row in rows:
original = row["transcription"]
cleaned = clean_text(original)
# track what changed
if cleaned != original:
if any(re.search(p, original, re.IGNORECASE) for p in METADATA_PATTERNS):
stats["metadata_fixed"] += 1
if any(re.search(p, original) for p in WORD_FIXES):
stats["word_fix"] += 1
if any(c in original for c in CHAR_MAP):
stats["char_normalised"] += 1
word_count = len(cleaned.split())
# skip empty after cleaning
if not cleaned:
orphaned_audio.append(BASE / row["file_name"])
continue
# skip duplicates (keep first occurrence)
if cleaned in seen_transcriptions:
stats["duplicates"] += 1
orphaned_audio.append(BASE / row["file_name"])
continue
seen_transcriptions.add(cleaned)
# flag but keep short / long (let user decide manually)
if word_count < 5:
stats["too_short"] += 1
if word_count > 300:
stats["too_long"] += 1
rows_out.append({"file_name": row["file_name"], "transcription": cleaned})
stats["kept"] += 1
with dst.open("w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["file_name", "transcription"])
writer.writeheader()
writer.writerows(rows_out)
# delete audio files for removed rows
deleted = 0
missing = 0
for audio_path in orphaned_audio:
if audio_path.exists():
audio_path.unlink()
deleted += 1
else:
missing += 1
print(f"\n{'='*55}")
print(f" {split.upper()} -- {src.name} -> {dst.name}")
print(f"{'='*55}")
print(f" Total rows : {stats['total']}")
print(f" Duplicates removed : {stats['duplicates']}")
print(f" Metadata stripped : {stats['metadata_fixed']}")
print(f" Word formation fixed: {stats['word_fix']}")
print(f" Chars normalised : {stats['char_normalised']}")
print(f" Short (<5 words) : {stats['too_short']} (kept, review manually)")
print(f" Long (>300 words) : {stats['too_long']} (kept, review manually)")
print(f" Final rows kept : {stats['kept']}")
print(f" Audio files deleted : {deleted}")
if missing:
print(f" Audio not found : {missing} (already missing)")
print(f"{'='*55}")
if __name__ == "__main__":
print("Cleaning dataset — originals unchanged.")
process("train")
process("test")
print("\nDone. Cleaned files saved.")