Rachel7's picture
Deploy af82b43: HVAC Blueprint Analyzer (T3 live deployment)
45a6327 verified
Raw History Blame Contribute Delete
6.76 kB
"""CLI: detect units on a page, score against ground truth, or do both.
Examples:
python -m analyzer.cli detect --pdf "path\\to\\set.pdf" --page 5
python -m analyzer.cli score --run runs\\p5_run1.json --gold ground_truth\\floor_005_Bulkhead_review.csv
python -m analyzer.cli eval --pdf "path\\to\\set.pdf" --page 5 --gold ground_truth\\floor_005_Bulkhead_review.csv
"""
import argparse
import datetime as dt
import sys
from collections import Counter
from pathlib import Path
from . import config
from .harness import export_review, score
from .markup import CATEGORY_COLORS, render_markup
def _parse_display_categories(s: str | None) -> list[str] | None:
"""Display filter: allows 'all' (None = show everything), any taxonomy id,
and 'other'. Unlike detection targets, 'other' is a valid display filter."""
if not s or s.strip().lower() == "all":
return None
valid = set(config.CATEGORIES) | {config.OTHER_CATEGORY}
cats = [c.strip() for c in s.split(",") if c.strip()]
unknown = [c for c in cats if c not in valid]
if unknown:
sys.exit(f"Unknown categories: {unknown}\nValid: {', '.join(sorted(valid))}")
return cats
def _parse_categories(s: str | None) -> list[str]:
if not s:
return list(config.DEFAULT_CATEGORIES)
if s.strip().lower() == "all":
return list(config.CATEGORIES)
cats = [c.strip() for c in s.split(",") if c.strip()]
unknown = [c for c in cats if c not in config.CATEGORIES]
if unknown:
sys.exit(f"Unknown categories: {unknown}\nValid: {', '.join(config.CATEGORIES)}")
return cats
def _run_detect(pdf: str, page: int, out: str | None, categories: list[str]) -> str:
if not config.ANTHROPIC_API_KEY:
sys.exit("No ANTHROPIC_API_KEY found. Copy .env.example to .env and add your key.")
from .detector import detect_page # import after key check
print(f"Detecting: {Path(pdf).name} page {page} | model={config.MODEL} effort={config.EFFORT}")
print(f"targets: {', '.join(categories)}")
result = detect_page(pdf, page, categories=categories)
if out is None:
stamp = dt.datetime.now().strftime("%Y%m%d_%H%M%S")
out = str(config.PROJECT_ROOT / "runs" / f"p{page}_{stamp}.json")
Path(out).parent.mkdir(parents=True, exist_ok=True)
Path(out).write_text(result.to_json(), encoding="utf-8")
u = result.usage
print(f"\nstop={result.stop} | {len(result.detections)} detections | "
f"{result.inspect_calls} inspections over {result.iterations} turns | {result.elapsed_s:.0f}s")
print(f"tokens: in={u.get('input_tokens',0):,} out={u.get('output_tokens',0):,} "
f"cache_read={u.get('cache_read_input_tokens',0):,} cache_write={u.get('cache_creation_input_tokens',0):,}")
print(f"cost: ${result.cost_usd:.2f}")
print(f"sheet: {result.sheet_summary}")
by_cat = Counter(d.category for d in result.detections)
print(f"by category: {', '.join(f'{c}={n}' for c, n in by_cat.most_common())}")
for d in result.detections:
print(f" {d.category:14s} {d.tag:12s} ({d.x:6.0f},{d.y:6.0f}) conf={d.confidence} {d.notes}")
print(f"\nsaved: {out}")
return out
def main() -> None:
ap = argparse.ArgumentParser(prog="analyzer")
sub = ap.add_subparsers(dest="cmd", required=True)
cat_help = "comma-separated category ids, or 'all' (default: all — detect everything). Options: " + ", ".join(config.CATEGORIES)
p_detect = sub.add_parser("detect", help="run detection on one page")
p_detect.add_argument("--pdf", required=True)
p_detect.add_argument("--page", type=int, required=True)
p_detect.add_argument("--categories", help=cat_help)
p_detect.add_argument("--out")
p_score = sub.add_parser("score", help="score a saved run against gold CSV")
p_score.add_argument("--run", required=True)
p_score.add_argument("--gold", required=True)
p_score.add_argument("--gold-category", default=config.INDOOR_UNIT_CATEGORY,
help="category the gold CSV covers (default: indoor_unit)")
p_eval = sub.add_parser("eval", help="detect then score")
p_eval.add_argument("--pdf", required=True)
p_eval.add_argument("--page", type=int, required=True)
p_eval.add_argument("--gold", required=True)
p_eval.add_argument("--categories", help=cat_help)
p_eval.add_argument("--gold-category", default=config.INDOOR_UNIT_CATEGORY)
p_eval.add_argument("--out")
p_export = sub.add_parser("export-review", help="write a saved run as a reviewable CSV (gold schema)")
p_export.add_argument("--run", required=True)
p_export.add_argument("--out", required=True)
p_export.add_argument("--floor", default="", help="floor_name to stamp on rows")
p_markup = sub.add_parser("markup", help="render the page with detection boxes, filtered by category")
p_markup.add_argument("--run", required=True)
p_markup.add_argument("--out", required=True)
p_markup.add_argument("--categories", help="display filter: comma list, 'other', or 'all' (default all)")
p_markup.add_argument("--dpi", type=int, default=150)
args = ap.parse_args()
if args.cmd == "detect":
_run_detect(args.pdf, args.page, args.out, _parse_categories(args.categories))
elif args.cmd == "score":
print(score(args.run, args.gold, args.gold_category).summary())
elif args.cmd == "eval":
cats = _parse_categories(args.categories)
if args.gold_category not in cats:
cats = [args.gold_category] + cats # ensure the scored category is actually detected
out = _run_detect(args.pdf, args.page, args.out, cats)
print("\n=== SCORE ===")
print(score(out, args.gold, args.gold_category).summary())
elif args.cmd == "export-review":
n = export_review(args.run, args.out, args.floor)
print(f"wrote {n} rows to {args.out}\nReview: set action=delete for wrong ones, "
"add rows (status=added) for misses, fix tag/category. Result is a gold CSV.")
elif args.cmd == "markup":
cats = _parse_display_categories(args.categories)
n, by_cat = render_markup(args.run, args.out, cats, args.dpi)
shown = ", ".join(f"{c}={by_cat[c]}" for c in sorted(by_cat, key=lambda k: -by_cat[k]))
print(f"drew {n} boxes -> {args.out}")
print(f"showing: {shown or '(none)'}")
print("legend:")
for c in sorted(by_cat):
r, g, b = CATEGORY_COLORS.get(c, (0.5, 0.5, 0.5))
print(f" {c:16s} RGB({int(r*255)},{int(g*255)},{int(b*255)})")
if __name__ == "__main__":
main()