bagaco3 / classifier /scripts /merge_quality_annotations.py
duarteocarmo
update
880db5d
Raw History Blame Contribute Delete
7.18 kB
"""Merge completed quality annotations into the annotated Parquet dataset."""
import json
import os
import random
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
import polars as polars
from tqdm import tqdm
from build_quality_annotation_dataset import (
MAX_WORKERS,
ROWS_PER_WINDOW,
SOURCE_SHARDS,
window_jobs_for,
)
CATEGORIES = {
"Society",
"Arts",
"Business",
"Science",
"Sports",
"Lifestyle",
"Health",
"Games",
"News",
}
ANNOTATION_COLUMNS = [
"custom_id",
"batch_id",
"justification",
"educational_score",
"category",
]
def result_files_from(manifest_file: Path) -> list[tuple[str, Path]]:
"""Return batch IDs and their downloaded result paths."""
manifest = json.loads(manifest_file.read_text(encoding="utf-8"))
return [
(batch["id"], Path("batch_results") / f"{batch['id']}.jsonl")
for batch in manifest["batches"]
]
def parsed_annotations(
input_file: Path,
manifest_file: Path,
) -> polars.DataFrame:
"""Parse and validate OpenRouter responses, then match them to source IDs."""
records = []
for batch_id, result_file in result_files_from(manifest_file=manifest_file):
if not result_file.exists():
raise FileNotFoundError(f"Missing batch result: {result_file}")
with result_file.open(encoding="utf-8") as file:
for line in file:
result = json.loads(line)
if result.get("error") is not None:
raise RuntimeError(f"Failed result {result.get('custom_id')}: {result['error']}")
response = result["response"]
if response["status_code"] != 200:
raise RuntimeError(
f"Result {result['custom_id']} returned {response['status_code']}"
)
content = response["body"]["choices"][0]["message"]["content"]
annotation = json.loads(content)
score = annotation.get("educational_score")
category = annotation.get("category")
if not isinstance(score, int) or score not in range(6):
raise ValueError(f"Invalid score for {result['custom_id']}: {score}")
if category not in CATEGORIES:
raise ValueError(
f"Invalid category for {result['custom_id']}: {category}"
)
records.append(
{
"custom_id": result["custom_id"],
"batch_id": batch_id,
"justification": annotation["justification"],
"educational_score": score,
"category": category,
}
)
annotations = polars.DataFrame(data=records)
inputs = polars.read_ndjson(source=input_file).select("custom_id", "id")
if annotations.get_column("custom_id").n_unique() != annotations.height:
raise ValueError("Batch results contain duplicate custom IDs.")
if annotations.height != inputs.height:
raise ValueError(
f"Expected {inputs.height:,} results, received {annotations.height:,}."
)
matched = inputs.join(
other=annotations,
on="custom_id",
how="inner",
validate="1:1",
)
if matched.height != inputs.height:
raise ValueError("Some input rows have no matching batch result.")
return matched.select("id", *ANNOTATION_COLUMNS)
def fetch_full_window(
url: str,
seed: int,
storage_options: dict[str, str] | None,
) -> polars.DataFrame:
"""Re-fetch one deterministic candidate window with every source column."""
scan = polars.scan_parquet(source=url, storage_options=storage_options)
rows = scan.select(polars.len()).collect().item()
offset = random.Random(x=seed).randint(
a=0,
b=max(rows - ROWS_PER_WINDOW, 0),
)
return scan.slice(offset=offset, length=ROWS_PER_WINDOW).collect()
def source_rows_for(
source: str,
target_ids: polars.DataFrame,
storage_options: dict[str, str] | None,
) -> polars.DataFrame:
"""Re-fetch the full source rows selected for annotation."""
jobs = window_jobs_for(source=source)
windows: list[polars.DataFrame | None] = [None] * len(jobs)
with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
futures = {
executor.submit(
fetch_full_window,
url=url,
seed=seed,
storage_options=storage_options,
): index
for index, (url, seed) in enumerate(jobs)
}
for future in tqdm(
as_completed(futures),
total=len(futures),
desc=f"Re-fetching {source}",
):
windows[futures[future]] = future.result()
candidates = polars.concat(
items=[window for window in windows if window is not None]
).unique(subset="id", keep="first", maintain_order=True)
return candidates.join(
other=target_ids,
on="id",
how="semi",
)
def main(
input_file: str = "to_annotate_quality.jsonl",
manifest_file: str = "to_annotate_quality.batches.json",
existing_data: str = "data/annotated.parquet",
output_file: str = "data/annotated.parquet",
) -> None:
"""Write the existing and newly annotated rows with one shared schema."""
input_path = Path(input_file)
annotations = parsed_annotations(
input_file=input_path,
manifest_file=Path(manifest_file),
)
inputs = polars.read_ndjson(source=input_path).select("id", "source")
token = os.getenv("HF_TOKEN")
storage_options = {"token": token} if token else None
full_rows = polars.concat(
items=[
source_rows_for(
source=source,
target_ids=inputs.filter(polars.col("source") == source).select("id"),
storage_options=storage_options,
)
for source in SOURCE_SHARDS
]
)
if full_rows.height != inputs.height:
raise ValueError(
f"Recovered {full_rows.height:,} of {inputs.height:,} source rows."
)
existing = polars.read_parquet(source=existing_data)
new_rows = full_rows.join(
other=annotations,
on="id",
how="inner",
validate="1:1",
).select(existing.columns)
combined = polars.concat(items=[existing, new_rows])
if combined.get_column("id").n_unique() != combined.height:
raise ValueError("Combined dataset contains duplicate source IDs.")
output_path = Path(output_file)
temporary_path = output_path.with_suffix(".tmp.parquet")
combined.write_parquet(file=temporary_path)
temporary_path.replace(output_path)
print(
combined.group_by("source", "educational_score")
.len()
.sort("source", "educational_score")
)
print(f"Wrote {combined.height:,} rows to {output_path}")
if __name__ == "__main__":
import fire
fire.Fire(component=main)