Wizzas commited on
Commit
e4188c6
·
verified ·
1 Parent(s): 4212a6e

Inspection results name the closest normal reference photos (explanation only)

Browse files
backend/references.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Nearest normal reference photos: an explanation aid, never part of the verdict.
2
+
3
+ Each product has a small set of diverse normal training photos, each summarised by one descriptor (the unit-length mean
4
+ of its foreground patch features from the same encoder as the detector). For a new photo the same descriptor is
5
+ compared with them and the closest few are named in the result, so a person can look at a similar normal photo next
6
+ to the flagged one. The detector's score, threshold and verdict do not depend on any of this.
7
+ """
8
+
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+ import torch
13
+ import torch.nn.functional as F
14
+
15
+
16
+ def descriptor(tokens, mask):
17
+ """Unit-length mean of the foreground patch features (all patches if the mask is empty)."""
18
+ features = F.normalize(tokens.float(), dim=-1)
19
+ keep = np.asarray(mask, dtype=bool)
20
+ if keep.any():
21
+ features = features[torch.as_tensor(keep, device=features.device)]
22
+ return F.normalize(features.mean(0), dim=0)
23
+
24
+
25
+ class ReferenceIndex:
26
+ """Loads references/<product>.npz lazily; a missing file simply means there are no references to show."""
27
+
28
+ def __init__(self, directory):
29
+ self.directory = Path(directory)
30
+ self.loaded = {}
31
+
32
+ def load(self, category, device):
33
+ key = (category, str(device))
34
+ if key not in self.loaded:
35
+ path = self.directory / f"{category}.npz"
36
+ if not path.exists():
37
+ self.loaded[key] = None
38
+ else:
39
+ with np.load(path, allow_pickle=False) as saved:
40
+ ids = [str(i) for i in saved["ids"]]
41
+ vectors = torch.from_numpy(saved["descriptors"].astype("float32"))
42
+ self.loaded[key] = (ids, F.normalize(vectors, dim=-1).to(device))
43
+ return self.loaded[key]
44
+
45
+ def nearest(self, category, tokens, mask, k=3):
46
+ found = self.load(category, tokens.device)
47
+ if found is None:
48
+ return []
49
+ ids, vectors = found
50
+ similarity = vectors @ descriptor(tokens, mask)
51
+ top = similarity.topk(min(k, len(ids)))
52
+ return [{"id": ids[int(i)], "similarity": round(float(s), 4)} for s, i in zip(top.values, top.indices)]
deployment/space/app.py CHANGED
@@ -28,6 +28,7 @@ from backend.config import CATEGORIES, Settings
28
  from backend.highres import HighResolutionEncoder, PROFILES, foreground_mask, profile_card, score_tokens, restore_map
29
  from backend.vision import sha256, display_map
30
  from backend.storage import now
 
31
  from backend.inspection_routes import mount_inspection_experience, INSPECTION_UX_PATHS
32
  from deployment.space.sessions import SessionRepository, identity, namespace, NAMESPACE, STAFF_TOKEN, WORKSPACE, artifact_workspace, authorize_artifact, capability, remember_staff, stored_staff
33
 
@@ -55,6 +56,8 @@ for category, card in CARDS.items():
55
  assert sha256(file) == card['bank_sha256'], f'Invalid bank checksum: {category}'
56
  with np.load(file, allow_pickle=False) as saved:
57
  BANKS[category] = F.normalize(torch.from_numpy(saved['patches'].astype('float32')), dim=-1).to(DEVICE)
 
 
58
 
59
 
60
  @spaces.GPU(duration=20)
@@ -68,7 +71,8 @@ def compute(rgb: np.ndarray, category: str) -> dict:
68
  raw, score = score_tokens(tokens, BANKS[category], mask)
69
  if DEVICE == 'cuda':
70
  torch.cuda.synchronize()
71
- return {'raw': raw, 'geometry': geometry, 'score': score,
 
72
  'foreground_fraction': float(mask.mean()), 'device': DEVICE,
73
  'gpu_name': torch.cuda.get_device_name() if DEVICE == 'cuda' else None,
74
  'peak_gpu_mb': round(torch.cuda.max_memory_allocated()/1024**2, 2) if DEVICE == 'cuda' else None,
@@ -198,6 +202,7 @@ def inspect_one(image_b64, filename, category, batch, request_id=''):
198
  image.save(ARTIFACTS/f'{identifier}.jpg', quality=92)
199
  heatmap.save(ARTIFACTS/f'{identifier}_heatmap.jpg', quality=92)
200
  record = {key:output[key] for key in ('inference_ms','device','gpu_name','peak_gpu_mb','foreground_fraction')}
 
201
  record.update(id=identifier,created_at=now(),category=category,batch=batch.strip(),filename=Path(filename).name[:160],
202
  verdict=verdict,score=score,threshold=threshold,uncertainty_margin=margin,defect_category=None,
203
  request_fingerprint=fingerprint(content,category,batch),
 
28
  from backend.highres import HighResolutionEncoder, PROFILES, foreground_mask, profile_card, score_tokens, restore_map
29
  from backend.vision import sha256, display_map
30
  from backend.storage import now
31
+ from backend.references import ReferenceIndex
32
  from backend.inspection_routes import mount_inspection_experience, INSPECTION_UX_PATHS
33
  from deployment.space.sessions import SessionRepository, identity, namespace, NAMESPACE, STAFF_TOKEN, WORKSPACE, artifact_workspace, authorize_artifact, capability, remember_staff, stored_staff
34
 
 
56
  assert sha256(file) == card['bank_sha256'], f'Invalid bank checksum: {category}'
57
  with np.load(file, allow_pickle=False) as saved:
58
  BANKS[category] = F.normalize(torch.from_numpy(saved['patches'].astype('float32')), dim=-1).to(DEVICE)
59
+ # Nearest normal reference photos (an explanation aid only; the score and verdict never use it).
60
+ REFERENCES = ReferenceIndex(BANK_DIRECTORY/'references') if PROFILE == 'dinov2_tuned_v1' else None
61
 
62
 
63
  @spaces.GPU(duration=20)
 
71
  raw, score = score_tokens(tokens, BANKS[category], mask)
72
  if DEVICE == 'cuda':
73
  torch.cuda.synchronize()
74
+ references = REFERENCES.nearest(category, tokens, mask) if REFERENCES is not None else []
75
+ return {'raw': raw, 'geometry': geometry, 'score': score, 'references': references,
76
  'foreground_fraction': float(mask.mean()), 'device': DEVICE,
77
  'gpu_name': torch.cuda.get_device_name() if DEVICE == 'cuda' else None,
78
  'peak_gpu_mb': round(torch.cuda.max_memory_allocated()/1024**2, 2) if DEVICE == 'cuda' else None,
 
202
  image.save(ARTIFACTS/f'{identifier}.jpg', quality=92)
203
  heatmap.save(ARTIFACTS/f'{identifier}_heatmap.jpg', quality=92)
204
  record = {key:output[key] for key in ('inference_ms','device','gpu_name','peak_gpu_mb','foreground_fraction')}
205
+ if output.get('references'):record['references']=output['references']
206
  record.update(id=identifier,created_at=now(),category=category,batch=batch.strip(),filename=Path(filename).name[:160],
207
  verdict=verdict,score=score,threshold=threshold,uncertainty_margin=margin,defect_category=None,
208
  request_fingerprint=fingerprint(content,category,batch),
models/highres_tuned/references/candle.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:efb06b87448709cd17bcedf5ac9db4faf8a69c8d67b76ebc2b10f9b9f189903e
3
+ size 34596
models/highres_tuned/references/capsules.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fab85b65aea0f785e36e323eb7ec7b2d969cc9d86503e6315ebbab6eb5cfdeda
3
+ size 34726
models/highres_tuned/references/cashew.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c92e2018d2df154f696e8fc13a1fc9cd83f3d72728e73f87935dc21147ccb7f9
3
+ size 34610
models/highres_tuned/references/chewinggum.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9032a8e6d5ed97aae83fa939ba0b81e2042bc278e28ef50d51adcfdf5a698457
3
+ size 34610
models/highres_tuned/references/fryum.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ab35a053a3fad2e34663472e2a48e13d6c312718f5171304c21d41750281cab0
3
+ size 34765
models/highres_tuned/references/macaroni1.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b74521015b395ca553be768182dd59645edad91416dfddc7a93283bf285cb119
3
+ size 34666
models/highres_tuned/references/macaroni2.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f5595744f0039c61b4387f5f71b862a8ae6c293be21273577c9313cb5b120937
3
+ size 34625
models/highres_tuned/references/pcb1.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b3e3743d8ea8198a4d101a185fea04e3981057af70fc89d4a8d3e09ff8adc38c
3
+ size 34686
models/highres_tuned/references/pcb2.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:972dbcb88395df00d05a503b2c1aee7fb73090e73555e365523303b8bf498bcd
3
+ size 34540
models/highres_tuned/references/pcb3.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5893df85fa8798a83cba1881f796aa3522d48954081e0d1059b2960eb2bda63f
3
+ size 34629
models/highres_tuned/references/pcb4.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:77c24cbf18ff09a08751412f3a4046dbb3ae15ee0350984462e792e910191c11
3
+ size 34632
models/highres_tuned/references/pipe_fryum.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8c03110665ce39bc7b08f0786b6f2400ca2b9c30cc8eac56894a39854f23185e
3
+ size 34703