Download runtime/bankshot.py from racklab/BankShot-Search: direct link, hf CLI and curl.
- Browser
- Download file 18.5 kB
-
https://huggingface.co/racklab/BankShot-Search/resolve/main/runtime/bankshot.py
- Command line
-
hf download hf://racklab/BankShot-Search/runtime/bankshot.py
-
curl -L -o bankshot.py https://huggingface.co/racklab/BankShot-Search/resolve/main/runtime/bankshot.py
18.5 kB
| """Experimental local BankShot workflow for the frozen industry catalog.""" | |
| import argparse | |
| from collections import defaultdict | |
| from hashlib import sha256 | |
| import json | |
| from pathlib import Path | |
| import re | |
| import sys | |
| from time import perf_counter_ns | |
| from urllib.parse import urlsplit | |
| import numpy as np | |
| from bankshot_device import prepare_ncs1 | |
| from bankshot_rank import ( | |
| ExpansionIndex, ProsePolicy, fuse, glossary_pattern, policy_features, | |
| scoped_lexical, section_features, source_id, | |
| ) | |
| from bankshot_tokens import InputTokens | |
| from local_graphs import Graphs, digest | |
| DOMAINS = ("dealership", "manufacturing", "store_security") | |
| RANKINGS = ("incumbent", "scoped", "fusion", "lexical", "semantic") | |
| IDENTIFIERS = { | |
| "dealership": re.compile(r"\b\d{2}[a-z]\d{6}\b", re.I), | |
| "manufacturing": re.compile(r"\b1910\.\d{1,4}\b"), | |
| } | |
| WORDS = re.compile(r"[a-z0-9]+") | |
| def normalize(text): | |
| return " ".join(WORDS.findall(text.casefold())) | |
| def ranking_profile(dealership_ranker, guide_cap, expansions, residuals, glossary, spread): | |
| components = { | |
| "glossary": glossary, "spread": spread, "guide_cap": guide_cap, | |
| "vehicle": digest(dealership_ranker / "model.onnx") if dealership_ranker else None, | |
| "expansions": digest(expansions) if expansions else None, | |
| "section_heads": {}, | |
| } | |
| if residuals is not None: | |
| for name in ("manufacturing", "store_security"): | |
| graph = residuals / name / "model.onnx" | |
| if graph.is_file(): | |
| components["section_heads"][name] = digest(graph) | |
| return sha256(json.dumps(components, sort_keys=True).encode()).hexdigest() | |
| class Catalog: | |
| def __init__(self, rows, revision): | |
| self.rows = rows | |
| self.revision = revision | |
| self.domains = {d: [] for d in DOMAINS} | |
| self.identifiers = {} | |
| self.guides = {} | |
| self.vehicles = defaultdict(list) | |
| for index, row in enumerate(rows): | |
| domain = row["domain"] | |
| self.domains[domain].append(index) | |
| self.identifiers[row["id"].split("/", 1)[1].casefold()] = index | |
| if domain == "store_security": | |
| self.guides.setdefault(row["page"], index) | |
| for make, model, year in row.get("affected_vehicles", ()): | |
| vehicle = (str(year), normalize(make), normalize(model)) | |
| self.vehicles[vehicle].append(index) | |
| self.guide_roots = {page.split("/", 1)[0] for page in self.guides} | |
| def guide_reference(self, text): | |
| path = text.strip().strip("`") | |
| if path.startswith(("https://", "http://")): | |
| try: | |
| url = urlsplit(path) | |
| except ValueError: | |
| return None | |
| if url.netloc != "docs.frigate.video": | |
| return None | |
| path = url.path | |
| path = path.strip("/") | |
| segment = path.split("/", 1) | |
| if (len(segment) == 2 and segment[0] in self.guide_roots | |
| and re.fullmatch(r"[a-z0-9_-]+(?:/[a-z0-9_-]+)+", path)): | |
| return path | |
| return None | |
| def result(self, status, path, indices=()): | |
| selected = {} | |
| for index in indices: | |
| row = self.rows[index] | |
| identifier = source_id(row) | |
| url = "https://docs.frigate.video/" + identifier + "/" if "page" in row else row["source"] | |
| selected.setdefault(identifier, { | |
| "id": identifier, "section_id": row["id"], | |
| "title": row.get("page_title", row["title"]), "url": url, | |
| }) | |
| if len(selected) == 10: | |
| break | |
| return {"status": status, "path": path, "catalog_revision": self.revision, | |
| "hits": list(selected.values())} | |
| class Search: | |
| def __init__(self, catalog, rank): | |
| self.catalog = catalog | |
| self.rank = rank | |
| self.vehicle_ranker = None | |
| self.policy = None | |
| self.standard_codes = {} | |
| def search(self, text, domain, vehicle=None, *, trace=None): | |
| c = self.catalog | |
| if domain not in DOMAINS: | |
| return c.result("unsupported", "catalog") | |
| if vehicle is not None: | |
| year, make, model = map(str, vehicle) | |
| if domain != "dealership" or not re.fullmatch(r"\d{4}", year) or not all(map(normalize, (make, model))): | |
| return c.result("needs_details", "vehicle") | |
| scope = c.vehicles.get((year, normalize(make), normalize(model)), []) | |
| else: | |
| scope = c.domains[domain] | |
| if domain == "store_security": | |
| direct = c.guide_reference(text) | |
| if direct is not None: | |
| index = c.guides.get(direct) | |
| if index is None: | |
| return c.result("no_match", "guide_reference") | |
| return c.result("found", "guide_reference", [index]) | |
| if domain == "manufacturing": | |
| chosen = self.standard_codes.get(normalize(text)) | |
| if chosen is not None and chosen in c.identifiers: | |
| return c.result("found", "standard_name", [c.identifiers[chosen]]) | |
| pattern = IDENTIFIERS.get(domain) | |
| ids = set(pattern.findall(text.casefold())) if pattern else set() | |
| if len(ids) > 1: | |
| return c.result("ambiguous", "identifier") | |
| if ids: | |
| idx = c.identifiers.get(next(iter(ids))) | |
| return c.result("found", "identifier", [idx]) if idx in scope else c.result("no_match", "identifier") | |
| if not scope: | |
| return c.result("no_match", "vehicle" if vehicle is not None else "catalog") | |
| if not normalize(text): | |
| if vehicle is not None: | |
| return c.result("found", "vehicle", scope) | |
| return c.result("needs_details", "catalog") | |
| if vehicle is not None and self.vehicle_ranker is not None: | |
| if self.policy is None and trace is None: | |
| return c.result("found", "vehicle_residual", self.vehicle_ranker(text, vehicle)) | |
| context = {} if trace is None else trace | |
| ids = self.vehicle_ranker(text, vehicle, trace=context) | |
| path = "vehicle_residual" | |
| elif trace is not None or self.policy is not None: | |
| context = {} if trace is None else trace | |
| path, ids = self.rank(text, domain, scope, vehicle is not None, trace=context) | |
| else: | |
| path, ids = self.rank(text, domain, scope, vehicle is not None) | |
| return c.result("found" if len(ids) else "no_match", path, ids) | |
| status = "found" if len(ids) else "no_match" | |
| if status == "found" and self.policy is not None: | |
| status = self.policy(domain, *context["policy_features"]) | |
| return c.result(status, path, ids if status == "found" else ()) | |
| class Hybrid: | |
| def __init__(self, root, catalog, backend, *, glossary, spread, ranking, guide_cap, expansions): | |
| context = root / "context-v2" | |
| section = context / "section-reranker" | |
| adapted = root / "owner-reports-training-v1" | |
| sys.path[:0] = [str(context), str(section), str(adapted), str(root)] | |
| from pair_features import COUNT, PairFeatures, words | |
| from sparse_index import SparseIndex | |
| from vehicle_prefix import VehiclePrefix | |
| self.matches = words | |
| self.catalog = catalog | |
| self.sources = tuple(map(source_id, catalog.rows)) | |
| self.spread = spread | |
| self.ranking = ranking | |
| self.residuals = {} | |
| self.guide_cap = guide_cap | |
| self.expansions = ExpansionIndex(expansions, catalog) if expansions is not None else None | |
| self.definitions = {} | |
| self.standard_codes = {} | |
| if glossary: | |
| source = root / "osha-letters-v1/glossary.json" | |
| entries = json.loads(source.read_text(encoding="utf-8-sig"))["entries"] | |
| self.definitions = {term.casefold(): v["definition"] for term, v in entries.items()} | |
| self.standard_codes = {term.casefold(): v["standard"] for term, v in entries.items()} | |
| # OSHA's general-industry index links lockout/tagout to 1910.147. | |
| self.standard_codes.update({"loto": "1910.147", "lockout tagout": "1910.147"}) | |
| self.glossary = glossary_pattern(self.definitions) if ranking != "incumbent" else None | |
| self.n_pairs = COUNT | |
| self.features = PairFeatures(catalog.rows) | |
| self.selector = VehiclePrefix(catalog.rows) | |
| self.tokens = InputTokens(context) | |
| self.full = SparseIndex("full", range(len(catalog.rows))) | |
| self.store = SparseIndex("support", catalog.domains["store_security"]) | |
| self.graphs = Graphs(backend, prepare_ncs1) | |
| locations = { | |
| "scorer": context / "student-token-sum", | |
| "general": section, | |
| "dealership": adapted, | |
| } | |
| self.models = {k: self.graphs.load(p / "model.onnx", p / "ir/model", packed=True) | |
| for k, p in locations.items() | |
| if ranking in ("incumbent", "scoped") or (ranking != "lexical" and k == "scorer")} | |
| def lexical(self, text, domain, scope): | |
| if self.ranking != "incumbent": | |
| index = self.store if domain == "store_security" else self.full | |
| return scoped_lexical(index, text, scope, expansions=self.expansions) | |
| if domain == "store_security": | |
| return self.store.rank(text) | |
| permitted = set(scope) | |
| return [i for i in self.full.rank(text) if i in permitted] | |
| def __call__(self, text, domain, scope, explicit_vehicle, trace=None): | |
| if domain == "manufacturing" and self.glossary is not None: | |
| text = self.glossary.sub(lambda m: self.definitions[m.group().casefold()], text) | |
| if not self.matches(text): | |
| return "hybrid", [] | |
| scope = np.asarray(scope, dtype=np.int64) | |
| started = perf_counter_ns() | |
| if explicit_vehicle and self.ranking == "incumbent": | |
| indices = self.full.conditioned(text, scope) | |
| if trace is not None: | |
| trace.update(lexical=indices, semantic=[], candidates=indices, reranked=indices) | |
| return "vehicle_lexical", indices | |
| lexical = [] if self.ranking == "semantic" else self.lexical(text, domain, scope) | |
| lexical_ms = (perf_counter_ns() - started) / 1e6 | |
| if self.ranking == "lexical": | |
| if trace is not None: | |
| trace.update(lexical=lexical, semantic=[], candidates=lexical, reranked=lexical, | |
| stage_ms={"lexical": lexical_ms}) | |
| return "scoped_lexical", lexical | |
| started = perf_counter_ns() | |
| dense = self.models["scorer"](self.tokens.features(text)).reshape(-1) | |
| if dense.shape != (len(self.full.docs),) or not np.isfinite(dense).all() or np.ptp(dense) < 1e-5: | |
| raise RuntimeError("Invalid semantic scorer output") | |
| dense_order = scope[np.lexsort((scope, -dense[scope]))] | |
| if domain == "store_security" and self.spread: | |
| guides = {} | |
| for index in dense_order: | |
| guides.setdefault(self.catalog.rows[index]["page"], index) | |
| dense_order = list(dict.fromkeys(list(guides.values()) + dense_order[:100].tolist())) | |
| semantic = dense_order[:100] | |
| semantic_ms = (perf_counter_ns() - started) / 1e6 | |
| if self.ranking == "semantic": | |
| if trace is not None: | |
| trace.update(lexical=[], semantic=list(map(int, semantic)), | |
| candidates=list(map(int, semantic)), reranked=list(map(int, semantic)), | |
| stage_ms={"scorer": semantic_ms}) | |
| return "semantic", semantic | |
| started = perf_counter_ns() | |
| shortlist = None | |
| if domain == "store_security" and self.guide_cap is not None: | |
| shortlist = set(fuse(((lexical, 1.0), (semantic, 0.8)), self.n_pairs, | |
| sources=self.sources, per_source=self.guide_cap)) | |
| matrix, candidates = self.features.from_candidates(text, lexical, semantic, dense, allowed=shortlist) | |
| valid = candidates >= 0 | |
| lane = "dealership" if domain == "dealership" and self.selector.choose(text) == "adapted" else "general" | |
| if self.ranking == "fusion": | |
| scores = matrix[:, 0] | |
| lane = "fusion" | |
| elif domain in self.residuals: | |
| fitted = section_features(self, text, matrix, candidates) | |
| scores = self.residuals[domain]({"pairs": np.ascontiguousarray(fitted.T[None, :, None, :])}).reshape(-1) | |
| lane = "section_residual" | |
| else: | |
| scores = self.models[lane]({"pairs": matrix.T[None, :, None, :]}).reshape(-1) | |
| if scores.shape != (self.n_pairs,) or not np.isfinite(scores).all(): | |
| raise RuntimeError("Invalid reranker output") | |
| found = candidates[valid] | |
| order = found[np.lexsort((found, -scores[valid]))] | |
| if trace is not None: | |
| trace.update(lexical=lexical, semantic=list(map(int, semantic)), candidates=found.tolist(), | |
| reranked=order.tolist(), | |
| stage_ms={"lexical": lexical_ms, "scorer": semantic_ms, | |
| "pair_features_and_rank": (perf_counter_ns() - started) / 1e6}) | |
| if self.ranking != "incumbent": | |
| trace["policy_features"] = policy_features(matrix, candidates, order, scores, self.sources) | |
| if trace.get("capture_pairs") is True: | |
| trace.update(matrix=matrix, candidate_ids=candidates, ranked_text=text) | |
| return lane, order | |
| def open_search(root, backend, *, glossary=True, spread=False, dealership_ranker=None, | |
| ranking="scoped", guide_cap=None, expansions=None, policy=None, residuals=None): | |
| if ranking not in RANKINGS or (guide_cap is not None and not 1 <= guide_cap <= 10): | |
| raise ValueError("Invalid ranking mode or guide cap") | |
| if ranking == "lexical" and dealership_ranker is not None: | |
| raise ValueError("A lexical-only control cannot load the learned vehicle ranker") | |
| if policy is not None and ranking not in ("scoped", "fusion"): | |
| raise ValueError("A prose policy requires scoped reranking or fusion") | |
| path = root / "corpus.jsonl" | |
| marker = json.loads((root / "owner-reports-training-v1/freeze.json").read_text(encoding="utf-8")) | |
| revision = digest(path) | |
| if revision != marker["catalog_sha256"]: | |
| raise ValueError("Catalog digest mismatch") | |
| rows = list(map(json.loads, path.read_bytes().splitlines())) | |
| if len(rows) != 10_000: | |
| raise ValueError("Expected the frozen 10,000-document catalog") | |
| catalog = Catalog(rows, revision) | |
| workflow = Search(catalog, Hybrid(root, catalog, backend, glossary=glossary, spread=spread, | |
| ranking=ranking, guide_cap=guide_cap, expansions=expansions)) | |
| workflow.profile_sha256 = ranking_profile(dealership_ranker, guide_cap, expansions, residuals, glossary, spread) | |
| workflow.standard_codes = workflow.rank.standard_codes | |
| if policy is not None: | |
| workflow.policy = ProsePolicy(policy, revision, ranking, backend, workflow.profile_sha256) | |
| if dealership_ranker is not None: | |
| from bankshot_vehicle import scoped_ranker | |
| workflow.vehicle_ranker = scoped_ranker(workflow, dealership_ranker, backend) | |
| if residuals is not None: | |
| if ranking != "scoped": | |
| raise ValueError("Section residuals require scoped ranking") | |
| for domain in ("manufacturing", "store_security"): | |
| folder = residuals / domain | |
| if not folder.is_dir(): | |
| continue | |
| trained = json.loads((folder / "training.json").read_bytes()) | |
| model = folder / "model.onnx" | |
| if (trained["catalog_sha256"] != revision or not trained["eligible"] | |
| or trained["model_sha256"] != digest(model)): | |
| raise ValueError("Section residual differs from the selected development model") | |
| ir = folder / "ir/model" | |
| if backend == "ncs1": | |
| build = json.loads((folder / "ir/build.json").read_bytes()) | |
| if (build["onnx_sha256"] != digest(model) or build["bin_sha256"] != digest(ir.with_suffix(".bin")) | |
| or build["xml_sha256"] != digest(ir.with_suffix(".xml"))): | |
| raise ValueError("Section residual IR digest mismatch") | |
| workflow.rank.residuals[domain] = workflow.rank.graphs.load(model, ir, packed=True) | |
| return workflow | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("root", type=Path, help="Frozen public-corpus-v1 directory") | |
| parser.add_argument("domain", choices=DOMAINS) | |
| parser.add_argument("text") | |
| parser.add_argument("--vehicle", nargs=3, metavar=("YEAR", "MAKE", "MODEL")) | |
| parser.add_argument("--backend", required=True, choices=("cpu", "ncs1")) | |
| parser.add_argument("--dealership-ranker", type=Path, help="Optional experimental exact-vehicle reranker") | |
| parser.add_argument("--ranking", choices=RANKINGS, default="scoped") | |
| parser.add_argument("--guide-cap", type=int, help="Limit repeated guide sections in the candidate shortlist") | |
| parser.add_argument("--expansions", type=Path, help="Catalog-pinned index of development-only terms") | |
| parser.add_argument("--policy", type=Path, help="Catalog-pinned prose abstention thresholds") | |
| parser.add_argument("--residuals", type=Path, help="Directory of selected section residuals") | |
| args = parser.parse_args() | |
| workflow = open_search(args.root, args.backend, dealership_ranker=args.dealership_ranker, | |
| ranking=args.ranking, guide_cap=args.guide_cap, expansions=args.expansions, | |
| policy=args.policy, residuals=args.residuals) | |
| start = perf_counter_ns() | |
| result = workflow.search(args.text, args.domain, args.vehicle) | |
| result.update(workflow.rank.graphs.identity) | |
| result["request_ms"] = (perf_counter_ns() - start) / 1e6 | |
| print(json.dumps(result, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |