Spaces:
Paused
Paused
File size: 57,953 Bytes
dac3297 | 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 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 | """
review_gui.py β Tkinter box reviewer for HVAC blueprint detections.
Steps through the detection boxes in a floor_*_review.csv, one at a time,
zoomed in, lets you CONFIRM / DELETE / MOVE / RESIZE / RELABEL each, then
shows a whole-floor OVERVIEW to confirm changes and ADD any missed units.
It only edits the review CSV β run `analyze_blueprint.py <pdf> --apply-review`
afterward to push corrections into the detection caches + YOLO labels.
Usage:
python review_gui.py <pdf> --out-dir output [--csv <name.csv>] [--all] [--dpi 300]
If --csv is omitted you'll pick from the review sheets found in --out-dir.
By default only non-'confirmed' boxes are stepped; use --all to step every box.
The overview at the end always shows ALL boxes.
"""
from __future__ import annotations
import argparse
import csv
import json
import subprocess
import sys
import tkinter as tk
from pathlib import Path
from tkinter import filedialog, messagebox, simpledialog, ttk
import fitz
from PIL import Image, ImageTk
ENGINE = Path(__file__).parent / "analyze_blueprint.py"
Image.MAX_IMAGE_PIXELS = None
CANVAS = 900
CONTEXT = 1.6
CROP_MIN = 900
HANDLE = 10
STATUS_COLOR = {"confirmed": "#2ecc40", "recovered": "#ff8c00",
"review": "#ffdc14", "added": "#b10dc9"}
# Training categories = the unit's form factor. The TAG (AC-2D-2, HP-1β¦) is for
# OUTPUT; the TYPE is the YOLO training class β stable across buildings where the
# tags are not. Set on a box with number keys 1-6 (applies to all same-tag boxes).
UNIT_TYPES = {
"1": "ceiling_ducted",
"2": "ceiling_cassette",
"3": "wall_mounted",
"4": "ceiling_suspended",
"5": "floor_standing",
"6": "condensing",
}
TYPE_SHORT = {
"ceiling_ducted": "ceiling ducted", "ceiling_cassette": "ceiling cassette",
"wall_mounted": "wall mounted", "ceiling_suspended": "ceiling suspended",
"floor_standing": "floor standing", "condensing": "condensing/outdoor",
}
LEGEND = [
("REVIEW KEYS", ""),
("Enter / c", "keep box"),
("d", "delete box"),
("r", "rename tag"),
("a", "approve rest"),
("", "of greens"),
("", ""),
("drag body", "move"),
("drag corner", "resize"),
("arrows", "nudge 10px"),
("Shift+arrow", "resize"),
("", ""),
("b", "previous box"),
("n", "skip box"),
("s", "save & quit"),
("q / Esc", "quit, no save"),
("", ""),
("OVERVIEW KEYS", ""),
("m", "add missed"),
("click box", "re-edit it"),
("Enter / c", "save floor"),
("e", "re-step all"),
("", ""),
("FLOOR NAV", ""),
("Ctrl+Right", "next floor"),
("Ctrl+Left", "prev floor"),
("", "(saves first)"),
("", ""),
("TYPE KEYS", "(training)"),
("1", "ceiling duct"),
("2", "cassette"),
("3", "wall mount"),
("4", "clg suspend"),
("5", "floor stand"),
("6", "condensing"),
]
def render_page(pdf_path: Path, page_0idx: int, dpi: int) -> Image.Image:
doc = fitz.open(pdf_path)
page = doc.load_page(page_0idx)
mat = fitz.Matrix(dpi / 72.0, dpi / 72.0)
pix = page.get_pixmap(matrix=mat, alpha=False)
return Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
class Reviewer:
def __init__(self, root, pdf_path, out_dir, dpi, show_all, start_csv):
self.root = root
self.pdf_path = Path(pdf_path)
self.out_dir = Path(out_dir)
self.dpi = dpi
self.show_all = show_all
self.plan_pages = self._load_manifest() # [(page_num, floor_name), β¦]
# per-floor state (set by load_floor)
self.img = None
self.rows = []
self.indices = []
self.csv_path = None
self.pos = 0
self.mode = "box"
self.single_edit = None
self.adding = False
self._next_id = 1
self.box = [0, 0, 0, 0]
self.crop_origin = (0, 0)
self.scale = 1.0
self._drag = None
self._newrect = None
# overview zoom/pan: ov_eff = canvas-px per image-px; ov_off = canvas offset
self.ov_zoom = 1.0
self.ov_eff = 1.0
self.ov_off = [0, 0]
self._ovpan = None
self.ov_img = None
self.page_num = None
self.floor_name = ""
self._build_ui()
self.load_floor(start_csv)
# ββ one-time UI construction βββββββββββββββββββββββββββββββββββββββββββββ
def _build_ui(self):
root = self.root
bar = tk.Frame(root, bg="black")
bar.pack(side=tk.TOP, fill=tk.X)
self.btn_prev = tk.Button(bar, text="β Prev floor", takefocus=0,
command=self.prev_floor)
self.btn_prev.pack(side=tk.LEFT, padx=4, pady=3)
self.btn_next = tk.Button(bar, text="Next floor βΆ", takefocus=0,
command=self.next_floor)
self.btn_next.pack(side=tk.LEFT, padx=4, pady=3)
self.floor_label = tk.Label(bar, text="", bg="black", fg="#7FDBFF",
font=("Consolas", 12, "bold"))
self.floor_label.pack(side=tk.LEFT, padx=12)
tk.Button(bar, text="Save", takefocus=0,
command=lambda: self.save_current(announce=True)
).pack(side=tk.RIGHT, padx=4, pady=3)
main = tk.Frame(root)
main.pack(side=tk.TOP, fill=tk.BOTH)
self.canvas = tk.Canvas(main, width=CANVAS, height=CANVAS, bg="gray20",
highlightthickness=0)
self.canvas.pack(side=tk.LEFT)
legend = tk.Frame(main, bg="black", width=200)
legend.pack(side=tk.RIGHT, fill=tk.Y)
for key, desc in LEGEND:
row = tk.Frame(legend, bg="black")
row.pack(side=tk.TOP, anchor="w", fill=tk.X, padx=8)
header = desc == "" and key.endswith("KEYS")
tk.Label(row, text=key, width=11, anchor="w", bg="black",
fg="#ffdc14" if header else "#7FDBFF",
font=("Consolas", 10, "bold" if header else "normal")
).pack(side=tk.LEFT)
tk.Label(row, text=desc, anchor="w", bg="black", fg="white",
font=("Consolas", 10)).pack(side=tk.LEFT)
self.status = tk.Label(root, text="", anchor="w", justify="left",
font=("Consolas", 11), bg="black", fg="white")
self.status.pack(side=tk.BOTTOM, fill=tk.X)
self.canvas.bind("<ButtonPress-1>", self.on_press)
self.canvas.bind("<B1-Motion>", self.on_motion)
self.canvas.bind("<ButtonRelease-1>", self.on_release)
# overview zoom: wheel (Win/Mac) + Button-4/5 (Linux)
self.canvas.bind("<MouseWheel>", self.on_wheel)
self.canvas.bind("<Button-4>", self.on_wheel)
self.canvas.bind("<Button-5>", self.on_wheel)
root.bind("<Return>", lambda e: self.on_enter())
root.bind("c", lambda e: self.on_enter())
root.bind("d", lambda e: self.mode == "box" and self.decide("delete"))
root.bind("r", lambda e: self.mode == "box" and self.relabel())
root.bind("a", lambda e: self.mode == "box" and self.approve_confirmed_rest())
root.bind("n", lambda e: self.mode == "box" and self.next_box())
root.bind("b", lambda e: self.mode == "box" and self.prev_box())
root.bind("m", lambda e: self.mode == "overview" and self.start_add())
root.bind("e", lambda e: self.mode == "overview" and self.restep())
# number keys 1-6 set the training TYPE on the current box (box mode)
for digit, utype in UNIT_TYPES.items():
root.bind(digit, lambda e, t=utype: self.mode == "box" and self.set_type(t))
root.bind("s", lambda e: self.save_current(announce=True))
root.bind("<Control-Right>", lambda e: self.next_floor())
root.bind("<Control-Left>", lambda e: self.prev_floor())
root.bind("q", lambda e: self.quit_nosave())
root.bind("<Escape>", lambda e: self.quit_nosave())
for key, dx, dy in (("Left", -10, 0), ("Right", 10, 0),
("Up", 0, -10), ("Down", 0, 10)):
root.bind(f"<{key}>", lambda e, dx=dx, dy=dy:
self.mode == "box" and self.nudge(dx, dy))
root.bind(f"<Shift-{key}>", lambda e, dx=dx, dy=dy:
self.mode == "box" and self.resize(dx, dy))
# ββ floor manifest + navigation ββββββββββββββββββββββββββββββββββββββββββ
def _load_manifest(self):
mpath = self.out_dir / "pages_manifest.csv"
if not mpath.exists():
return []
plan = []
for r in csv.DictReader(open(mpath, encoding="utf-8")):
if r.get("page_type") == "plan":
plan.append((int(r["page_num"]), r.get("floor_name", "")))
return sorted(plan)
def _review_csv_for_page(self, page_num):
hits = sorted(self.out_dir.glob(f"floor_{page_num:03d}_*_review.csv"))
return hits[0] if hits else None
@property
def cur_page(self):
# From the loaded floor (set even when the floor has zero boxes).
if self.page_num is not None:
return self.page_num
return int(self.rows[0]["page_num"]) if self.rows else None
def load_floor(self, csv_path):
csv_path = Path(csv_path)
rows = list(csv.DictReader(open(csv_path, encoding="utf-8")))
self.csv_path = csv_path
self.rows = rows
# A floor can legitimately have ZERO detected boxes (Gemini missed them
# all) β it must still open so the human can ADD the missed units. Take
# page/name from the rows, else parse them from the filename floor_NNN_*.
parts = csv_path.stem.split("_")
if rows:
page0 = int(rows[0]["page_num"]) - 1
self.floor_name = rows[0].get("floor_name", "")
else:
page0 = (int(parts[1]) - 1) if len(parts) > 1 and parts[1].isdigit() else 0
self.floor_name = " ".join(parts[2:-1]) if len(parts) > 3 else ""
self.page_num = page0 + 1
self._next_id = max((int(r["id"]) for r in rows), default=0) + 1
if self.show_all:
self.indices = list(range(len(rows)))
else:
self.indices = [i for i, r in enumerate(rows)
if r.get("status") != "confirmed"] or list(range(len(rows)))
self.pos = 0
self.mode = "box"
self.single_edit = None
self.adding = False
self.root.title(f"Review β {csv_path.name}")
empty_hint = " β 0 detected β add missed units with 'm'" if not rows else ""
self.floor_label.config(text=f"page {page0+1}: {self.floor_name}{empty_hint}")
self.img = render_page(self.pdf_path, page0, self.dpi)
self.root.focus_set()
# Start on the whole-floor OVERVIEW so duplicates/misses are visible first;
# click a box to edit/delete it, 'e' to step through every box, 'm' to add.
self.ov_zoom = 1.0
self.ov_off = [0, 0]
self.show_overview()
def next_floor(self):
self.save_current()
cur = self.cur_page or 0
# Navigate only among floors that were actually detected (have a review
# CSV). With --sample-floors we intentionally skip floors, so jump to the
# next DETECTED one instead of prompting to re-detect a skipped floor.
avail = sorted(int(p.name.split("_")[1]) for p in
self.out_dir.glob("floor_*_review.csv"))
later = [p for p in avail if p > cur]
if not later:
messagebox.showinfo(
"No more floors",
"This is the last detected floor.\n\n"
"(Only the sampled floors were detected β that's expected.)")
return
self.load_floor(self._review_csv_for_page(later[0]))
self.root.focus_set()
def prev_floor(self):
self.save_current()
cur = self.cur_page or 0
earlier = sorted(int(p.name.split("_")[1]) for p in
self.out_dir.glob("floor_*_review.csv"))
earlier = [p for p in earlier if p < cur]
if not earlier:
messagebox.showinfo("No previous floor", "This is the first reviewed floor.")
return
self.load_floor(self._review_csv_for_page(earlier[-1]))
self.root.focus_set()
def run_detection(self, page_num, name):
cmd = [sys.executable, str(Path(__file__).parent / "analyze_blueprint.py"),
str(self.pdf_path), "--out-dir", str(self.out_dir),
"--page", str(page_num), "--dpi", str(self.dpi), "-y"]
subprocess.Popen(cmd)
messagebox.showinfo(
"Detection started",
f"Detecting page {page_num} ({name}) in the background.\n"
f"Wait ~3β5 min, then click 'Next floor' again to load it.")
# ββ current row helpers ββββββββββββββββββββββββββββββββββββββββββββββββββ
@property
def row(self):
if self.single_edit is not None:
return self.rows[self.single_edit]
return self.rows[self.indices[self.pos]]
def on_enter(self):
if self.mode == "overview":
self.save_current()
else:
self.decide("keep")
def load_current(self):
if self.single_edit is None and self.pos >= len(self.indices):
self.show_overview()
return
r = self.row
bx, by, bw, bh = int(r["x"]), int(r["y"]), int(r["w"]), int(r["h"])
self.box = [bx, by, bx + bw, by + bh]
half = max(int(max(bw, bh) * CONTEXT), CROP_MIN)
cx, cy = bx + bw // 2, by + bh // 2
W, H = self.img.size
x0 = max(0, min(cx - half, W - 2 * half)) if W > 2 * half else 0
y0 = max(0, min(cy - half, H - 2 * half)) if H > 2 * half else 0
x1, y1 = min(W, x0 + 2 * half), min(H, y0 + 2 * half)
self.crop_origin = (x0, y0)
crop = self.img.crop((x0, y0, x1, y1))
self.scale = CANVAS / max(crop.size)
disp = crop.resize((int(crop.size[0] * self.scale),
int(crop.size[1] * self.scale)), Image.LANCZOS)
self.tkimg = ImageTk.PhotoImage(disp)
self.redraw()
# ββ coordinate mapping (box mode) ββββββββββββββββββββββββββββββββββββββββ
def img_to_canvas(self, ix, iy):
ox, oy = self.crop_origin
return (ix - ox) * self.scale, (iy - oy) * self.scale
def redraw(self):
self.canvas.delete("all")
self.canvas.create_image(0, 0, anchor=tk.NW, image=self.tkimg)
r = self.row
color = STATUS_COLOR.get(r["status"], "#ff4136")
cx0, cy0 = self.img_to_canvas(self.box[0], self.box[1])
cx1, cy1 = self.img_to_canvas(self.box[2], self.box[3])
self.canvas.create_rectangle(cx0, cy0, cx1, cy1, outline=color, width=3)
for hx, hy in ((cx0, cy0), (cx1, cy0), (cx0, cy1), (cx1, cy1)):
self.canvas.create_rectangle(hx - 5, hy - 5, hx + 5, hy + 5,
outline=color, fill="black")
disp_tag = r["action"] if (r.get("action") or "").startswith("AC") else r["tag"]
utype = r.get("unit_type") or ""
label = f"{disp_tag} [{TYPE_SHORT.get(utype, utype)}]" if utype else disp_tag
self.canvas.create_text(cx0 + 2, cy0 - 12, anchor=tk.W, text=label,
fill=color, font=("Consolas", 14, "bold"))
n = len(self.indices)
where = "single edit" if self.single_edit is not None else f"box {self.pos+1}/{n}"
action = r.get("action") or "β"
type_txt = TYPE_SHORT.get(utype, utype) if utype else "β press 1-6"
self.status.config(text=(
f" {where} id={r['id']} tag={r['tag']} type={type_txt} "
f"status={r['status']} action={action}"))
# ββ mouse (routes by mode) βββββββββββββββββββββββββββββββββββββββββββββββ
def on_press(self, e):
if self.mode == "overview":
return self.ov_press(e)
corners = {
"nw": self.img_to_canvas(self.box[0], self.box[1]),
"ne": self.img_to_canvas(self.box[2], self.box[1]),
"sw": self.img_to_canvas(self.box[0], self.box[3]),
"se": self.img_to_canvas(self.box[2], self.box[3]),
}
for name, (hx, hy) in corners.items():
if abs(e.x - hx) <= HANDLE and abs(e.y - hy) <= HANDLE:
self._drag = (name, e.x, e.y, list(self.box))
return
self._drag = ("move", e.x, e.y, list(self.box))
def on_motion(self, e):
if self.mode == "overview":
return self.ov_motion(e)
if not self._drag:
return
mode, sx, sy, box0 = self._drag
dix, diy = (e.x - sx) / self.scale, (e.y - sy) / self.scale
b = list(box0)
if mode == "move":
b = [box0[0] + dix, box0[1] + diy, box0[2] + dix, box0[3] + diy]
elif mode == "nw":
b[0], b[1] = box0[0] + dix, box0[1] + diy
elif mode == "ne":
b[2], b[1] = box0[2] + dix, box0[1] + diy
elif mode == "sw":
b[0], b[3] = box0[0] + dix, box0[3] + diy
elif mode == "se":
b[2], b[3] = box0[2] + dix, box0[3] + diy
self.box = [int(round(v)) for v in b]
self.redraw()
def on_release(self, e):
if self.mode == "overview":
return self.ov_release(e)
self._drag = None
self.commit_box()
# ββ keyboard box edits βββββββββββββββββββββββββββββββββββββββββββββββββββ
def nudge(self, dx, dy):
self.box = [self.box[0] + dx, self.box[1] + dy,
self.box[2] + dx, self.box[3] + dy]
self.commit_box(); self.redraw()
def resize(self, dx, dy):
self.box = [self.box[0], self.box[1],
max(self.box[0] + 10, self.box[2] + dx),
max(self.box[1] + 10, self.box[3] + dy)]
self.commit_box(); self.redraw()
def commit_box(self):
x0, y0, x1, y1 = self.box
if x1 < x0:
x0, x1 = x1, x0
if y1 < y0:
y0, y1 = y1, y0
r = self.row
r["x"], r["y"] = str(int(x0)), str(int(y0))
r["w"], r["h"] = str(int(x1 - x0)), str(int(y1 - y0))
# ββ decisions ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def decide(self, action):
self.commit_box()
self.row["action"] = action
if self.single_edit is not None:
self.single_edit = None
self.show_overview()
else:
self.next_box()
def relabel(self):
new = simpledialog.askstring("Relabel", "New tag (e.g. AC-D):",
parent=self.root)
if new:
self.row["action"] = new.strip().upper()
self.redraw()
def _disp_tag(self, r):
return r["action"] if (r.get("action") or "").startswith("AC") else r.get("tag", "")
def set_type(self, utype):
"""Set the training TYPE on the current box and every box sharing its tag
(form factor is consistent per tag), so it's one keypress per unit kind."""
tag = self._disp_tag(self.row)
n = 0
for rr in self.rows:
if self._disp_tag(rr) == tag:
rr["unit_type"] = utype
n += 1
self.redraw()
self.status.config(text=(
f" type β {TYPE_SHORT.get(utype, utype)} applied to {n} '{tag}' box(es) "
f"(tag stays for output; type is the training class)"))
def next_box(self):
self.pos += 1
self.load_current()
def prev_box(self):
if self.pos > 0:
self.pos -= 1
self.load_current()
def approve_confirmed_rest(self):
self.commit_box()
self.row["action"] = self.row.get("action") or "keep"
skipped, j = 0, self.pos + 1
while j < len(self.indices):
r = self.rows[self.indices[j]]
if r.get("status") == "confirmed":
r["action"] = r.get("action") or "keep"
skipped += 1; j += 1
else:
break
self.pos = j
if skipped:
print(f"Approved {skipped} confirmed box(es).")
self.load_current()
# ββ OVERVIEW mode ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
MAX_OV_ZOOM = 6.0
def show_overview(self):
self.mode = "overview"
self.single_edit = None
self.adding = False
self._ovpan = None
self.render_overview()
self.draw_overview()
def render_overview(self):
"""(Re)build the overview image at the current zoom. ov_eff = canvas-px
per image-px; BILINEAR keeps zoom snappy on the big 14k-px sheet."""
W, H = self.img.size
base = CANVAS / max(W, H) # fit-to-window scale
self.ov_eff = base * self.ov_zoom
disp = self.img.resize((max(1, int(W * self.ov_eff)),
max(1, int(H * self.ov_eff))), Image.BILINEAR)
self.ov_img = ImageTk.PhotoImage(disp)
def _clamp_off(self):
"""Keep the (possibly zoomed) image from drifting off-canvas: center it
when smaller than the canvas, else pin its edges to the canvas edges."""
W, H = self.img.size
for k, span in ((0, W * self.ov_eff), (1, H * self.ov_eff)):
if span <= CANVAS:
self.ov_off[k] = (CANVAS - span) / 2
else:
self.ov_off[k] = min(0, max(CANVAS - span, self.ov_off[k]))
def draw_overview(self):
self._clamp_off()
ox, oy = self.ov_off
self.canvas.delete("all")
self.canvas.create_image(ox, oy, anchor=tk.NW, image=self.ov_img)
changes = {"delete": 0, "relabel": 0, "added": 0, "moved": 0}
for r in self.rows:
x = int(r["x"]) * self.ov_eff + ox
y = int(r["y"]) * self.ov_eff + oy
w = int(r["w"]) * self.ov_eff
h = int(r["h"]) * self.ov_eff
act = (r.get("action") or "")
if act == "delete":
color = "#ff4136"; changes["delete"] += 1
elif act.startswith("AC") and act != r["tag"]:
color = "#0074d9"; changes["relabel"] += 1
elif r["status"] == "added":
color = "#b10dc9"; changes["added"] += 1
else:
color = STATUS_COLOR.get(r["status"], "#2ecc40")
self.canvas.create_rectangle(x, y, x + w, y + h, outline=color, width=2)
if act == "delete":
self.canvas.create_line(x, y, x + w, y + h, fill=color, width=1)
kept = sum(1 for r in self.rows if (r.get("action") or "") != "delete")
zoom_txt = f"zoom {self.ov_zoom:.1f}x" if self.ov_zoom > 1.0 else "wheel=zoom"
self.status.config(text=(
f" OVERVIEW β {len(self.rows)} boxes: {kept} kept, "
f"{changes['delete']} deleted, {changes['relabel']} relabeled, "
f"{changes['added']} added | {zoom_txt} Β· drag=pan Β· click box=edit Β· "
f"[m]=add missed Β· [Enter]=save Β· [q]=quit"))
def on_wheel(self, e):
"""Mouse-wheel zoom in the overview, anchored on the cursor."""
if self.mode != "overview" or self.img is None:
return
up = getattr(e, "delta", 0) > 0 or getattr(e, "num", 0) == 4
factor = 1.25 if up else 1 / 1.25
new = min(self.MAX_OV_ZOOM, max(1.0, self.ov_zoom * factor))
if new == self.ov_zoom:
return
old_eff = self.ov_eff
ix = (e.x - self.ov_off[0]) / old_eff # image point under cursor
iy = (e.y - self.ov_off[1]) / old_eff
self.ov_zoom = new
self.render_overview()
self.ov_off[0] = e.x - ix * self.ov_eff # keep that point under cursor
self.ov_off[1] = e.y - iy * self.ov_eff
self.draw_overview()
def ov_press(self, e):
if self.adding:
self._newrect = (e.x, e.y, e.x, e.y)
return
# click an existing box β edit it
for i, r in enumerate(self.rows):
x = int(r["x"]) * self.ov_eff + self.ov_off[0]
y = int(r["y"]) * self.ov_eff + self.ov_off[1]
w = int(r["w"]) * self.ov_eff
h = int(r["h"]) * self.ov_eff
if x <= e.x <= x + w and y <= e.y <= y + h:
self.mode = "box"
self.single_edit = i
self.load_current()
return
# clicked empty space β start panning the view
self._ovpan = (e.x, e.y, list(self.ov_off))
def ov_motion(self, e):
if self.adding and self._newrect:
x0, y0, _, _ = self._newrect
self._newrect = (x0, y0, e.x, e.y)
self.draw_overview()
self.canvas.create_rectangle(*self._newrect, outline="#b10dc9", width=2)
elif self._ovpan:
sx, sy, off0 = self._ovpan
self.ov_off = [off0[0] + (e.x - sx), off0[1] + (e.y - sy)]
self.draw_overview()
def ov_release(self, e):
if self._ovpan and not self.adding:
self._ovpan = None
return
if not (self.adding and self._newrect):
return
x0, y0, x1, y1 = self._newrect
self._newrect = None
self.adding = False
if abs(x1 - x0) < 5 or abs(y1 - y0) < 5:
self.draw_overview(); return
tag = simpledialog.askstring("Add missed unit",
"Tag for the new unit (e.g. AC-D):",
parent=self.root)
if not tag:
self.draw_overview(); return
ox, oy = self.ov_off
ix0, iy0 = (min(x0, x1) - ox) / self.ov_eff, (min(y0, y1) - oy) / self.ov_eff
ix1, iy1 = (max(x0, x1) - ox) / self.ov_eff, (max(y0, y1) - oy) / self.ov_eff
new = {
"id": str(self._next_id), "tag": tag.strip().upper(),
"status": "added", "action": "keep",
"x": str(int(ix0)), "y": str(int(iy0)),
"w": str(int(ix1 - ix0)), "h": str(int(iy1 - iy0)),
"page_num": str(self.page_num),
"floor_name": self.floor_name,
"unit_type": "",
}
self._next_id += 1
self.rows.append(new)
# open it zoomed so the user can fine-tune the rough overview box
self.mode = "box"
self.single_edit = len(self.rows) - 1
self.load_current()
def start_add(self):
self.adding = True
self.status.config(text=" ADD MISSED β drag a box around the unit, "
"then type its tag. (Esc to cancel)")
def restep(self):
self.mode = "box"
self.single_edit = None
self.pos = 0
self.indices = list(range(len(self.rows)))
self.load_current()
# ββ persistence ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def write_csv(self):
fields = ["id", "tag", "status", "action", "x", "y", "w", "h",
"page_num", "floor_name", "unit_type"]
with open(self.csv_path, "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=fields)
w.writeheader()
for r in self.rows:
w.writerow({k: r.get(k, "") for k in fields})
def save_current(self, announce=False):
"""Write the current floor's CSV (no quit). announce=True pops a
confirmation so explicit saves (Save button / 's') are unmistakable."""
if not self.csv_path:
if announce:
messagebox.showwarning("No floor", "No floor is loaded to save.")
return
try:
if self.mode == "box" and self.rows:
self.commit_box()
self.write_csv()
except Exception as e:
messagebox.showerror("Save failed", f"Could not save:\n{e}")
print(f"Save failed: {e}")
return
n = len(self.rows)
print(f"Saved {self.csv_path.name} ({n} boxes)")
self.status.config(text=f" β Saved {self.csv_path.name} ({n} boxes). "
f"Prev/Next floor to switch, or q to quit.")
if announce:
messagebox.showinfo("Saved", f"Saved {self.csv_path.name}\n{n} boxes written.")
def quit_nosave(self):
if self.adding: # Esc during add cancels add, not the app
self.adding = False
self._newrect = None
self.draw_overview()
return
if messagebox.askyesno("Quit", "Save the current floor before quitting?"):
self.save_current()
else:
print("Quit without saving current floor.")
self.root.destroy()
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Launcher β pick a PDF, list floors with run-status, detect, review
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ENGINE_DIR = ENGINE.parent / "hvac_pipeline"
class SchedulePicker(tk.Toplevel):
"""Page through the PDF, pick the schedule page, and optionally drag a box
around the schedule table. Calls on_pick(page_1based, region_or_None) where
region is (x0, y0, x1, y1) as 0-1 fractions of the page."""
def __init__(self, master, pdf_path, on_pick, start_page=1):
super().__init__(master)
self.title("Manually select schedule β page to it, then drag a box around the table")
self.pdf_path = str(pdf_path)
self.on_pick = on_pick
self.doc = fitz.open(self.pdf_path)
self.n = self.doc.page_count
self.page = max(1, min(start_page, self.n))
self.img_off = (0, 0) # where the page image sits on the canvas
self.disp_size = (1, 1) # rendered page size in px
self.rect_id = None
self.start = None
self.sel = None # selection in canvas px
bar = tk.Frame(self); bar.pack(side=tk.TOP, fill=tk.X)
tk.Button(bar, text="β Prev", command=self.prev).pack(side=tk.LEFT)
tk.Button(bar, text="Next βΆ", command=self.next).pack(side=tk.LEFT)
tk.Label(bar, text=" page").pack(side=tk.LEFT)
self.page_var = tk.StringVar(value=str(self.page))
e = tk.Entry(bar, width=5, textvariable=self.page_var); e.pack(side=tk.LEFT)
e.bind("<Return>", lambda _e: self.goto())
tk.Button(bar, text="Go", command=self.goto).pack(side=tk.LEFT)
self.lbl = tk.Label(bar, text=""); self.lbl.pack(side=tk.LEFT, padx=10)
tk.Button(bar, text="Use this region β", command=self.confirm_region,
font=("Segoe UI", 10, "bold")).pack(side=tk.RIGHT, padx=4)
tk.Button(bar, text="Use whole page", command=self.confirm_page).pack(side=tk.RIGHT)
tk.Button(bar, text="Clear box", command=self.clear_box).pack(side=tk.RIGHT, padx=4)
self.canvas = tk.Canvas(self, bg="gray20", cursor="cross")
self.canvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
self.canvas.bind("<ButtonPress-1>", self.on_press)
self.canvas.bind("<B1-Motion>", self.on_drag)
self.canvas.bind("<ButtonRelease-1>", self.on_up)
tk.Label(self, fg="gray40", anchor="w",
text="Tip: page to the schedule sheet, then drag a rectangle around the "
"INDOOR UNIT schedule table and click 'Use this region'. "
"No box? 'Use whole page' reads the entire sheet.").pack(
side=tk.BOTTOM, fill=tk.X)
self.geometry("1150x820")
self.bind("<Left>", lambda _e: self.prev())
self.bind("<Right>", lambda _e: self.next())
self.after(80, self.render)
# ββ navigation ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def prev(self):
if self.page > 1: self.page -= 1; self.render()
def next(self):
if self.page < self.n: self.page += 1; self.render()
def goto(self):
try:
p = int(self.page_var.get())
except ValueError:
return
self.page = max(1, min(p, self.n)); self.render()
def render(self):
self.sel = None
page = self.doc.load_page(self.page - 1)
cw = max(400, self.canvas.winfo_width())
ch = max(300, self.canvas.winfo_height())
r = page.rect
sc = min(cw / r.width, ch / r.height)
pix = page.get_pixmap(matrix=fitz.Matrix(sc, sc), alpha=False)
self.pil = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
self.disp_size = self.pil.size
self.tkimg = ImageTk.PhotoImage(self.pil)
self.canvas.delete("all")
ox = max(0, (cw - pix.width) // 2); oy = max(0, (ch - pix.height) // 2)
self.img_off = (ox, oy)
self.canvas.create_image(ox, oy, anchor="nw", image=self.tkimg)
self.rect_id = None
self.page_var.set(str(self.page))
self.lbl.config(text=f"page {self.page}/{self.n}")
# ββ box drawing βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ--
def on_press(self, e):
self.start = (e.x, e.y)
if self.rect_id: self.canvas.delete(self.rect_id)
self.rect_id = self.canvas.create_rectangle(e.x, e.y, e.x, e.y,
outline="#00e0ff", width=2)
def on_drag(self, e):
if self.rect_id and self.start:
self.canvas.coords(self.rect_id, self.start[0], self.start[1], e.x, e.y)
def on_up(self, e):
if not self.start: return
x0, y0 = self.start; x1, y1 = e.x, e.y
self.sel = (min(x0, x1), min(y0, y1), max(x0, x1), max(y0, y1))
def clear_box(self):
if self.rect_id: self.canvas.delete(self.rect_id); self.rect_id = None
self.sel = None
def _normalized(self):
ox, oy = self.img_off
w, h = self.disp_size
x0, y0, x1, y1 = self.sel
fx0 = min(max((x0 - ox) / w, 0.0), 1.0)
fy0 = min(max((y0 - oy) / h, 0.0), 1.0)
fx1 = min(max((x1 - ox) / w, 0.0), 1.0)
fy1 = min(max((y1 - oy) / h, 0.0), 1.0)
return (fx0, fy0, fx1, fy1)
# ββ confirm βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ--
def confirm_region(self):
if not self.sel or (self.sel[2] - self.sel[0]) < 8 or (self.sel[3] - self.sel[1]) < 8:
messagebox.showinfo("Draw a box first",
"Drag a rectangle around the schedule table, "
"or use 'Use whole page'.")
return
page, region = self.page, self._normalized()
self.destroy()
self.on_pick(page, region)
def confirm_page(self):
page = self.page
self.destroy()
self.on_pick(page, None)
class Launcher:
"""Front door: upload a PDF β schedule check β run all/some floors with the
best recipe β schedule + cross-floor flags β per-floor PNG / verify."""
def __init__(self, root, base_out=Path("output"), dpi=300):
self.root = root
self.base_out = Path(base_out)
self.dpi = dpi
self.pdf = None
self.crisp = None # optional un-flattened/crisp PDF for rendering
self.out_dir = None
self.plan_pages = []
self.proc = None
self.proc_log = None
self._ran_all = False # whether the last run covered all floors
root.title("HVAC Blueprint Analyzer")
top = tk.Frame(root, padx=10, pady=6); top.pack(side=tk.TOP, fill=tk.X)
tk.Button(top, text="β Select PDFβ¦", command=self.select_pdf,
font=("Segoe UI", 10, "bold")).pack(side=tk.LEFT)
self.pdf_lbl = tk.Label(top, text="no PDF selected", fg="gray30", font=("Consolas", 10))
self.pdf_lbl.pack(side=tk.LEFT, padx=8)
tk.Button(top, text="Crisp PDF (optional)β¦", command=self.select_crisp).pack(side=tk.RIGHT)
info = tk.Frame(root, padx=10); info.pack(side=tk.TOP, fill=tk.X)
self.sched_lbl = tk.Label(info, text="Schedule: β", fg="gray30", font=("Consolas", 10))
self.sched_lbl.pack(side=tk.LEFT)
tk.Button(info, text="Manually select scheduleβ¦", command=self.manual_schedule).pack(side=tk.RIGHT)
# recipe controls (default = the best recipe we validated)
rec = tk.LabelFrame(root, text="Recipe", padx=8, pady=4); rec.pack(side=tk.TOP, fill=tk.X, padx=10)
self.v_runs = tk.IntVar(value=3); self.v_tile = tk.IntVar(value=1800)
self.v_fp = tk.BooleanVar(value=True); self.v_alltags = tk.BooleanVar(value=True)
self.force = tk.BooleanVar(value=False)
tk.Label(rec, text="runs").pack(side=tk.LEFT)
tk.Spinbox(rec, from_=1, to=5, width=3, textvariable=self.v_runs).pack(side=tk.LEFT, padx=(2, 10))
tk.Label(rec, text="tile").pack(side=tk.LEFT)
tk.Spinbox(rec, from_=1000, to=3000, increment=200, width=5, textvariable=self.v_tile).pack(side=tk.LEFT, padx=(2, 10))
tk.Checkbutton(rec, text="fp-filter", variable=self.v_fp).pack(side=tk.LEFT)
tk.Checkbutton(rec, text="all-tags", variable=self.v_alltags).pack(side=tk.LEFT)
tk.Checkbutton(rec, text="force re-detect", variable=self.force).pack(side=tk.LEFT, padx=10)
cols = ("page", "floor", "status")
self.tree = ttk.Treeview(root, columns=cols, show="headings", height=14, selectmode="extended")
for c, w in (("page", 55), ("floor", 230), ("status", 230)):
self.tree.heading(c, text=c.title()); self.tree.column(c, width=w, anchor="w")
self.tree.pack(side=tk.TOP, fill=tk.BOTH, expand=True, padx=10)
self.tree.bind("<Double-1>", lambda e: self.review_selected())
btns = tk.Frame(root, padx=10, pady=6); btns.pack(side=tk.TOP, fill=tk.X)
self.btn_all = tk.Button(btns, text="βΆ Run ALL floors", command=self.detect_all_missing,
state=tk.DISABLED, font=("Segoe UI", 10, "bold"))
self.btn_all.pack(side=tk.LEFT, padx=3)
self.btn_one = tk.Button(btns, text="Run selected", command=self.detect_selected, state=tk.DISABLED)
self.btn_one.pack(side=tk.LEFT, padx=3)
self.btn_review = tk.Button(btns, text="Verify selected βΆ", command=self.review_selected,
state=tk.DISABLED, font=("Segoe UI", 10, "bold"))
self.btn_review.pack(side=tk.LEFT, padx=3)
self.btn_png = tk.Button(btns, text="Open PNG", command=self.open_png, state=tk.DISABLED)
self.btn_png.pack(side=tk.LEFT, padx=3)
tk.Button(btns, text="Re-check schedule", command=lambda: self.reconcile_schedule(True)).pack(side=tk.LEFT, padx=3)
tk.Button(btns, text="Cross-floor check", command=lambda: self.cross_floor(True)).pack(side=tk.LEFT, padx=3)
tk.Button(btns, text="Room-coverage check", command=lambda: self.room_coverage(True)).pack(side=tk.LEFT, padx=3)
tk.Button(btns, text="Refresh", command=self.refresh_status).pack(side=tk.LEFT, padx=3)
flag_fr = tk.LabelFrame(root, text="Flags β schedule mismatches & cross-floor issues", padx=4, pady=2)
flag_fr.pack(side=tk.TOP, fill=tk.X, padx=10, pady=(0, 4))
self.flags = tk.Text(flag_fr, height=7, font=("Consolas", 9), wrap="word", bg="#111", fg="#eee")
self.flags.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.flags.insert("end", "(flags appear here after a run / schedule check)")
self.flags.config(state=tk.DISABLED)
self.progress = tk.Label(root, text="Select a blueprint PDF to begin.", anchor="w",
bg="black", fg="white", font=("Consolas", 10))
self.progress.pack(side=tk.BOTTOM, fill=tk.X)
# ββ selection ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def select_pdf(self):
path = filedialog.askopenfilename(title="Select blueprint PDF",
filetypes=[("PDF files", "*.pdf"), ("All files", "*.*")])
if not path:
return
self.pdf = Path(path)
self.out_dir = self.base_out / self.pdf.stem
self.out_dir.mkdir(parents=True, exist_ok=True)
self.pdf_lbl.config(text=f"{self.pdf.name} β {self.out_dir}", fg="black")
self.scan_floors()
def select_crisp(self):
if not self.pdf:
messagebox.showinfo("Select PDF first", "Pick the main PDF first.")
return
path = filedialog.askopenfilename(title="Select crisp / un-flattened PDF (same pages)",
filetypes=[("PDF files", "*.pdf")])
if path:
self.crisp = Path(path)
self.pdf_lbl.config(text=f"{self.pdf.name} +crisp:{self.crisp.name}", fg="black")
def _render_pdf(self):
return self.crisp or self.pdf
# ββ scan / schedule ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _schedule_cache(self):
return self.out_dir / f"{self.pdf.stem}_schedule_cache.json"
# ββ manual schedule selection βββββββββββββββββββββββββββββββββββββββββββββ
def manual_schedule(self):
if not self.pdf:
messagebox.showinfo("Select PDF first", "Pick a blueprint PDF first."); return
if self.proc is not None:
messagebox.showinfo("Busy", "A run is already in progress."); return
SchedulePicker(self.root, self.pdf, self._run_manual_schedule, start_page=1)
def _run_manual_schedule(self, page, region):
cmd = [sys.executable, str(ENGINE), str(self.pdf), "--out-dir", str(self.out_dir),
"--dpi", str(self.dpi), "--schedule-page", str(page),
"--step", "schedule", "--refresh-schedule", "-y"]
if region:
cmd += ["--schedule-region", ",".join(f"{v:.4f}" for v in region)]
self.progress.config(text=f"Reading schedule from page {page}"
+ (" (boxed region)β¦" if region else " (whole page)β¦"))
self._run(cmd, on_done=self._after_manual_schedule)
def _after_manual_schedule(self):
self.refresh_status()
cache = self._schedule_cache()
if cache.exists():
try:
data = json.load(open(cache, encoding="utf-8"))
tags = ", ".join(sorted(data.keys())) or "(none)"
messagebox.showinfo("Schedule read",
f"Found {len(data)} unit tag(s):\n\n{tags}")
except Exception:
pass
else:
messagebox.showwarning("No schedule found",
"Nothing was read from that page/region. "
"Try a tighter box around the indoor-unit table, "
"or a different page.")
def scan_floors(self):
manifest = self.out_dir / "pages_manifest.csv"
if manifest.exists():
self._load_manifest(); self.refresh_status()
else:
self.progress.config(text="Reading schedule + classifying pages (one-time)β¦")
cmd = [sys.executable, str(ENGINE), str(self.pdf), "--out-dir", str(self.out_dir),
"--dpi", str(self.dpi), "--classify-only", "-y"]
self._run(cmd, on_done=self._after_classify)
def _after_classify(self):
if (self.out_dir / "pages_manifest.csv").exists():
self._load_manifest(); self.refresh_status()
else:
self.progress.config(text="Classification failed β check console / GEMINI_API_KEY.")
def _load_manifest(self):
self.plan_pages = []
for r in csv.DictReader(open(self.out_dir / "pages_manifest.csv", encoding="utf-8")):
if r.get("page_type") == "plan":
self.plan_pages.append((int(r["page_num"]), r.get("floor_name", "")))
self.plan_pages.sort()
def _review_csv_for_page(self, page_num):
hits = sorted(self.out_dir.glob(f"floor_{page_num:03d}_*_review.csv"))
return hits[0] if hits else None
def refresh_status(self):
self.tree.delete(*self.tree.get_children())
for page, name in self.plan_pages:
csvp = self._review_csv_for_page(page)
n = ""
if csvp:
n = f"β {sum(1 for _ in csv.DictReader(open(csvp, encoding='utf-8')))} units β verify/PNG"
else:
n = "β not run"
self.tree.insert("", tk.END, iid=str(page), values=(page, name, n))
for b in (self.btn_all, self.btn_one, self.btn_review, self.btn_png):
b.config(state=tk.NORMAL)
if self.pdf:
self.sched_lbl.config(
text="Schedule: cached β (re-used)" if self._schedule_cache().exists()
else "Schedule: will extract on first run",
fg="green" if self._schedule_cache().exists() else "gray30")
ran = sum(1 for p, _ in self.plan_pages if self._review_csv_for_page(p))
if self.proc is None:
self.progress.config(text=f"{len(self.plan_pages)} floors Β· {ran} ran Β· "
f"{len(self.plan_pages)-ran} remaining.")
def _selected_pages(self):
return [int(i) for i in self.tree.selection()]
# ββ detection (best recipe) ββββββββββββββββββββββββββββββββββββββββββββββ
def detect_all_missing(self):
pages = [p for p, _ in self.plan_pages] if self.force.get() else \
[p for p, _ in self.plan_pages if not self._review_csv_for_page(p)]
if not pages:
messagebox.showinfo("Nothing to do", "All floors ran. Tick force re-detect to redo.")
return
self._detect(pages, ran_all=True)
def detect_selected(self):
pages = self._selected_pages()
if not pages:
messagebox.showinfo("Pick a floor", "Select floor(s) first."); return
if not self.force.get():
pages = [p for p in pages if not self._review_csv_for_page(p)]
if not pages:
messagebox.showinfo("Already ran", "Selected ran. Tick force re-detect to redo."); return
self._detect(pages, ran_all=False)
def _detect(self, pages, ran_all):
if self.proc is not None:
messagebox.showinfo("Busy", "A run is already in progress."); return
self._ran_all = ran_all
rng = ",".join(str(p) for p in pages)
cmd = [sys.executable, str(ENGINE), str(self.pdf), "--out-dir", str(self.out_dir),
"--dpi", str(self.dpi), "--pages", rng,
"--tile-size", str(self.v_tile.get()), "--runs", str(self.v_runs.get()), "-y"]
if self.v_alltags.get(): cmd.append("--all-tags")
if self.v_fp.get(): cmd.append("--fp-filter")
if self.crisp: cmd += ["--render-pdf", str(self.crisp)]
if self.force.get(): cmd.append("--refresh-detections")
self.progress.config(text=f"Running {len(pages)} floor(s): tile={self.v_tile.get()} "
f"runs={self.v_runs.get()} all-tags={self.v_alltags.get()} "
f"fp={self.v_fp.get()}β¦")
self._run(cmd, on_done=self._after_detect)
def _after_detect(self):
# always reconcile schedule; cross-floor only if we ran everything
self.reconcile_schedule(announce=False, then_crossfloor=self._ran_all)
# ββ QA: schedule reconcile + cross-floor βββββββββββββββββββββββββββββββββ
def reconcile_schedule(self, announce=True, then_crossfloor=False):
if self.proc is not None:
return
cmd = [sys.executable, str(ENGINE_DIR / "reconcile_schedule.py"), str(self.pdf),
"--out-dir", str(self.out_dir)]
if self.crisp: cmd += ["--render-pdf", str(self.crisp)]
self.progress.config(text="Checking detected counts vs scheduleβ¦")
self._run(cmd, on_done=lambda: self._after_reconcile(then_crossfloor))
def _after_reconcile(self, then_crossfloor):
if then_crossfloor and len([p for p, _ in self.plan_pages if self._review_csv_for_page(p)]) >= 3:
self.cross_floor(announce=False)
else:
self.room_coverage()
def cross_floor(self, announce=True):
if self.proc is not None:
return
cmd = [sys.executable, str(ENGINE_DIR / "cross_floor_check.py"),
"--out-dir", str(self.out_dir)]
self.progress.config(text="Running cross-floor consistency checkβ¦")
self._run(cmd, on_done=self.room_coverage)
def room_coverage(self, announce=False):
# Layered room-coverage check: spatial gap finder β Gemini confirm.
# Runs automatically after every detection so missed-room flags appear.
if self.proc is not None:
return
cmd = [sys.executable, str(ENGINE_DIR / "room_coverage_check.py"), str(self.pdf),
"--out-dir", str(self.out_dir), "--dpi", str(self.dpi)]
if self.crisp: cmd += ["--render-pdf", str(self.crisp)]
self.progress.config(text="Checking room coverage (gaps where a unit may be missing)β¦")
self._run(cmd, on_done=self.show_flags)
def show_flags(self):
self.flags.config(state=tk.NORMAL); self.flags.delete("1.0", "end")
# schedule conflicts
sc = self.out_dir / "schedule_conflicts.csv"
if sc.exists():
rows = [r for r in csv.DictReader(open(sc, encoding="utf-8"))]
self.flags.insert("end", f"SCHEDULE MISMATCHES ({len(rows)}):\n")
for r in rows[:20]:
self.flags.insert("end", f" {r['tag']}: detected {r['detected_count']} vs "
f"schedule {r['schedule_qty']} (floors: {r['floors']}) "
f"-> conflict_{r['tag'].replace('-','')}.png\n")
# cross-floor missing + tag flags
for fn, hdr in (("cross_floor_missing.csv", "CROSS-FLOOR MISSING (a unit most floors have)"),
("cross_floor_flags.csv", "CROSS-FLOOR TAG OUTLIERS")):
p = self.out_dir / fn
if p.exists():
rows = [r for r in csv.DictReader(open(p, encoding="utf-8"))]
if rows:
self.flags.insert("end", f"\n{hdr} ({len(rows)}):\n")
for r in rows[:15]:
self.flags.insert("end", " " + ", ".join(f"{k}={v}" for k, v in r.items()) + "\n")
# room-coverage (possible missed rooms)
rc = self.out_dir / "room_coverage_flags.csv"
if rc.exists():
rows = [r for r in csv.DictReader(open(rc, encoding="utf-8"))]
conf = [r for r in rows if str(r.get("confirmed")).lower() == "true"]
shown = conf or rows
if shown:
lbl = "POSSIBLE MISSED ROOMS (model-confirmed)" if conf else \
"POSSIBLE MISSED ROOMS (spatial gaps β unconfirmed)"
self.flags.insert("end", f"\n{lbl} ({len(shown)}):\n")
for r in shown[:15]:
short = r['floor'].replace('_review.csv', '').replace('floor_', 'f')
self.flags.insert("end", f" {short} at ({r['cx']},{r['cy']}) "
f"{r.get('kind','')} {r.get('note','')} "
f"-> roomgap_{short}_*.png\n")
if self.flags.get("1.0", "end").strip() == "":
self.flags.insert("end", "No flags β detected counts match schedule, no cross-floor issues.")
self.flags.config(state=tk.DISABLED)
self.refresh_status()
self.progress.config(text="Done. Review flags above; verify floors as needed.")
# ββ per-floor PNG / verify βββββββββββββββββββββββββββββββββββββββββββββββ
def open_png(self):
pages = self._selected_pages()
if not pages:
messagebox.showinfo("Pick a floor", "Select a floor."); return
png = sorted(self.out_dir.glob(f"floor_{pages[0]:03d}_*_annotated.png"))
if png:
import os as _os
_os.startfile(str(png[0])) # opens in default image viewer (Windows)
else:
messagebox.showinfo("No PNG", "That floor hasn't been detected yet.")
def review_selected(self):
pages = self._selected_pages()
if not pages:
messagebox.showinfo("Pick a floor", "Select a floor to verify."); return
csvp = self._review_csv_for_page(pages[0])
if not csvp:
if messagebox.askyesno("Not detected", f"Page {pages[0]} not detected yet. Run it now?"):
self._detect([pages[0]], ran_all=False)
return
win = tk.Toplevel(self.root)
Reviewer(win, self._render_pdf(), self.out_dir, self.dpi, show_all=True, start_csv=csvp)
win.transient(self.root); win.grab_set()
self.root.wait_window(win)
self.refresh_status()
# ββ subprocess plumbing ββββββββββββββββββββββββββββββββββββββββββββββββββ
def _run(self, cmd, on_done):
self._on_done = on_done
self.proc_log = open(self.out_dir / "_gui_run.log", "w", encoding="utf-8")
self.proc = subprocess.Popen(cmd, stdout=self.proc_log, stderr=subprocess.STDOUT)
self._poll()
def _poll(self):
if self.proc is None:
return
if self.proc.poll() is None:
try:
lines = [l for l in (self.out_dir / "_gui_run.log").read_text(
encoding="utf-8", errors="replace").splitlines() if l.strip()]
if lines:
self.progress.config(text=" " + lines[-1][:140])
except OSError:
pass
self.refresh_status()
self.root.after(1500, self._poll)
else:
if self.proc_log:
self.proc_log.close()
self.proc = None
self.refresh_status()
cb, self._on_done = self._on_done, None
if cb:
cb()
def main():
ap = argparse.ArgumentParser(description="HVAC Blueprint Analyzer β GUI")
ap.add_argument("pdf", type=Path, nargs="?", default=None,
help="Optional: open straight into this PDF (else use the picker)")
ap.add_argument("--out-dir", type=Path, default=Path("output"),
help="Base outputs dir; each PDF gets its own subfolder")
ap.add_argument("--csv", type=str, default=None,
help="Open a specific review sheet directly (legacy mode)")
ap.add_argument("--dpi", type=int, default=300)
ap.add_argument("--all", action="store_true")
args = ap.parse_args()
root = tk.Tk()
# Legacy direct-review mode: --csv with an explicit pdf + out-dir
if args.csv and args.pdf:
csv_path = args.out_dir / args.csv
if not csv_path.exists():
sys.exit(f"Review CSV not found: {csv_path}")
Reviewer(root, args.pdf, args.out_dir, args.dpi, args.all, csv_path)
else:
launcher = Launcher(root, base_out=args.out_dir, dpi=args.dpi)
if args.pdf: # pre-load a PDF if given
launcher.pdf = args.pdf
launcher.out_dir = args.out_dir / args.pdf.stem
launcher.out_dir.mkdir(parents=True, exist_ok=True)
launcher.pdf_lbl.config(text=f"{args.pdf.name} β {launcher.out_dir}",
fg="black")
launcher.scan_floors()
root.mainloop()
if __name__ == "__main__":
main()
|