-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathband-report-from-csv.py
More file actions
179 lines (149 loc) · 4.68 KB
/
band-report-from-csv.py
File metadata and controls
179 lines (149 loc) · 4.68 KB
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
#!/usr/bin/env python3
#
# /// script
# requires-python = ">=3.12"
# dependencies = ["numpy"]
# ///
"""
band-report-from-csv.py
Generate a band report from a similarities CSV by sweeping thresholds and
recording connected components.
Expected CSV columns:
- file_a
- file_b
- weighted_score
Usage:
uv run --locked band-report-from-csv.py similarities.csv
uv run --locked band-report-from-csv.py similarities.csv --step 0.01 --csv band-report.csv
"""
from __future__ import annotations
import argparse
import csv
import logging
import sys
from pathlib import Path
from typing import Dict, List, Set, Tuple
import numpy as np
# -------------------------
# Graph utilities
# -------------------------
def build_components(
files: Set[str],
edges: Dict[Tuple[str, str], float],
threshold: float,
) -> List[Set[str]]:
graph: Dict[str, Set[str]] = {f: set() for f in files}
for (a, b), score in edges.items():
if score >= threshold:
graph[a].add(b)
graph[b].add(a)
visited: Set[str] = set()
components: List[Set[str]] = []
for node in graph:
if node in visited:
continue
stack = [node]
comp = set()
while stack:
cur = stack.pop()
if cur in visited:
continue
visited.add(cur)
comp.add(cur)
stack.extend(graph[cur] - visited)
components.append(comp)
return components
# -------------------------
# Main
# -------------------------
def main() -> None:
parser = argparse.ArgumentParser(
description="Produce a band report (threshold → components) from similarities CSV"
)
parser.add_argument("csv", help="similarities.csv input file")
parser.add_argument(
"--step",
type=float,
default=0.01,
help="Threshold step size (default: 0.01)",
)
parser.add_argument(
"--csv-out",
help="Optional CSV output path for band report",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Print what would be done and exit",
)
parser.add_argument(
"--verbose",
action="store_true",
help="Verbose logging",
)
args = parser.parse_args()
logging.basicConfig(
level=logging.DEBUG if args.verbose else logging.INFO,
format="%(levelname)s: %(message)s",
stream=sys.stderr,
)
csv_path = Path(args.csv)
if not csv_path.exists():
sys.exit(f"CSV file not found: {csv_path}")
if args.dry_run:
print(f"Dry run: Would process {csv_path} with step {args.step}")
if args.csv_out:
print(f"Dry run: Would write output to {args.csv_out}")
return
edges: Dict[Tuple[str, str], float] = {}
files: Set[str] = set()
scores: List[float] = []
with csv_path.open("r", encoding="utf-8") as f:
reader = csv.DictReader(f)
required = {"file_a", "file_b", "weighted_score"}
if not required.issubset(reader.fieldnames or []):
sys.exit(f"CSV must contain columns: {', '.join(required)}")
for row in reader:
a = row["file_a"]
b = row["file_b"]
s = float(row["weighted_score"])
files.update([a, b])
edges[(a, b)] = s
scores.append(s)
lo, hi = min(scores), max(scores)
thresholds = np.arange(round(lo, 2), round(hi + args.step, 2), args.step)
report_rows: List[dict] = []
print("\nBand report (threshold → components):\n")
for t in thresholds[::-1]: # high → low
comps = build_components(files, edges, float(t))
sizes = sorted((len(c) for c in comps), reverse=True)
row = {
"threshold": round(float(t), 2),
"components": len(comps),
"largest_component": sizes[0] if sizes else 0,
"component_sizes": " ".join(map(str, sizes)),
}
report_rows.append(row)
print(
f"t≥{row['threshold']:.2f} | "
f"components={row['components']} | "
f"largest={row['largest_component']} | "
f"sizes=[{row['component_sizes']}]"
)
if args.csv_out:
out = Path(args.csv_out)
with out.open("w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(
f,
fieldnames=[
"threshold",
"components",
"largest_component",
"component_sizes",
],
)
writer.writeheader()
writer.writerows(report_rows)
logging.info(f"Band report CSV written to {out}")
if __name__ == "__main__":
main()