"""Compare fixed description observations and build a review ZIP."""
import argparse
from html import escape
import json
from pathlib import Path
from zipfile import ZIP_DEFLATED, ZipFile
NAME = "stock-audit"
BODY = "# Inventory checks\n\nAudit the selected inventory CSV or XLSX for missing stock counts and produce a short table.\n"
SPLITS = ("development", "holdout")
def read_json(path):
return json.loads(path.read_bytes())
def compare(cases, variants, observations):
cases_by_id = {row["id"]: row for row in cases}
if len(cases_by_id) != len(cases):
raise ValueError("duplicate case ID")
for row in cases:
if row["split"] not in SPLITS or type(row["expected"]) is not bool or not row["prompt"].strip():
raise ValueError("invalid case")
for split in SPLITS:
labels = {row["expected"] for row in cases if row["split"] == split}
if labels != {False, True}:
raise ValueError(f"{split} must include positives and negatives")
if observations["scope"] not in ("synthetic-fixture", "imported-host-trace"):
raise ValueError("invalid observation scope")
results = observations["candidates"]
if set(results) != set(variants) or not variants:
raise ValueError("candidate mismatch")
scores = {}
for variant, description in variants.items():
if not description.strip() or len(description) > 1024:
raise ValueError(f"invalid description length for {variant}")
records = results[variant]
if set(records) != set(cases_by_id) or any(type(choice) is not bool for choice in records.values()):
raise ValueError(f"invalid or missing decisions for {variant}")
per_split = {}
for split in SPLITS:
summary = {"hits": 0, "misses": 0, "false_activations": 0, "correct_rejections": 0}
for identifier, row in cases_by_id.items():
if row["split"] == split:
category = {(True, True): "hits", (True, False): "misses",
(False, True): "false_activations", (False, False): "correct_rejections"}
summary[category[row["expected"], records[identifier]]] += 1
summary["accuracy"] = (summary["hits"] + summary["correct_rejections"]) / sum(summary.values())
per_split[split] = summary
scores[variant] = per_split
winner = max(scores, key=lambda variant: (scores[variant]["development"]["accuracy"],
-scores[variant]["development"]["false_activations"], variant))
return {"scope": observations["scope"], "scores": scores, "development_choice": winner}
def write_report(path, variants, evaluation):
scope = escape(evaluation["scope"])
rows = []
for variant, scores in evaluation["scores"].items():
for split, result in scores.items():
cells = (variant, split, result["hits"], result["misses"], result["false_activations"],
result["correct_rejections"], f'{result["accuracy"]:.0%}')
rows.append(f'<tr data-case="{escape(variant + "-" + split)}">' +
"".join(f"<td>{escape(str(cell))}</td>" for cell in cells) + "</tr>")
text = ('<!doctype html><meta charset="utf-8"><title>Description comparison</title>'
f'<h1>Description comparison</h1><p id="scope">{scope}</p><p id="choice">'
f'{escape(evaluation["development_choice"])}</p><dl>' +
"".join(f"<dt>{escape(key)}</dt><dd>{escape(value)}</dd>" for key, value in variants.items()) +
'</dl><table><thead><tr><th>Version</th><th>Split</th><th>Hit</th><th>Miss</th><th>False activation</th>'
'<th>Correct rejection</th><th>Accuracy</th></tr></thead><tbody>' + "".join(rows) + "</tbody></table>")
path.write_text(text, encoding="utf-8", newline="\n")
def skill_file(description):
scalar = json.dumps(description, ensure_ascii=False)
return f"---\nname: {NAME}\ndescription: {scalar}\n---\n\n{BODY}"
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("cases", type=Path)
parser.add_argument("variants", type=Path)
parser.add_argument("observations", type=Path)
parser.add_argument("--report", type=Path, required=True)
parser.add_argument("--candidate-zip", type=Path, required=True)
args = parser.parse_args()
variants = read_json(args.variants)
try:
evaluation = compare(read_json(args.cases), variants, read_json(args.observations))
except (KeyError, TypeError, ValueError) as error:
parser.exit(2, f"{error}\n")
choice = evaluation["development_choice"]
write_report(args.report, variants, evaluation)
with ZipFile(args.candidate_zip, "w", compression=ZIP_DEFLATED) as archive:
archive.writestr(NAME + "/SKILL.md", skill_file(variants[choice]))
print(json.dumps(evaluation, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())
本例需在 Windows、Python 3.12。各实验所需工具和版本见下载包 README。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12。各实验所需工具和版本见下载包 README。
入口文件:projects/skills-description/compare.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
compare.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12。各实验所需工具和版本见下载包 README。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a331.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a338.zip