Build a Batch Text Labeling Pipeline with CSV Input
System DesignModel answerLast 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
idortextcolumn is absent from the header, raiseValueError. - 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The pipeline has three cleanly separated phases: parse, classify, persist. Keeping them separate makes the error-boundary logic easy to reason about.
Error boundary rule
| Condition | Treatment |
|---|---|
Invalid UTF-8, malformed CSV structure, missing id/text column | File-level: raise ValueError before any classifier call |
Row where id or text is blank after stripping | Row-level: skip, increment counter, exclude from records |
| Classifier exception or malformed classifier response | Row-level: store {"error": "..."}, increment error counter |
State this rule out loud. Interviewers are checking that you know the difference between a corrupt file and a noisy row.
Parsing details that trip people up
- Use
utf-8-sigwhen decoding. Excel and Google Sheets often prepend a UTF-8 BOM (\xef\xbb\xbf). With plainutf-8, the first header becomes"\ufeffid"and your column check fails silently. - Pass
newline=""toio.StringIO. Thecsvmodule requires this so it can handle\r\ninside quoted fields correctly. - Never split on
"\n"or","manually.csv.DictReaderimplements RFC 4180 quoting; hand-splitting breaks on any field that contains those characters. - Strip whitespace from
reader.fieldnamesbefore checking foridandtext. Spreadsheet exports sometimes add a trailing space to a header. reader.fieldnamesisNonefor an empty file; handle that case explicitly.
Classifier output is untrusted
The classifier is an external service. Wrap every call in try/except Exception. Also defensively cast the response: str(response["label"]) and float(response["confidence"]). If the service returns a malformed dict, treat it as a row error rather than crashing.
If str(e) produces an empty string, fall back to type(e).__name__ so the error field is never blank.
Atomic write
Write to a NamedTemporaryFile in the same directory as dest_path, then call os.replace. Because both paths are on the same filesystem, the rename is atomic at the OS level. Always create parent directories first with os.makedirs(exist_ok=True).
Complexity
- Time: O(B + N·C) where B is the byte length of the file, N is the number of valid rows, and C is the per-call classifier latency. Parsing is linear in B; classifier calls dominate in practice.
- Space: O(B) — the decoded text, row list, and results all live in memory. At 10 MB / ~5k rows this is fine. For files significantly larger, you would stream rows and write JSON Lines incrementally.
Edge cases to mention
- Empty file (
b""):fieldnamesisNone→ValueError. - Header-only file: valid, summary is all zeros,
recordsis[]. - Duplicate
idvalues: process each row independently; deduplication is a product decision. - Extra columns beyond
idandtext: ignore them. - Row with fewer fields than the header:
DictReaderfills missing fields withNone, which strips to""and becomes a skip.
Solution
import csv
import io
import json
import os
import tempfile
from typing import Any, Dict, List, Protocol
class TextClassifier(Protocol):
def predict(self, text: str) -> Dict[str, Any]:
"""Returns {'label': str, 'confidence': float}"""
...
class BatchLabelingPipeline:
REQUIRED_COLUMNS = ("id", "text")
def __init__(self, classifier: TextClassifier) -> None:
self.classifier = classifier
def run(self, file_content: bytes, dest_path: str) -> Dict[str, Any]:
valid_rows, skipped, total = self._parse(file_content)
records, labeled, errors = self._classify(valid_rows)
summary: Dict[str, Any] = {
"total_rows": total,
"labeled": labeled,
"errors": errors,
"skipped": skipped,
}
self._atomic_write(dest_path, {"summary": summary, "records": records})
return summary
# ------------------------------------------------------------------
# Stage 1: parse
# ------------------------------------------------------------------
def _parse(self, file_content: bytes):
try:
decoded = file_content.decode("utf-8-sig")
except UnicodeDecodeError as exc:
raise ValueError(f"File is not valid UTF-8: {exc}") from exc
try:
stream = io.StringIO(decoded, newline="")
reader = csv.DictReader(stream, strict=True)
# Validate header
raw_fieldnames = reader.fieldnames
if not raw_fieldnames:
raise ValueError("CSV has no header row")
reader.fieldnames = [(f or "").strip() for f in raw_fieldnames]
missing = [c for c in self.REQUIRED_COLUMNS if c not in reader.fieldnames]
if missing:
raise ValueError(f"CSV header is missing required columns: {missing}")
valid_rows: List[tuple] = []
skipped = total = 0
for row in reader:
total += 1
row_id = (row.get("id") or "").strip()
text = (row.get("text") or "").strip()
if not row_id or not text:
skipped += 1
else:
valid_rows.append((row_id, text))
except csv.Error as exc:
raise ValueError(f"CSV parsing failed: {exc}") from exc
return valid_rows, skipped, total
# ------------------------------------------------------------------
# Stage 2: classify
# ------------------------------------------------------------------
def _classify(self, valid_rows: List[tuple]):
records: List[Dict[str, Any]] = []
labeled = errors = 0
for row_id, text in valid_rows:
record: Dict[str, Any] = {"id": row_id, "text": text}
try:
response = self.classifier.predict(text)
record["label"] = str(response["label"])
record["confidence"] = float(response["confidence"])
labeled += 1
except Exception as exc:
record["error"] = str(exc) or type(exc).__name__
errors += 1
records.append(record)
return records, labeled, errors
# ------------------------------------------------------------------
# Stage 3: atomic persist
# ------------------------------------------------------------------
def _atomic_write(self, dest_path: str, payload: Dict[str, Any]) -> None:
dest_path = os.path.abspath(dest_path)
parent_dir = os.path.dirname(dest_path)
os.makedirs(parent_dir, exist_ok=True)
# Write to a temp file in the same directory so os.replace is
# a same-filesystem rename (atomic on POSIX and Windows).
fd, tmp_path = tempfile.mkstemp(dir=parent_dir, suffix=".tmp")
try:
with os.fdopen(fd, "w", encoding="utf-8") as fh:
json.dump(payload, fh, ensure_ascii=False, indent=2)
os.replace(tmp_path, dest_path)
except Exception:
# Clean up the temp file if anything goes wrong before rename.
try:
os.unlink(tmp_path)
except OSError:
pass
raise
Common mistakes to avoid
- Calling the classifier inside the parsing phase — a syntax error on row 1 would waste API budget already spent on earlier rows.
- Using a bare
except:without capturingexc— the error field in the record ends up empty. - Writing JSON directly to
dest_path— a crash mid-write leaves a truncated file that downstream consumers cannot read. - Forgetting
ensure_ascii=False— non-ASCII characters get escaped as\uXXXX, making the output harder to read and audit.