KatInterview

Build a Batch Text Labeling Pipeline with CSV Input

System DesignModel answer
MediumModel answerSystem Designpythonfile-processingerror-handling

Last updated

Parse an uploaded CSV of text records, classify each via an external ML client, and write a structured JSON results file with per-row error isolation.

Background

You are building the ingestion layer of a text annotation platform. Users upload CSV files containing raw text snippets they want labeled. Your job is to wire together three stages: parsing the file, calling an external classifier for each snippet, and writing the results to disk.

Task

Implement the BatchLabelingPipeline class with a single public method, run, described below.

Stage 1 — Parse and Validate

run receives the CSV as raw bytes. The file must have columns named id and text (in any order, possibly alongside other columns).

  • Decode the bytes as UTF-8.
  • If the file cannot be decoded, or if the id or text column is absent from the header, raise ValueError.
  • For every data row, strip whitespace from both fields. If either field is empty after stripping, skip that row and increment a counter. Do not call the classifier for skipped rows.

Stage 2 — Classify

For each valid row, call classifier.predict(text). The client returns {"label": str, "confidence": float}.

  • If the call raises any exception, record the error message for that row and continue. One bad row must never abort the whole batch.

Stage 3 — Persist

Write a JSON file to dest_path. Create any missing parent directories first. Use an atomic write so readers never see a partial file.

The JSON structure must be:

{
  "summary": {
    "total_rows": <int>,
    "labeled": <int>,
    "errors": <int>,
    "skipped": <int>
  },
  "records": [
    {"id": "...", "text": "...", "label": "...", "confidence": 0.0},
    {"id": "...", "text": "...", "error": "..."}
  ]
}

total_rows counts every data row the parser yields, including skipped ones. The invariant total_rows == labeled + errors + skipped must always hold.

Return Value

Return the summary dictionary.

Interface

from typing import Any, Dict, Protocol

class TextClassifier(Protocol):
    def predict(self, text: str) -> Dict[str, Any]:
        """Returns {'label': str, 'confidence': float}"""
        ...

class BatchLabelingPipeline:
    def __init__(self, classifier: TextClassifier) -> None:
        self.classifier = classifier

    def run(self, file_content: bytes, dest_path: str) -> Dict[str, Any]:
        """Parse file_content, classify valid rows, persist results, return summary."""
        pass

Constraints

  • File size is at most 10 MB (~5,000 rows).
  • Text fields may contain UTF-8 characters, commas, and embedded newlines (RFC 4180 quoting).
  • Files exported from spreadsheet tools may include a UTF-8 BOM.

Example

csv_data = b"""id,text
1,"Arrived fast and works perfectly."
2,
3,"Stopped working after two days."
"""

# classifier behavior:
# predict("Arrived fast and works perfectly.") -> {"label": "positive", "confidence": 0.95}
# predict("Stopped working after two days.")   -> raises RuntimeError("timeout")

pipeline = BatchLabelingPipeline(classifier)
summary = pipeline.run(csv_data, "out/batch_1.json")

Returned summary:

{"total_rows": 3, "labeled": 1, "errors": 1, "skipped": 1}

out/batch_1.json:

{
  "summary": {"total_rows": 3, "labeled": 1, "errors": 1, "skipped": 1},
  "records": [
    {"id": "1", "text": "Arrived fast and works perfectly.", "label": "positive", "confidence": 0.95},
    {"id": "3", "text": "Stopped working after two days.", "error": "timeout"}
  ]
}

Note: row 2 is skipped (blank text) and does not appear in records.

Hints

Hint 1

Decide early which failures are file-level (raise immediately, no API calls made) versus row-level (record the error, keep going). That boundary drives the entire structure.

Hint 2

Python's csv.DictReader handles RFC 4180 quoting — embedded commas and newlines inside quoted fields — but you must open the stream with newline="" and decode with utf-8-sig to strip an optional BOM before the reader sees the data.

Hint 3

For the atomic write, write to a temporary file in the same directory as dest_path, then rename it into place with os.replace. This guarantees readers see either the complete old file or the complete new one.