Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -561,66 +561,226 @@ def find_all_circuit_paths(G, details_map, max_paths=20):
|
|
| 561 |
|
| 562 |
return all_paths
|
| 563 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 564 |
|
| 565 |
-
|
|
|
|
|
|
|
|
|
|
| 566 |
details_map = {d['label']: d for d in details} if details else {}
|
| 567 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 568 |
|
| 569 |
-
|
|
|
|
|
|
|
|
|
|
| 570 |
return "No connections detected between components."
|
| 571 |
|
| 572 |
gnd_nodes = set(get_gnd_nodes(G))
|
| 573 |
|
| 574 |
-
lines = ["DIRECT WIRE CONNECTIONS:", "β"*42]
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
|
|
|
|
|
|
|
|
|
| 578 |
|
|
|
|
| 579 |
lines += ["", "β"*42,
|
| 580 |
-
"CIRCUIT PATHS
|
| 581 |
"β"*42]
|
| 582 |
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
path_groups = find_all_circuit_paths(G, details_map)
|
| 587 |
|
| 588 |
-
if not
|
| 589 |
-
lines.append("\n
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
lines.append(
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
for i, comp in enumerate(comps, 1):
|
| 607 |
-
lines.append(f" Section {i}: {', '.join(fmt(n) for n in sorted(comp))}")
|
| 608 |
-
|
| 609 |
-
lines.append("\nTOPOLOGY:")
|
| 610 |
-
degs = dict(G.degree())
|
| 611 |
-
branches = [n for n, deg in degs.items() if deg > 2 and n not in gnd_nodes]
|
| 612 |
-
if branches:
|
| 613 |
-
lines.append(" Parallel / multi-branch circuit")
|
| 614 |
-
lines.append(f" Junction nodes: {', '.join(fmt(n) for n in branches)}")
|
| 615 |
else:
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 622 |
|
| 623 |
return "\n".join(lines)
|
|
|
|
| 624 |
|
| 625 |
def detect_gnd_symbols(img_np, details):
|
| 626 |
"""
|
|
@@ -839,7 +999,7 @@ def handle_image1(image, confidence):
|
|
| 839 |
src = d.get("source") or "default"
|
| 840 |
sch = d.get("schematic_label", d['label'])
|
| 841 |
report += f"{sch} [{d['label']}] ({d['component']}) = {d['value'] or 'unknown'} ({src})\n"
|
| 842 |
-
report += "\n" + describe_connectivity(G, details=details) + "\n"
|
| 843 |
return annotated, net_vis, details, summary, report, "", get_debug_text()
|
| 844 |
except Exception as e:
|
| 845 |
traceback.print_exc()
|
|
|
|
| 561 |
|
| 562 |
return all_paths
|
| 563 |
|
| 564 |
+
def get_circuit_paths_with_vlm(full_image_pil, details):
|
| 565 |
+
"""
|
| 566 |
+
Use Qwen VLM to directly read circuit paths from the image.
|
| 567 |
+
This bypasses Wire-CC entirely for path detection.
|
| 568 |
+
"""
|
| 569 |
+
comp_list = "\n".join([
|
| 570 |
+
f"- {d.get('schematic_label', d['label'])} ({d['component']}, {d['value']})"
|
| 571 |
+
for d in details
|
| 572 |
+
if 'GND' not in d['label']
|
| 573 |
+
])
|
| 574 |
+
prompt = (
|
| 575 |
+
"You are an expert electrical engineer analyzing a circuit schematic diagram.\n\n"
|
| 576 |
+
f"These components are in the circuit:\n{comp_list}\n\n"
|
| 577 |
+
"TASK: Trace every complete current path from each voltage source to ground.\n\n"
|
| 578 |
+
"Rules:\n"
|
| 579 |
+
"1. Start from each voltage source positive terminal\n"
|
| 580 |
+
"2. Trace through components following the wires\n"
|
| 581 |
+
"3. End at Ground (GND symbol β three horizontal lines at bottom)\n"
|
| 582 |
+
"4. List EVERY distinct path you can trace\n"
|
| 583 |
+
"5. Only include components you can see a wire connecting\n"
|
| 584 |
+
"6. Do NOT guess β only trace paths you can visually confirm\n\n"
|
| 585 |
+
"Format β output ONLY path lines like this:\n"
|
| 586 |
+
"PATH: V1 β S1 β L1 β L2 β C1 β LED1 β GND\n"
|
| 587 |
+
"PATH: V1 β S1 β R1 β L4 β C1 β LED1 β GND\n"
|
| 588 |
+
"PATH: V2 β S2 β R3 β L3 β C2 β GND\n\n"
|
| 589 |
+
"Each PATH line must:\n"
|
| 590 |
+
"- Start with PATH:\n"
|
| 591 |
+
"- Use β between components\n"
|
| 592 |
+
"- Use exact schematic labels from the list above\n"
|
| 593 |
+
"- End with GND (or the ground node name)\n"
|
| 594 |
+
"- Be a complete loop path\n\n"
|
| 595 |
+
"Output ONLY PATH lines, nothing else."
|
| 596 |
+
)
|
| 597 |
+
messages = [{"role": "user", "content": [
|
| 598 |
+
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image_to_b64(full_image_pil)}"}},
|
| 599 |
+
{"type": "text", "text": prompt}
|
| 600 |
+
]}]
|
| 601 |
+
|
| 602 |
+
# Try Qwen first, fallback to nemotron
|
| 603 |
+
models_to_try = [
|
| 604 |
+
"qwen/qwen2.5-vl-72b-instruct:free",
|
| 605 |
+
"qwen/qwen2-vl-7b-instruct:free",
|
| 606 |
+
"nvidia/nemotron-nano-12b-v2-vl:free",
|
| 607 |
+
]
|
| 608 |
+
|
| 609 |
+
text = ""
|
| 610 |
+
for model_name in models_to_try:
|
| 611 |
+
try:
|
| 612 |
+
client = get_client()
|
| 613 |
+
resp = client.chat.completions.create(
|
| 614 |
+
model=model_name,
|
| 615 |
+
messages=messages,
|
| 616 |
+
max_tokens=2000,
|
| 617 |
+
temperature=0.1,
|
| 618 |
+
timeout=45,
|
| 619 |
+
)
|
| 620 |
+
if resp.choices and resp.choices[0].message.content:
|
| 621 |
+
text = resp.choices[0].message.content.strip()
|
| 622 |
+
debug_log(f"VLM_PATHS ({model_name})", text[:500])
|
| 623 |
+
if text:
|
| 624 |
+
break
|
| 625 |
+
except Exception as e:
|
| 626 |
+
debug_log(f"VLM_PATHS ({model_name}) FAILED", str(e))
|
| 627 |
+
continue
|
| 628 |
+
|
| 629 |
+
# Parse PATH lines
|
| 630 |
+
paths = []
|
| 631 |
+
valid_labels = {d.get('schematic_label', d['label']) for d in details}
|
| 632 |
+
valid_labels |= {d['label'] for d in details}
|
| 633 |
+
valid_labels |= {'GND', 'GND1', 'GND2', 'Ground', 'ground'}
|
| 634 |
+
|
| 635 |
+
for line in text.split("\n"):
|
| 636 |
+
line = line.strip()
|
| 637 |
+
if not line.upper().startswith("PATH:"):
|
| 638 |
+
continue
|
| 639 |
+
path_str = line[5:].strip()
|
| 640 |
+
# Split by β or -> or --
|
| 641 |
+
parts = re.split(r'β|->|-->', path_str)
|
| 642 |
+
parts = [p.strip().strip("*_`β’ ") for p in parts]
|
| 643 |
+
parts = [p for p in parts if p]
|
| 644 |
+
|
| 645 |
+
# Validate: at least 2 nodes, all nodes recognizable
|
| 646 |
+
if len(parts) < 2:
|
| 647 |
+
continue
|
| 648 |
+
|
| 649 |
+
# Resolve schematic labels to detection labels
|
| 650 |
+
resolved = []
|
| 651 |
+
valid = True
|
| 652 |
+
for p in parts:
|
| 653 |
+
# Check if it's a known label
|
| 654 |
+
if p in valid_labels or p.upper() in {'GND', 'GROUND'}:
|
| 655 |
+
resolved.append(p)
|
| 656 |
+
else:
|
| 657 |
+
# Try fuzzy match
|
| 658 |
+
matched = None
|
| 659 |
+
for lbl in valid_labels:
|
| 660 |
+
if lbl.upper() == p.upper():
|
| 661 |
+
matched = lbl
|
| 662 |
+
break
|
| 663 |
+
if matched:
|
| 664 |
+
resolved.append(matched)
|
| 665 |
+
else:
|
| 666 |
+
debug_log("VLM_PATH_SKIP", f"Unknown node '{p}' in path: {path_str}")
|
| 667 |
+
valid = False
|
| 668 |
+
break
|
| 669 |
+
if valid and len(resolved) >= 2:
|
| 670 |
+
paths.append(resolved)
|
| 671 |
|
| 672 |
+
debug_log("VLM_PATHS_PARSED", f"{len(paths)} valid paths found")
|
| 673 |
+
return paths
|
| 674 |
+
|
| 675 |
+
def describe_connectivity(G, details=None, full_image_pil=None):
|
| 676 |
details_map = {d['label']: d for d in details} if details else {}
|
| 677 |
+
# Also map by schematic label
|
| 678 |
+
for d in (details or []):
|
| 679 |
+
sch = d.get('schematic_label', d['label'])
|
| 680 |
+
if sch != d['label']:
|
| 681 |
+
details_map[sch] = d
|
| 682 |
|
| 683 |
+
def fmt(l):
|
| 684 |
+
return fmt_comp(l, details_map)
|
| 685 |
+
|
| 686 |
+
if G.number_of_edges() == 0 and not full_image_pil:
|
| 687 |
return "No connections detected between components."
|
| 688 |
|
| 689 |
gnd_nodes = set(get_gnd_nodes(G))
|
| 690 |
|
| 691 |
+
lines = ["DIRECT WIRE CONNECTIONS (Wire-CC):", "β"*42]
|
| 692 |
+
if G.number_of_edges() == 0:
|
| 693 |
+
lines.append(" No wire connections detected by CV.")
|
| 694 |
+
else:
|
| 695 |
+
for u, v in sorted(G.edges()):
|
| 696 |
+
via = G.get_edge_data(u, v, {}).get('via', '')
|
| 697 |
+
lines.append(f" {fmt(u)} ββ {fmt(v)} [{via}]")
|
| 698 |
|
| 699 |
+
# ββ VLM Circuit Path Detection ββββββββββββββββββββββββββββββββββββββββββ
|
| 700 |
lines += ["", "β"*42,
|
| 701 |
+
"ALL CIRCUIT PATHS (traced by VLM from image)",
|
| 702 |
"β"*42]
|
| 703 |
|
| 704 |
+
vlm_paths = []
|
| 705 |
+
if full_image_pil is not None:
|
| 706 |
+
vlm_paths = get_circuit_paths_with_vlm(full_image_pil, details or [])
|
|
|
|
| 707 |
|
| 708 |
+
if not vlm_paths:
|
| 709 |
+
lines.append("\n VLM could not detect paths β falling back to graph traversal.\n")
|
| 710 |
+
# Fallback to graph-based paths
|
| 711 |
+
path_groups = find_all_circuit_paths(G, details_map)
|
| 712 |
+
if not path_groups:
|
| 713 |
+
lines.append(" No paths found.")
|
| 714 |
+
else:
|
| 715 |
+
total_shown = 0
|
| 716 |
+
for src_fmt, paths in path_groups:
|
| 717 |
+
lines.append(f"\n ββ From {src_fmt}")
|
| 718 |
+
for i, path in enumerate(paths, 1):
|
| 719 |
+
lines.append(f"\n Path {i}:")
|
| 720 |
+
lines.append(f" {fmt(path[0])}(+)")
|
| 721 |
+
for node in path[1:-1]:
|
| 722 |
+
lines.append(f" β {fmt(node)}")
|
| 723 |
+
lines.append(f" β {fmt(path[-1])}")
|
| 724 |
+
total_shown += 1
|
| 725 |
+
lines.append(f" ββ {len(paths)} path(s)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 726 |
else:
|
| 727 |
+
lines.append(f"\n Found {len(vlm_paths)} circuit path(s):\n")
|
| 728 |
+
# Group by source
|
| 729 |
+
from collections import defaultdict
|
| 730 |
+
by_source = defaultdict(list)
|
| 731 |
+
for path in vlm_paths:
|
| 732 |
+
src = path[0]
|
| 733 |
+
by_source[src].append(path)
|
| 734 |
+
|
| 735 |
+
for src, src_paths in by_source.items():
|
| 736 |
+
src_d = details_map.get(src, {})
|
| 737 |
+
src_val = src_d.get('value', '')
|
| 738 |
+
src_fmt = f"{src}({src_val})" if src_val else src
|
| 739 |
+
lines.append(f" ββ From {src_fmt} βββββββββββββββββββ")
|
| 740 |
+
for i, path in enumerate(src_paths, 1):
|
| 741 |
+
lines.append(f"\n Path {i}:")
|
| 742 |
+
# Format each node nicely
|
| 743 |
+
d0 = details_map.get(path[0], {})
|
| 744 |
+
v0 = d0.get('value', '')
|
| 745 |
+
lines.append(f" {path[0]}({v0})(+)" if v0 else f" {path[0]}(+)")
|
| 746 |
+
for node in path[1:-1]:
|
| 747 |
+
dn = details_map.get(node, {})
|
| 748 |
+
vn = dn.get('value', '')
|
| 749 |
+
lines.append(f" β {node}({vn})" if vn else f" β {node}")
|
| 750 |
+
# Last node (GND or endpoint)
|
| 751 |
+
last = path[-1]
|
| 752 |
+
dl = details_map.get(last, {})
|
| 753 |
+
vl = dl.get('value', '')
|
| 754 |
+
lines.append(f" β {last}({vl})" if vl else f" β {last}")
|
| 755 |
+
lines.append(f"\n ββ {len(src_paths)} path(s) from {src_fmt}")
|
| 756 |
+
|
| 757 |
+
# ββ Circuit sections βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 758 |
+
if G.number_of_edges() > 0:
|
| 759 |
+
lines += ["", "β"*42, "CIRCUIT SECTIONS (from Wire-CC graph):"]
|
| 760 |
+
comps = list(nx.connected_components(G))
|
| 761 |
+
if len(comps) == 1:
|
| 762 |
+
lines.append(" β
Fully connected circuit")
|
| 763 |
+
else:
|
| 764 |
+
lines.append(f" β οΈ {len(comps)} separate sections:")
|
| 765 |
+
for i, comp in enumerate(comps, 1):
|
| 766 |
+
lines.append(f" Section {i}: {', '.join(fmt(n) for n in sorted(comp))}")
|
| 767 |
+
|
| 768 |
+
lines.append("\nTOPOLOGY:")
|
| 769 |
+
degs = dict(G.degree())
|
| 770 |
+
branches = [n for n, deg in degs.items() if deg > 2 and n not in gnd_nodes]
|
| 771 |
+
if branches:
|
| 772 |
+
lines.append(" Parallel / multi-branch circuit")
|
| 773 |
+
lines.append(f" Junction nodes: {', '.join(fmt(n) for n in branches)}")
|
| 774 |
+
else:
|
| 775 |
+
types = [d.get('component', '').lower() for _, d in G.nodes(data=True)]
|
| 776 |
+
r = any('resist' in t for t in types)
|
| 777 |
+
l = any('inductor' in t for t in types)
|
| 778 |
+
c = any('capacit' in t for t in types)
|
| 779 |
+
tag = "RLC" if r and l and c else "RC" if r and c else "RL" if r and l else "series"
|
| 780 |
+
lines.append(f" {tag} circuit")
|
| 781 |
|
| 782 |
return "\n".join(lines)
|
| 783 |
+
|
| 784 |
|
| 785 |
def detect_gnd_symbols(img_np, details):
|
| 786 |
"""
|
|
|
|
| 999 |
src = d.get("source") or "default"
|
| 1000 |
sch = d.get("schematic_label", d['label'])
|
| 1001 |
report += f"{sch} [{d['label']}] ({d['component']}) = {d['value'] or 'unknown'} ({src})\n"
|
| 1002 |
+
report += "\n" + describe_connectivity(G, details=details, full_image_pil=Image.fromarray(np.array(image))) + "\n"
|
| 1003 |
return annotated, net_vis, details, summary, report, "", get_debug_text()
|
| 1004 |
except Exception as e:
|
| 1005 |
traceback.print_exc()
|