TExcelTAD
Home › Data Preparation Toolkit: Cleaning to Leakage-Free Splits › Corrupted Files and the Cleaning Log

Corrupted Files and the Cleaning Log

Not every problem is a wrong value in a good file. Sometimes the file itself is broken: a truncated CSV line, a JSON Lines file with one invalid record, an image that ends halfway, an audio clip of zero length, a file that claims to be a PNG but is an HTML error page. And every cleaning step in this section changes the data, so you need a record of what was changed, why and how many rows it touched. This lesson covers both: reading defensively and keeping a cleaning log.

Reading files defensively

The principle: never let one bad record stop the whole load, and never let it disappear silently. Read record by record, keep the good ones, and quarantine the bad ones with the reason.

python · try it yourself
import io
import json
import pandas as pd

jsonl = io.StringIO(
    '{"id": 1, "text": "great product", "label": 1}\n'
    '{"id": 2, "text": "arrived broken", "label": 0}\n'
    '{"id": 3, "text": "ok I guess", "label": \n'
    '\n'
    '{"id": 4, "text": "would buy again", "label": 1}\n'
    '{"id": 5, "label": 0}\n'
    '[1, 2, 3]\n'
)
required = {"id": int, "text": str, "label": int}
good, quarantine = [], []
for lineno, line in enumerate(jsonl, start=1):
    if not line.strip():
        continue                                   # blank lines are harmless
    try:
        rec = json.loads(line)
    except json.JSONDecodeError as e:
        quarantine.append((lineno, f"invalid JSON: {e.msg}"))
        continue
    if not isinstance(rec, dict):
        quarantine.append((lineno, f"not an object: {type(rec).__name__}"))
        continue
    problems = [k for k, t in required.items() if not isinstance(rec.get(k), t)]
    if problems:
        quarantine.append((lineno, f"missing or wrong type: {problems}"))
        continue
    good.append(rec)

print(pd.DataFrame(good).to_string(index=False))
for lineno, why in quarantine:
    print(f"line {lineno}: {why}")
 id            text  label
  1   great product      1
  2  arrived broken      0
  4 would buy again      1
line 3: invalid JSON: Expecting value
line 6: missing or wrong type: ['text']
line 7: not an object: list

Three good records load, three bad lines are reported with their line numbers, and nothing crashes. For CSV, pd.read_csv(..., on_bad_lines="warn") (or a callable for on_bad_lines with the Python engine) gives the same behaviour for rows with too many fields, but it does not catch rows with too few fields: those are padded with NaN, which is why a row-count and a missing-value check after loading are still needed.

Checking binary files: images and audio

For media files, "it has the right extension" proves nothing. Check, per file:

  1. Signature (magic bytes): PNG starts with 89 50 4E 47, JPEG with FF D8 FF, WAV with RIFF....WAVE.
  2. It decodes: the library can read it fully, not only the header.
  3. Its content is plausible: image size and channels as expected, audio length above zero, sample rate as expected.
  4. It is not a duplicate: a content hash (SHA-256) catches byte-identical copies under different names.
python · try it yourself
import hashlib
import io
import wave
import numpy as np
import cv2

cv2.setLogLevel(0)          # silence OpenCV's own warnings; we report problems ourselves

def png_bytes(img):
    ok, buf = cv2.imencode(".png", img)
    return buf.tobytes()

def wav_bytes(samples, rate=16000):
    out = io.BytesIO()
    with wave.open(out, "wb") as w:
        w.setnchannels(1); w.setsampwidth(2); w.setframerate(rate)
        w.writeframes(samples.astype(np.int16).tobytes())
    return out.getvalue()

rng = np.random.default_rng(0)
img = rng.integers(0, 255, (32, 32, 3), dtype=np.uint8)
tone = (8000 * np.sin(2 * np.pi * 440 * np.arange(1600) / 16000))
files = {
    "cat_001.png": png_bytes(img),
    "cat_002.png": png_bytes(img)[:300],                       # truncated download
    "cat_003.png": b"<html><body>404 Not Found</body></html>",  # error page saved as .png
    "cat_004.png": png_bytes(img),                             # same bytes as cat_001
    "say_yes.wav": wav_bytes(tone),
    "say_no.wav":  wav_bytes(np.zeros(0)),                     # empty recording
}

def check(name, data):
    if name.endswith(".png"):
        if not data.startswith(b"\x89PNG"):
            return "not a PNG (bad signature)"
        im = cv2.imdecode(np.frombuffer(data, np.uint8), cv2.IMREAD_COLOR)
        if im is None:
            return "PNG does not decode"
        return f"ok {im.shape[1]}x{im.shape[0]}"
    with wave.open(io.BytesIO(data)) as w:
        n, rate = w.getnframes(), w.getframerate()
    return "empty audio" if n == 0 else f"ok {n / rate:.2f} s at {rate} Hz"

seen = {}
for name, data in files.items():
    digest = hashlib.sha256(data).hexdigest()[:12]
    status = check(name, data)
    if status.startswith("ok") and digest in seen:
        status = f"duplicate of {seen[digest]}"
    seen.setdefault(digest, name)
    print(f"{name:12s} {digest}  {status}")
cat_001.png  6f5b670a481f  ok 32x32
cat_002.png  ebf3f3e21e77  PNG does not decode
cat_003.png  ab0fed4d121b  not a PNG (bad signature)
cat_004.png  6f5b670a481f  duplicate of cat_001.png
say_yes.wav  4f43bc5e58a5  ok 0.10 s at 16000 Hz
say_no.wav   ba584a378b11  empty audio

The checker accepted two files and rejected four, each with a reason. The truncated PNG still has a valid signature; only decoding reveals it. The duplicate check runs on the bytes, so it finds cat_004.png even though its name looks new; near-duplicates (the same photo resized or re-encoded) need perceptual hashes or embeddings, covered in Preparing Image Data.

Note: Quarantine, do not delete. Move bad files to a separate folder or list them in a manifest with the reason. Some are recoverable (a re-download), and the count of bad files per source is itself a data-quality signal.

The cleaning log

Every operation in this section (deduplication, type fixes, unit conversion, range rules, category mapping, quarantined files) should leave a line in a log: step, rule, rows affected, examples. The log lets a reviewer check your decisions, lets you rerun the exact same cleaning on next month's data, and explains later why the training set has 9,412 rows and not 10,000.

A light way to get one is to wrap each step in a function and record its effect automatically:

python · try it yourself
import json
import pandas as pd

LOG = []

def step(name, rule):
    def wrap(fn):
        def run(df):
            before = len(df)
            out, changed = fn(df)
            LOG.append({"step": name, "rule": rule, "rows_in": before,
                        "rows_out": len(out), "values_changed": int(changed)})
            return out
        return run
    return wrap

@step("dedup", "drop exact duplicate rows")
def dedup(df):
    out = df.drop_duplicates()
    return out, 0

@step("smoker", "map yes/y/1 -> yes, no/n/0 -> no, rest -> missing")
def smoker(df):
    m = {"yes": "yes", "y": "yes", "1": "yes", "no": "no", "n": "no", "0": "no"}
    new = df["smoker"].str.lower().map(m)
    changed = (new.fillna("<NA>") != df["smoker"].fillna("<NA>")).sum()
    return df.assign(smoker=new), changed

@step("age_range", "age outside [0, 120] -> missing")
def age_range(df):
    bad = ~df["age"].between(0, 120)
    return df.assign(age=df["age"].where(~bad)), bad.sum()

raw = pd.DataFrame({"age": [34, 34, 230, 51, 47], "smoker": ["Y", "Y", "no", "maybe", "1"]})
clean = age_range(smoker(dedup(raw)))
print(clean.to_string(index=False))
print(json.dumps(LOG, indent=1))
 age smoker
34.0    yes
 NaN     no
51.0    NaN
47.0    yes
[
 {
  "step": "dedup",
  "rule": "drop exact duplicate rows",
  "rows_in": 5,
  "rows_out": 4,
  "values_changed": 0
 },
 {
  "step": "smoker",
  "rule": "map yes/y/1 -> yes, no/n/0 -> no, rest -> missing",
  "rows_in": 4,
  "rows_out": 4,
  "values_changed": 3
 },
 {
  "step": "age_range",
  "rule": "age outside [0, 120] -> missing",
  "rows_in": 4,
  "rows_out": 4,
  "values_changed": 1
 }
]

The log is plain JSON, so it can be saved next to the cleaned data and versioned with it (Dataset Versioning). In a larger project the same idea becomes a list of named, tested functions run in a fixed order, with the log written by the runner. In a scikit-learn model, the cleaning steps that learn from data (imputers, encoders) move into the pipeline; the fixed rules of this section stay in the cleaning script that runs before it.

Pitfalls

  • try: ... except: pass around the loader: bad records vanish without a trace. Always count and keep them.
  • Trusting the extension: check signatures and decode fully; an HTML error page saved as .jpg is common with scraped data.
  • Cleaning in a notebook by hand: cells run out of order and the steps are not repeatable. Put the rules in functions and log them.
  • A log without counts: "removed duplicates" says nothing; "removed 588 exact duplicates of 10,000 rows (5.9%)" lets a reviewer notice that 5.9% is suspicious.

Practice

  1. A folder of 20,000 photos takes hours to fully decode. How could you check it faster without skipping corrupted files?
Answer

Check signatures and file sizes for all files first (cheap), decode in parallel workers, and cache the result per content hash so unchanged files are never checked twice. Files below a minimum size, or whose size differs a lot from others at the same resolution, are decoded first.

  1. What should the log entry for the city mapping of the previous lesson contain?
Answer

Step name, the mapping table (or its version/hash), rows in and out, the number of values changed, and the list of unmapped values with their counts (hanoi city, hue), so the mapping can be extended and the step rerun.

Test yourself

A truncated PNG still starts with the bytes 89 50 4E 47. Which check catches it?

  1. The file extension
  2. The signature check
  3. Fully decoding the image
  4. The SHA-256 hash

What should happen to a JSON Lines record that does not parse?

  1. Stop the whole load
  2. Skip it silently
  3. Quarantine it with its line number and reason, and continue
  4. Replace it with an empty record

Which entry is most useful in a cleaning log?

  1. 'Cleaned the data'
  2. 'Removed duplicates'
  3. 'dedup: drop exact duplicates, 10,000 -> 9,412 rows'
  4. The full dataset after each step