Datasets:
File size: 4,733 Bytes
028b945 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 | #!/usr/bin/env python3
"""Convert APM prompt CSV files into JSONL examples for model inference."""
from __future__ import annotations
import argparse
import csv
import hashlib
import json
import re
from pathlib import Path
from typing import Any, Dict, Iterable, List
FILENAME_RE = re.compile(r"prompts_(?P<language>.+)_(?P<noise>N\d+)\.csv$")
ALPHA_RE = re.compile(r"alpha_(?P<value>\d+(?:\.\d+)?)$")
DEFAULT_INSTRUCTION = (
"Rewrite the noisy user prompt into a clear prompt that preserves the user's "
"intent. Return only the rewritten prompt; do not ask clarification questions "
"or add explanations."
)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--dataset-dir",
type=Path,
default=Path("."),
help="Directory containing prompts_<language>_<noise>.csv files.",
)
parser.add_argument(
"--output-dir",
type=Path,
default=Path("benchmark_inputs"),
help="Directory where JSONL inference inputs will be written.",
)
parser.add_argument(
"--no-instruction",
action="store_true",
help="Do not include the default mediation instruction in each row.",
)
parser.add_argument(
"--overwrite",
action="store_true",
help="Replace existing output files.",
)
return parser.parse_args()
def alpha_columns(fieldnames: Iterable[str]) -> List[str]:
columns = [name for name in fieldnames if ALPHA_RE.fullmatch(name)]
return sorted(columns, key=lambda name: float(ALPHA_RE.fullmatch(name).group("value")))
def example_id(payload: Dict[str, Any]) -> str:
stable = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
return hashlib.sha1(stable.encode("utf-8")).hexdigest()
def iter_examples(csv_path: Path, include_instruction: bool) -> Iterable[Dict[str, Any]]:
match = FILENAME_RE.match(csv_path.name)
if not match:
return
language = match.group("language")
noise = match.group("noise")
with csv_path.open("r", encoding="utf-8-sig", newline="") as f:
reader = csv.DictReader(f)
if reader.fieldnames is None:
return
alphas = alpha_columns(reader.fieldnames)
for row_index, row in enumerate(reader):
clean_text = row.get("Clean_text", "")
category = row.get("Category", "")
for alpha_col in alphas:
alpha_value = float(ALPHA_RE.fullmatch(alpha_col).group("value"))
noisy_prompt = row.get(alpha_col, "")
identity = {
"language": language,
"noise": noise,
"row_index": row_index,
"alpha": alpha_value,
"clean_text": clean_text,
"noisy_prompt": noisy_prompt,
}
example = {
"example_id": example_id(identity),
"language": language,
"noise": noise,
"category": category,
"alpha": alpha_value,
"clean_text": clean_text,
"noisy_prompt": noisy_prompt,
"source_file": csv_path.name,
"row_index": row_index,
}
if include_instruction:
example["instruction"] = DEFAULT_INSTRUCTION
yield example
def main() -> None:
args = parse_args()
csv_paths = sorted(args.dataset_dir.glob("prompts_*_N*.csv"))
if not csv_paths:
raise SystemExit(f"No prompt CSV files found in {args.dataset_dir}")
total = 0
args.output_dir.mkdir(parents=True, exist_ok=True)
for csv_path in csv_paths:
match = FILENAME_RE.match(csv_path.name)
if not match:
continue
language = match.group("language")
noise = match.group("noise")
out_dir = args.output_dir / noise
out_dir.mkdir(parents=True, exist_ok=True)
out_path = out_dir / f"{language}.jsonl"
if out_path.exists() and not args.overwrite:
raise SystemExit(f"{out_path} already exists; pass --overwrite to replace it")
count = 0
with out_path.open("w", encoding="utf-8") as f:
for example in iter_examples(csv_path, include_instruction=not args.no_instruction):
f.write(json.dumps(example, ensure_ascii=False) + "\n")
count += 1
total += count
print(f"Wrote {count:5d} examples -> {out_path}")
print(f"Prepared {total} inference examples")
if __name__ == "__main__":
main()
|