Wizzas commited on
Commit
3784513
·
verified ·
1 Parent(s): 84df9af

DefectRAG phase 2: incremental real-model application migration

Browse files
README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- title: DefectRAG - Phase 1 compatibility test
3
  emoji: 🔬
4
  colorFrom: purple
5
  colorTo: gray
@@ -9,28 +9,19 @@ python_version: "3.12.12"
9
  app_file: app.py
10
  license: mit
11
  pinned: false
12
- short_description: Existing React UI plus one genuine DINOv2 ZeroGPU inspection
13
  ---
14
 
15
- # Phase 1 only — not the production DefectRAG migration
16
 
17
- This isolated proof preserves the existing React dashboard. Only one public VisA
18
- PCB1 fixture is accepted for real DINOv2 scoring and heatmap generation.
19
- Use **Image inspection**, choose **PCB 1**, select the **PCB 1 anomalous sample**,
20
- then **Run inspection**. Alternatively upload the same supplied JPEG file.
 
21
 
22
- No arbitrary private images are accepted. History here is temporary test data.
23
- RAG/batch execution and cloud staff collaboration are not migrated or enabled.
24
- The normal local application and its configured Supabase workspace remain intact.
25
- Some local-runtime labels remain historical UI text; this test runs in the Space.
26
 
27
- The test uses frozen DINOv2 ViT-S/14, its existing normal-reference bank and
28
- unchanged operational threshold. No training or new accuracy evaluation occurs.
29
- The Space requires configured ZeroGPU hardware; a CPU-only run is not proof of
30
- ZeroGPU compatibility. Inspect the returned phase1 and device metadata.
31
-
32
- VisA sample: Amazon Science, CC BY 4.0; Yang Zou, Jongheon Jeong, Latha Pemula,
33
- Dongqing Zhang and Onkar Dabeer, SPot-the-Difference, ECCV 2022.
34
- https://github.com/amazon-science/spot-diff
35
- DINOv2: Meta, Apache-2.0. https://huggingface.co/facebook/dinov2-small
36
- See docs/THIRD_PARTY_NOTICES.md and the bundled model license.
 
1
  ---
2
+ title: DefectRAG
3
  emoji: 🔬
4
  colorFrom: purple
5
  colorTo: gray
 
9
  app_file: app.py
10
  license: mit
11
  pinned: false
12
+ short_description: Live React dashboard and DINOv2 inspection on ZeroGPU
13
  ---
14
 
15
+ # DefectRAG — migration phase 2
16
 
17
+ Existing React UI, real frozen DINOv2 inspection across all 12 VisA categories,
18
+ original normal-reference banks, calibration and heatmaps. No training rerun.
19
+ Anonymous browser history is isolated and temporary. Sign in to the configured
20
+ staff workspace for durable shared records when available. Do not treat anomaly
21
+ scores as probabilities or diagnoses. The operator selects the product category.
22
 
23
+ Gradio client requests use bounded GPU leases. Quotas and cold starts apply.
24
+ Local application and static showcase are preserved separately.
 
 
25
 
26
+ VisA: Amazon Science, CC BY 4.0, Zou et al., ECCV 2022.
27
+ DINOv2: Meta, Apache-2.0. See docs/THIRD_PARTY_NOTICES.md.
 
 
 
 
 
 
 
 
app.py CHANGED
@@ -1,6 +1,7 @@
1
- import os
2
- from pathlib import Path
3
- os.environ['DEFECTRAG_PHASE1_UI']=str(Path(__file__).parent/'frontend/dist')
4
- os.environ['GRADIO_ANALYTICS_ENABLED']='False'
5
- from deployment.zerogpu_phase1.app import server
6
- server.launch(server_name='0.0.0.0',server_port=7860,show_error=True)
 
 
1
+ import os
2
+ from pathlib import Path
3
+ os.environ['DEFECTRAG_SPACE_UI']=str(Path(__file__).parent/'frontend/dist')
4
+ os.environ['GRADIO_ANALYTICS_ENABLED']='False'
5
+ os.environ['DEFECTRAG_LIVE_RAG']='0'
6
+ from deployment.space.app import server
7
+ server.launch(server_name='0.0.0.0',server_port=7860,ssr_mode=False,show_error=True)
backend/main.py CHANGED
@@ -22,11 +22,11 @@ from .rag import KnowledgeIndex, EvidenceWorkflow
22
 
23
  log=logging.getLogger('defectrag')
24
 
25
- def create_app(settings=None, detector=None, workflow=None):
26
  settings=settings or Settings()
27
  settings.data.mkdir(parents=True,exist_ok=True)
28
  artifacts=settings.data/'artifacts'; artifacts.mkdir(exist_ok=True)
29
- repo=SQLiteRepository(settings.data/'inspection.sqlite3')
30
  detector=detector or create_detector(settings)
31
  if workflow is None:
32
  workflow=EvidenceWorkflow(settings,KnowledgeIndex(settings.root,settings.data/'index'))
@@ -237,4 +237,5 @@ def create_app(settings=None, detector=None, workflow=None):
237
  if dist.exists(): app.mount('/',StaticFiles(directory=dist,html=True),name='dashboard')
238
  return app
239
 
240
- app=create_app()
 
 
22
 
23
  log=logging.getLogger('defectrag')
24
 
25
+ def create_app(settings=None, detector=None, workflow=None, repository=None):
26
  settings=settings or Settings()
27
  settings.data.mkdir(parents=True,exist_ok=True)
28
  artifacts=settings.data/'artifacts'; artifacts.mkdir(exist_ok=True)
29
+ repo=repository if repository is not None else SQLiteRepository(settings.data/'inspection.sqlite3')
30
  detector=detector or create_detector(settings)
31
  if workflow is None:
32
  workflow=EvidenceWorkflow(settings,KnowledgeIndex(settings.root,settings.data/'index'))
 
237
  if dist.exists(): app.mount('/',StaticFiles(directory=dist,html=True),name='dashboard')
238
  return app
239
 
240
+ import os
241
+ app=create_app() if os.getenv('DEFECTRAG_FACTORY_ONLY')!='1' else None
deployment/space/app.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Incremental Gradio/ZeroGPU host for the existing DefectRAG React dashboard."""
2
+ import os
3
+ from pathlib import Path
4
+ ROOT = Path(__file__).resolve().parents[2]
5
+ RUNTIME = Path(os.getenv('DEFECTRAG_SPACE_RUNTIME', ROOT/'runtime/space-development'))
6
+ os.environ['DEFECTRAG_DATA'] = str(RUNTIME)
7
+ os.environ['DEFECTRAG_FACTORY_ONLY'] = '1'
8
+ os.environ['USE_TF'] = '0'
9
+ import spaces
10
+ import base64
11
+ from io import BytesIO
12
+ import importlib.metadata
13
+ import json
14
+ import platform
15
+ import re
16
+ import time
17
+ import uuid
18
+ import warnings
19
+ import numpy as np
20
+ from PIL import Image, ImageOps, UnidentifiedImageError
21
+ import torch
22
+ import torch.nn.functional as F
23
+ from gradio import Server
24
+ from fastapi import HTTPException
25
+ from fastapi.responses import FileResponse, JSONResponse
26
+ from fastapi.staticfiles import StaticFiles
27
+ from backend.config import CATEGORIES, Settings
28
+ from backend.highres import HighResolutionEncoder, foreground_mask, score_tokens, restore_map
29
+ from backend.vision import sha256, display_map
30
+ from backend.storage import now
31
+ from deployment.space.sessions import SessionRepository, identity, namespace, NAMESPACE, STAFF_TOKEN, authorize_artifact, capability
32
+
33
+ ZERO = os.getenv('SPACES_ZERO_GPU') == '1'
34
+ DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
35
+ CARDS = {category: json.loads((ROOT/f'models/highres/{category}.json').read_text()) for category in CATEGORIES}
36
+ ENCODER = HighResolutionEncoder(ROOT/'models/encoder_dinov2', device='cpu')
37
+ encoder_digest = sha256(ROOT/'models/encoder_dinov2/model.safetensors')
38
+ assert all(card['encoder_sha256'] == encoder_digest for card in CARDS.values())
39
+ if DEVICE == 'cuda':
40
+ ENCODER.model.half().to('cuda')
41
+ ENCODER.device = torch.device('cuda')
42
+ ENCODER.dtype = torch.float16
43
+ ENCODER.mean = ENCODER.mean.half().to('cuda')
44
+ ENCODER.std = ENCODER.std.half().to('cuda')
45
+ BANKS = {}
46
+ for category, card in CARDS.items():
47
+ file = ROOT/f'models/highres/{category}.npz'
48
+ assert sha256(file) == card['bank_sha256'], f'Invalid bank checksum: {category}'
49
+ with np.load(file, allow_pickle=False) as saved:
50
+ BANKS[category] = F.normalize(torch.from_numpy(saved['patches'].astype('float32')), dim=-1).to(DEVICE)
51
+
52
+
53
+ @spaces.GPU(duration=20)
54
+ @torch.inference_mode()
55
+ def compute(rgb: np.ndarray, category: str) -> dict:
56
+ start = time.perf_counter()
57
+ if DEVICE == 'cuda':
58
+ torch.cuda.reset_peak_memory_stats()
59
+ tokens, geometry = ENCODER.encode(Image.fromarray(rgb))
60
+ mask = foreground_mask(tokens, geometry['grid'])
61
+ raw, score = score_tokens(tokens, BANKS[category], mask)
62
+ if DEVICE == 'cuda':
63
+ torch.cuda.synchronize()
64
+ return {'raw': raw, 'geometry': geometry, 'score': score,
65
+ 'foreground_fraction': float(mask.mean()), 'device': DEVICE,
66
+ 'gpu_name': torch.cuda.get_device_name() if DEVICE == 'cuda' else None,
67
+ 'peak_gpu_mb': round(torch.cuda.max_memory_allocated()/1024**2, 2) if DEVICE == 'cuda' else None,
68
+ 'inference_ms': round((time.perf_counter()-start)*1000, 2)}
69
+
70
+
71
+ class MetadataDetector:
72
+ profile_name = 'dinov2_highres_v1'
73
+ def cards(self):
74
+ return list(CARDS.values())
75
+
76
+
77
+ REPO = SessionRepository(RUNTIME/'sessions')
78
+ ARTIFACTS = RUNTIME/'artifacts'
79
+ ARTIFACTS.mkdir(parents=True, exist_ok=True)
80
+ from backend.main import create_app
81
+ cpu_app = create_app(Settings(), detector=MetadataDetector(), repository=REPO)
82
+ server = Server(title='DefectRAG')
83
+
84
+
85
+ @server.middleware('http')
86
+ async def workspace_access(request, call_next):
87
+ path = request.url.path
88
+ public = path in ('/api/health', '/api/models', '/api/evaluation', '/api/benchmark/official', '/api/samples') or path.startswith('/api/samples/')
89
+ if not path.startswith('/api/') or public:
90
+ return await call_next(request)
91
+ try:
92
+ match = re.fullmatch(r'/api/inspections/([a-f0-9]{32})/(image|heatmap|report)', path)
93
+ if match and 'access' in request.query_params:
94
+ owner = authorize_artifact(request.query_params['access'], *match.groups())
95
+ elif path == '/api/export.csv' and 'access' in request.query_params:
96
+ owner = authorize_artifact(request.query_params['access'],'workspace','csv')
97
+ else:
98
+ owner = namespace(request.headers.get('X-DefectRAG-Session',''))
99
+ context = NAMESPACE.set(owner)
100
+ token = STAFF_TOKEN.set(request.headers.get('authorization','').removeprefix('Bearer '))
101
+ except ValueError as exc:
102
+ return JSONResponse({'error': {'message': str(exc)}}, status_code=401)
103
+ try:
104
+ response = await call_next(request)
105
+ response.headers['X-DefectRAG-Export'] = '/api/export.csv?access='+capability('workspace','csv')
106
+ response.headers['Cache-Control'] = 'private, no-store'
107
+ return response
108
+ finally:
109
+ STAFF_TOKEN.reset(token)
110
+ NAMESPACE.reset(context)
111
+
112
+
113
+ @server.api(name='ready', concurrency_limit=1)
114
+ def ready(message: str) -> dict:
115
+ return {'message': message, 'zero_gpu_environment': ZERO, 'python': platform.python_version(),
116
+ 'device': DEVICE, 'categories': list(CARDS), 'versions': {name: importlib.metadata.version(name)
117
+ for name in ('gradio','spaces','torch','transformers','huggingface-hub')}}
118
+
119
+
120
+ def inspect_one(image_b64, filename, category, batch):
121
+ if category not in CARDS or len(batch)>80 or len(image_b64)>14*1024*1024:
122
+ raise ValueError('Choose a supported category, image up to 10 MB and batch label up to 80 characters.')
123
+ try:
124
+ content = base64.b64decode(image_b64, validate=True)
125
+ if len(content)>10*1024*1024:
126
+ raise ValueError('Image limit is 10 MB')
127
+ with warnings.catch_warnings():
128
+ warnings.simplefilter('error', Image.DecompressionBombWarning)
129
+ with Image.open(BytesIO(content)) as opened:
130
+ if opened.format not in ('JPEG','PNG','WEBP') or opened.width*opened.height>25_000_000 or min(opened.size)<32 or max(opened.size)>4*min(opened.size):
131
+ raise ValueError('Use JPEG, PNG or WebP, 32px minimum, up to 25 MP and 4:1 aspect ratio.')
132
+ image = ImageOps.exif_transpose(opened).convert('RGB')
133
+ except (ValueError, OSError, UnidentifiedImageError, Image.DecompressionBombWarning, Image.DecompressionBombError) as exc:
134
+ raise ValueError(f'Invalid image: {exc}') from None
135
+ start = time.perf_counter()
136
+ output = compute(np.asarray(image), category)
137
+ card = CARDS[category]
138
+ threshold, margin, score = card['threshold'], card['uncertainty_margin'], output['score']
139
+ verdict = 'Uncertain' if abs(score-threshold)<=margin else 'Anomalous' if score>=threshold else 'Good'
140
+ identifier = uuid.uuid4().hex
141
+ preview = image.copy()
142
+ preview.thumbnail((1000,1000))
143
+ heatmap = display_map(restore_map(output['raw'],output['geometry'],preview.size),preview,card['heatmap_scale'])
144
+ image.thumbnail((1600,1600))
145
+ image.save(ARTIFACTS/f'{identifier}.jpg', quality=92)
146
+ heatmap.save(ARTIFACTS/f'{identifier}_heatmap.jpg', quality=92)
147
+ record = {key:output[key] for key in ('inference_ms','device','gpu_name','peak_gpu_mb','foreground_fraction')}
148
+ record.update(id=identifier,created_at=now(),category=category,batch=batch.strip(),filename=Path(filename).name[:160],
149
+ verdict=verdict,score=score,threshold=threshold,uncertainty_margin=margin,defect_category=None,
150
+ model_id=card['model_id'],model_sha256=card['bank_sha256'],profile='dinov2_highres_v1',calibration=card['calibration'],
151
+ total_model_ms=round((time.perf_counter()-start)*1000,2),
152
+ localization=f"{output['geometry']['grid'][0]} x {output['geometry']['grid'][1]} DINOv2 patch distances with PCA foreground heuristic; interpolated, not supervised segmentation",
153
+ scope='VisA appearance anomaly screening; operator-selected category is not verified; foreground heuristic can fail.',
154
+ deployment={'transport':'@gradio/client','zero_gpu_environment':ZERO},
155
+ image_url=f'/api/inspections/{identifier}/image',heatmap_url=f'/api/inspections/{identifier}/heatmap')
156
+ return REPO.save(record)
157
+
158
+
159
+ @server.api(name='inspect',concurrency_limit=1,concurrency_id='model-work')
160
+ def inspect(image_b64: str, filename: str, category: str, batch: str, session: str, token: str='') -> dict:
161
+ with identity(session,token):
162
+ return inspect_one(image_b64,filename,category,batch)
163
+
164
+
165
+ @server.get('/api/health')
166
+ def health():
167
+ return {'data':{'status':'ok','mode':'cloud_session_workspace','models':list(CARDS.values()),
168
+ 'encoder_configured':True,'llm_model':'generation migration in progress','zero_gpu':ZERO,
169
+ 'history':'anonymous browser history is temporary; staff workspace uses Supabase'}}
170
+
171
+
172
+ for route in cpu_app.routes:
173
+ path = getattr(route,'path','')
174
+ if path.startswith('/api/') and path not in {'/api/health','/api/inspect','/api/batch','/api/assistant'}:
175
+ server.router.routes.append(route)
176
+
177
+
178
+ @server.post('/api/{operation}')
179
+ def queued_only(operation: str):
180
+ raise HTTPException(409,'Use the dashboard Gradio queue for model execution.')
181
+
182
+
183
+ UI = Path(os.getenv('DEFECTRAG_SPACE_UI', ROOT/'development-support/space/ui-dist'))
184
+ @server.get('/')
185
+ def dashboard():
186
+ return FileResponse(UI/'index.html')
187
+ @server.get('/config.js')
188
+ def public_config():
189
+ return FileResponse(UI/'config.js')
190
+ @server.get('/logo.svg')
191
+ def logo():
192
+ return FileResponse(UI/'logo.svg')
193
+ server.mount('/assets',StaticFiles(directory=UI/'assets'),name='react-assets')
194
+
195
+ if __name__ == '__main__':
196
+ server.launch(server_name='0.0.0.0',server_port=int(os.getenv('PORT','8784')),show_error=True,ssr_mode=False)
deployment/space/probe_services.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Read public configuration/service metadata without printing credentials."""
2
+ import json
3
+ from pathlib import Path
4
+ import re
5
+ import requests
6
+ from huggingface_hub import HfApi
7
+
8
+ ROOT=Path(__file__).resolve().parents[2]
9
+ OUT=ROOT/'development-support/space'
10
+ OUT.mkdir(parents=True,exist_ok=True)
11
+ text=Path(r'C:\Users\User\Desktop\DefectRAG-v2\frontend\public\config.js').read_text()
12
+ config={key:re.search(key+r'''\s*:\s*['"]([^'"]+)''',text).group(1)
13
+ for key in ('supabaseUrl','supabasePublishableKey')}
14
+ assert config['supabaseUrl'].startswith('https://')
15
+ key=config['supabasePublishableKey']
16
+ assert key.startswith('sb_publishable_'), 'Review key type; never publish a service credential'
17
+ headers={'apikey':key}
18
+ result={'supabase_project_url':config['supabaseUrl'],'publishable_key_configured':True,'tables':{}}
19
+ for table in ('staff_members','shared_inspections','staff_notes'):
20
+ response=requests.get(config['supabaseUrl']+'/rest/v1/'+table,params={'select':'*','limit':'0'},headers=headers,timeout=20)
21
+ result['tables'][table]={'status':response.status_code}
22
+ if not response.ok:
23
+ result['tables'][table]['code']=response.json().get('code')
24
+ auth=requests.get(config['supabaseUrl']+'/auth/v1/settings',headers=headers,timeout=20)
25
+ result['auth_settings_status']=auth.status_code
26
+ api=HfApi()
27
+ model=api.model_info('Qwen/Qwen3-4B-Instruct-2507',files_metadata=True)
28
+ result['qwen_candidate']={'repo':model.id,'revision':model.sha,
29
+ 'safetensors_bytes':sum(f.size or 0 for f in model.siblings if f.rfilename.endswith('.safetensors'))}
30
+ (OUT/'service-probe.json').write_text(json.dumps(result,indent=2))
31
+ (OUT/'ui-dist/config.js').write_text('window.DEFECTRAG_PUBLIC_CONFIG='+json.dumps(config)+';')
32
+ print(json.dumps(result,indent=2))
deployment/space/publish.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Allowlisted incremental commits; no private runtime, dataset or secrets upload."""
2
+ import argparse
3
+ import hashlib
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+ from huggingface_hub import HfApi, CommitOperationAdd
8
+
9
+ ROOT = Path(__file__).resolve().parents[2]
10
+ REPO = 'Wizzas/DefectRAG'
11
+ OUT = ROOT/'development-support/space'
12
+
13
+
14
+ def main():
15
+ parser = argparse.ArgumentParser()
16
+ parser.add_argument('--phase', type=int, choices=(2,3,4,5), required=True)
17
+ args = parser.parse_args()
18
+ files = {}
19
+ for directory in ('backend','deployment/space'):
20
+ for path in (ROOT/directory).glob('*.py'):
21
+ files[path.relative_to(ROOT).as_posix()] = path
22
+ for path in (ROOT/'development-support/space/ui-dist').rglob('*'):
23
+ if path.is_file():
24
+ files['frontend/dist/'+path.relative_to(ROOT/'development-support/space/ui-dist').as_posix()] = path
25
+ for path in (ROOT/'models/highres').glob('*.npz'):
26
+ files[path.relative_to(ROOT).as_posix()] = path
27
+ if args.phase>=3:
28
+ for path in (ROOT/'models/embedding').rglob('*'):
29
+ if path.is_file() and path.suffix not in ('.py','.pyc'):
30
+ files[path.relative_to(ROOT).as_posix()] = path
31
+ for path in (ROOT/'knowledge').glob('*.md'):
32
+ files[path.relative_to(ROOT).as_posix()] = path
33
+ requirements = (ROOT/'deployment/zerogpu_phase1/requirements-space.txt').read_text(encoding='utf-8')
34
+ # The platform's unused preinstalled datasets 5 requires Hub <2. Gradio needs
35
+ # >=1.16; pin the compatible intersection rather than upgrading unrelated libs.
36
+ requirements = requirements.replace('huggingface-hub==2.2.0','huggingface-hub==1.31.0')
37
+ root_app = ("import os\nfrom pathlib import Path\n"
38
+ "os.environ['DEFECTRAG_SPACE_UI']=str(Path(__file__).parent/'frontend/dist')\n"
39
+ "os.environ['GRADIO_ANALYTICS_ENABLED']='False'\n"
40
+ f"os.environ['DEFECTRAG_LIVE_RAG']='{'1' if args.phase>=3 else '0'}'\n"
41
+ "from deployment.space.app import server\n"
42
+ "server.launch(server_name='0.0.0.0',server_port=7860,ssr_mode=False,show_error=True)\n")
43
+ readme = (ROOT/'deployment/zerogpu_phase1/SPACE_README.md').read_text(encoding='utf-8')
44
+ header = readme.split('---',2)[1].replace('DefectRAG - Phase 1 compatibility test','DefectRAG').replace('Existing React UI plus one genuine DINOv2 ZeroGPU inspection','Live React dashboard and DINOv2 inspection on ZeroGPU')
45
+ body = f'''\n# DefectRAG — migration phase {args.phase}\n
46
+ Existing React UI, real frozen DINOv2 inspection across all 12 VisA categories,
47
+ original normal-reference banks, calibration and heatmaps. No training rerun.
48
+ Anonymous browser history is isolated and temporary. Sign in to the configured
49
+ staff workspace for durable shared records when available. Do not treat anomaly
50
+ scores as probabilities or diagnoses. The operator selects the product category.
51
+
52
+ Gradio client requests use bounded GPU leases. Quotas and cold starts apply.
53
+ Local application and static showcase are preserved separately.
54
+
55
+ VisA: Amazon Science, CC BY 4.0, Zou et al., ECCV 2022.
56
+ DINOv2: Meta, Apache-2.0. See docs/THIRD_PARTY_NOTICES.md.
57
+ '''
58
+ raw = {'app.py':root_app.encode(),'requirements.txt':requirements.encode(),
59
+ 'README.md':('---'+header+'---\n'+body).encode()}
60
+ assert not any(part in ('.env','runtime','node_modules','experiments','.venv') for name in files for part in Path(name).parts)
61
+ api = HfApi()
62
+ before = api.space_info(REPO)
63
+ assert api.get_space_runtime(REPO).requested_hardware=='zero-a10g'
64
+ # Deduplicate unchanged allowlisted files between phase commits.
65
+ state_file = OUT/'published-hashes.json'
66
+ previous = json.loads(state_file.read_text()) if state_file.exists() else {}
67
+ hashes = {name:hashlib.sha256(path.read_bytes()).hexdigest() for name,path in files.items()}
68
+ hashes.update({name:hashlib.sha256(value).hexdigest() for name,value in raw.items()})
69
+ operations = [CommitOperationAdd(path_in_repo=name,path_or_fileobj=path)
70
+ for name,path in files.items() if previous.get(name)!=hashes[name]]
71
+ operations += [CommitOperationAdd(path_in_repo=name,path_or_fileobj=value)
72
+ for name,value in raw.items() if previous.get(name)!=hashes[name]]
73
+ commit = api.create_commit(repo_id=REPO,repo_type='space',operations=operations,
74
+ parent_commit=before.sha,commit_message=f'DefectRAG phase {args.phase}: incremental real-model application migration')
75
+ state_file.write_text(json.dumps(hashes,indent=2))
76
+ receipt = {'phase':args.phase,'commit':commit.oid,'parent':before.sha,'changed_files':len(operations),'manifest':hashes}
77
+ (OUT/f'publish-phase{args.phase}.json').write_text(json.dumps(receipt,indent=2))
78
+ print(json.dumps({key:value for key,value in receipt.items() if key!='manifest'}))
79
+
80
+
81
+ if __name__=='__main__':
82
+ main()
deployment/space/sessions.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Isolate anonymous browser history; grant short-lived artifact capabilities."""
2
+ import base64
3
+ from contextlib import contextmanager
4
+ from contextvars import ContextVar
5
+ import hashlib
6
+ import hmac
7
+ import os
8
+ from pathlib import Path
9
+ import re
10
+ import time
11
+ from backend.storage import SQLiteRepository
12
+
13
+ NAMESPACE = ContextVar('defectrag_namespace', default=None)
14
+ STAFF_TOKEN = ContextVar('defectrag_staff_token', default='')
15
+ SIGNING_KEY = os.environ.get('DEFECTRAG_SIGNING_KEY', '').encode() or os.urandom(32)
16
+
17
+
18
+ def namespace(session):
19
+ if not isinstance(session, str) or not re.fullmatch('[a-f0-9]{64}', session):
20
+ raise ValueError('A private browser workspace is required. Reload the dashboard.')
21
+ return hashlib.sha256(session.encode()).hexdigest()
22
+
23
+
24
+ @contextmanager
25
+ def identity(session, token=''):
26
+ marker = NAMESPACE.set(namespace(session))
27
+ staff = STAFF_TOKEN.set(token)
28
+ try:
29
+ yield
30
+ finally:
31
+ STAFF_TOKEN.reset(staff)
32
+ NAMESPACE.reset(marker)
33
+
34
+
35
+ def capability(identifier, kind):
36
+ text = f'{NAMESPACE.get()}:{identifier}:{kind}:{int(time.time())+3600}'
37
+ signature = hmac.new(SIGNING_KEY, text.encode(), 'sha256').hexdigest()
38
+ return base64.urlsafe_b64encode(f'{text}:{signature}'.encode()).decode().rstrip('=')
39
+
40
+
41
+ def authorize_artifact(access, identifier, kind):
42
+ try:
43
+ raw = base64.urlsafe_b64decode(access+'='*(-len(access)%4)).decode()
44
+ owner, actual_id, actual_kind, expires, signature = raw.split(':')
45
+ text = ':'.join((owner, actual_id, actual_kind, expires))
46
+ if (not re.fullmatch('[a-f0-9]{64}', owner) or actual_id != identifier or actual_kind != kind
47
+ or int(expires) < time.time() or not hmac.compare_digest(signature,
48
+ hmac.new(SIGNING_KEY, text.encode(), 'sha256').hexdigest())):
49
+ raise ValueError()
50
+ return owner
51
+ except (ValueError, TypeError, UnicodeError):
52
+ raise ValueError('Image or report access expired. Reopen the saved inspection.') from None
53
+
54
+
55
+ class SessionRepository:
56
+ def __init__(self, directory):
57
+ self.directory = Path(directory)
58
+
59
+ def current(self):
60
+ owner = NAMESPACE.get()
61
+ if not owner:
62
+ raise ValueError('Workspace authorization is missing')
63
+ return SQLiteRepository(self.directory / owner / 'inspection.sqlite3')
64
+
65
+ def decorate(self, record):
66
+ if record is None:
67
+ return None
68
+ result = dict(record)
69
+ for kind in ('image', 'heatmap', 'report'):
70
+ result[kind+'_url'] = f"/api/inspections/{record['id']}/{kind}?access={capability(record['id'], kind)}"
71
+ return result
72
+
73
+ def save(self, record):
74
+ return self.decorate(self.current().save(record))
75
+
76
+ def get(self, identifier):
77
+ return self.decorate(self.current().get(identifier))
78
+
79
+ def list(self, *args, **kwargs):
80
+ return [self.decorate(row) for row in self.current().list(*args, **kwargs)]
81
+
82
+ def __getattr__(self, name):
83
+ return getattr(self.current(), name)
frontend/dist/assets/TeamWorkspace-CTDq3hP1.js ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import{c as h,r as n,a as Q,b as d,R as e,L as X,S as $,A as ee,d as te}from"./index-Ch_CERBq.js";/**
2
+ * @license lucide-react v0.468.0 - ISC
3
+ *
4
+ * This source code is licensed under the ISC license.
5
+ * See the LICENSE file in the root directory of this source tree.
6
+ */const ae=h("ArchiveRestore",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]]);/**
7
+ * @license lucide-react v0.468.0 - ISC
8
+ *
9
+ * This source code is licensed under the ISC license.
10
+ * See the LICENSE file in the root directory of this source tree.
11
+ */const _=h("Cloud",[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]]);/**
12
+ * @license lucide-react v0.468.0 - ISC
13
+ *
14
+ * This source code is licensed under the ISC license.
15
+ * See the LICENSE file in the root directory of this source tree.
16
+ */const re=h("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);/**
17
+ * @license lucide-react v0.468.0 - ISC
18
+ *
19
+ * This source code is licensed under the ISC license.
20
+ * See the LICENSE file in the root directory of this source tree.
21
+ */const ne=h("LogIn",[["path",{d:"M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4",key:"u53s6r"}],["polyline",{points:"10 17 15 12 10 7",key:"1ail0h"}],["line",{x1:"15",x2:"3",y1:"12",y2:"12",key:"v6grx8"}]]);/**
22
+ * @license lucide-react v0.468.0 - ISC
23
+ *
24
+ * This source code is licensed under the ISC license.
25
+ * See the LICENSE file in the root directory of this source tree.
26
+ */const le=h("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/**
27
+ * @license lucide-react v0.468.0 - ISC
28
+ *
29
+ * This source code is licensed under the ISC license.
30
+ * See the LICENSE file in the root directory of this source tree.
31
+ */const se=h("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/**
32
+ * @license lucide-react v0.468.0 - ISC
33
+ *
34
+ * This source code is licensed under the ISC license.
35
+ * See the LICENSE file in the root directory of this source tree.
36
+ */const ce=h("Send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]);/**
37
+ * @license lucide-react v0.468.0 - ISC
38
+ *
39
+ * This source code is licensed under the ISC license.
40
+ * See the LICENSE file in the root directory of this source tree.
41
+ */const oe=h("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);function me(){var D;const[c,A]=n.useState(null),[l,x]=n.useState(null),[v,M]=n.useState([]),[S,H]=n.useState({}),[g,F]=n.useState(""),[R,L]=n.useState(""),[o,q]=n.useState(!1),[P,y]=n.useState(""),[E,W]=n.useState(!1),[s,w]=n.useState(null),[B,V]=n.useState([]),[K,G]=n.useState([]),[k,z]=n.useState(""),[Y,I]=n.useState(!1),[U,O]=n.useState(""),[Z,N]=n.useState(!1),C=Q();async function i(t){q(!0),y("");try{await t()}catch(r){y(r.message||"Team request failed.")}finally{q(!1)}}async function b(){const{client:t,staff:r}=await te();x(r);let a=t.from("shared_inspections").select("*").order("created_at",{ascending:!1}).limit(200);a=E?a.not("archived_at","is",null):a.is("archived_at",null);const[{data:m,error:f},{data:u,error:p}]=await Promise.all([a,t.from("staff_members").select("*")]);if(f)throw f;if(p)throw p;M(m||[]),H(Object.fromEntries((u||[]).map(T=>[T.user_id,T.display_name])))}n.useEffect(()=>{if(!C)return;let t=!1,r;return d().then(async a=>{r=a.auth.onAuthStateChange((f,u)=>{t||(A((u==null?void 0:u.user)||null),f==="PASSWORD_RECOVERY"&&I(!0))}).data.subscription;const{data:m}=await a.auth.getUser();t||A(m.user)}).catch(a=>{t||y(a.message)}),()=>{t=!0,r==null||r.unsubscribe()}},[C]),n.useEffect(()=>{if(!c)return;let t=!1;b().catch(a=>{t||y(a.message)});const r=setInterval(()=>b().catch(a=>{t||y(a.message)}),15e3);return()=>{t=!0,clearInterval(r)}},[c==null?void 0:c.id,E]);async function j(t){await i(async()=>{const r=await d(),a=r.storage.from("team-inspections"),m=await Promise.all([t.image_path,t.heatmap_path].map(p=>a.createSignedUrl(p,900)));if(m.some(p=>p.error))throw new Error("Private images could not be loaded. Check staff/storage policies.");const{data:f,error:u}=await r.from("staff_notes").select("*").eq("inspection_id",t.id).order("created_at");if(u)throw u;w(t),V(m.map(p=>p.data.signedUrl)),G(f||[])})}async function J(){await i(async()=>{const t=await d(),r=v.filter(a=>a.owner_id===c.id).map(a=>a.id);if(r.length){const{error:a}=await t.rpc("archive_team_inspections",{p_ids:r});if(a)throw a}w(null),N(!1),await b()})}return C?e.createElement(e.Fragment,null,e.createElement("section",{className:"card"},e.createElement("div",{className:"section-title"},e.createElement("div",null,e.createElement("h2",null,e.createElement(oe,{size:21})," Staff workspace"),e.createElement("p",null,"Signed-in staff share saved inspections and review notes. Live AI runs on the connected inspection backend.")),e.createElement("span",{className:"subtle-tag"},e.createElement(_,{size:13})," SUPABASE")),P&&e.createElement("div",{className:"error",role:"alert"},P),c?e.createElement(e.Fragment,null,e.createElement("div",{className:"team-toolbar"},e.createElement("div",null,e.createElement($,{size:18}),e.createElement("strong",null,(l==null?void 0:l.display_name)||c.email),e.createElement("span",{className:"subtle-tag"},(l==null?void 0:l.role)||"CHECKING MEMBERSHIP")),e.createElement("button",{className:"secondary",disabled:o,onClick:()=>i(b)},e.createElement(se,{size:16})," Refresh"),e.createElement("button",{className:"secondary",onClick:()=>i(async()=>{await(await d()).auth.signOut(),M([]),w(null),x(null)})},e.createElement(le,{size:16})," Sign out")),Y&&e.createElement("form",{className:"login-form",onSubmit:t=>{t.preventDefault(),i(async()=>{const r=await d(),{error:a}=await r.auth.updateUser({password:U});if(a)throw a;O(""),I(!1)})}},e.createElement("label",{className:"field"},"Set a new password",e.createElement("input",{type:"password",minLength:12,autoComplete:"new-password",value:U,onChange:t=>O(t.target.value),required:!0})),e.createElement("button",{className:"primary",disabled:o},"Save password")),e.createElement("div",{className:"team-toolbar"},e.createElement("span",null,"Latest ",v.length," shared records · refreshes every 15 seconds"),(l==null?void 0:l.role)==="developer"&&e.createElement("button",{className:"secondary",onClick:()=>{W(!E),w(null)}},e.createElement(ae,{size:16}),E?"Active history":"Developer recovery"),!E&&e.createElement("button",{className:"secondary danger",disabled:o||!v.some(t=>t.owner_id===c.id),onClick:()=>N(!0)},e.createElement(ee,{size:16})," Archive my visible history")),Z&&e.createElement("div",{className:"note"},e.createElement("div",null,e.createElement("strong",null,"Archive your visible records?"),e.createElement("p",null,"They will leave the shared active history. Original files and conversations remain recoverable by a developer. Other staff members’ records will stay active."),e.createElement("div",{className:"button-row"},e.createElement("button",{className:"primary",disabled:o,onClick:J},"Archive my records"),e.createElement("button",{className:"secondary",onClick:()=>N(!1)},"Cancel")))),e.createElement("div",{className:"table-wrap"},e.createElement("table",null,e.createElement("thead",null,e.createElement("tr",null,e.createElement("th",null,"Inspection"),e.createElement("th",null,"Product"),e.createElement("th",null,"Result"),e.createElement("th",null,"Shared by"),e.createElement("th",null,"Saved"),e.createElement("th",null))),e.createElement("tbody",null,v.map(t=>{var r;return e.createElement("tr",{key:t.id},e.createElement("td",null,e.createElement("strong",null,t.id.slice(0,8))),e.createElement("td",null,t.payload.category),e.createElement("td",null,e.createElement("span",{className:"badge "+((r=t.payload.verdict)==null?void 0:r.toLowerCase())},t.payload.verdict)),e.createElement("td",null,S[t.owner_id]||"Staff member"),e.createElement("td",null,new Date(t.created_at).toLocaleString()),e.createElement("td",null,e.createElement("button",{className:"text-button",onClick:()=>j(t)},"Review"),E&&(l==null?void 0:l.role)==="developer"&&e.createElement("button",{className:"text-button",disabled:o,onClick:()=>i(async()=>{const a=await d(),{error:m}=await a.rpc("restore_team_inspections",{p_ids:[t.id]});if(m)throw m;await b()})},"Restore")))}))),!v.length&&e.createElement("div",{className:"empty"},e.createElement(_,{size:30}),e.createElement("p",null,E?"No archived records to recover.":"No shared inspections yet. In the local app, open a result and select Share with staff.")))):e.createElement("form",{className:"login-form",onSubmit:t=>{t.preventDefault(),i(async()=>{const r=await d(),{error:a}=await r.auth.signInWithPassword({email:g,password:R});if(a)throw a;L("")})}},e.createElement("label",{className:"field"},"Work email",e.createElement("input",{type:"email",autoComplete:"username",value:g,onChange:t=>F(t.target.value),required:!0})),e.createElement("label",{className:"field"},"Password",e.createElement("input",{type:"password",autoComplete:"current-password",value:R,onChange:t=>L(t.target.value),required:!0})),e.createElement("button",{className:"primary",disabled:o},o?e.createElement(X,{className:"spin",size:17}):e.createElement(ne,{size:17})," Sign in"),e.createElement("button",{type:"button",className:"text-button",disabled:!g||o,onClick:()=>i(async()=>{const t=await d(),{error:r}=await t.auth.resetPasswordForEmail(g,{redirectTo:location.origin+location.pathname});if(r)throw r;y("Password reset requested. Check your email.")})},"Reset password"),e.createElement("p",{className:"caption"},"Accounts must be invited and approved by your workspace developer. Signing up alone does not grant staff access."))),c&&s&&e.createElement("section",{className:"card"},e.createElement("div",{className:"section-title"},e.createElement("div",null,e.createElement("h2",null,"Shared inspection · ",s.id.slice(0,8)),e.createElement("p",null,"Saved snapshot from ",S[s.owner_id]||"a colleague",". This page does not run a new prediction.")),e.createElement("button",{className:"text-button",onClick:()=>w(null)},"Close")),e.createElement("div",{className:"shared-images"},B.map((t,r)=>e.createElement("img",{key:t,src:t,alt:r?"Saved anomaly heatmap":"Saved inspected product"}))),e.createElement("div",{className:"observation"},e.createElement("strong",null,"SAVED MEASUREMENTS"),e.createElement("span",null,s.payload.verdict," · score ",Number(s.payload.score).toFixed(5)," · threshold ",Number(s.payload.threshold).toFixed(5))),e.createElement("h3",{className:"section-gap"},"Recorded evidence"),(D=s.conversation)!=null&&D.length?s.conversation.map((t,r)=>e.createElement("p",{className:"cloud-message",key:r},e.createElement("strong",null,t.role==="user"?"Inspector":"Evidence Assistant",": "),t.question||t.answer)):e.createElement("p",{className:"caption"},"No conversation was included when this inspection was shared."),e.createElement("h3",{className:"section-gap"},"Staff review notes"),K.map(t=>e.createElement("div",{className:"cloud-message",key:t.id},e.createElement("strong",null,S[t.author_id]||"Staff member"),e.createElement("p",null,t.body),e.createElement("small",null,new Date(t.created_at).toLocaleString()))),!s.archived_at&&e.createElement("form",{className:"question-form",onSubmit:t=>{t.preventDefault(),i(async()=>{const r=await d(),{error:a}=await r.from("staff_notes").insert({inspection_id:s.id,author_id:c.id,body:k.trim()});if(a)throw a;z(""),await j(s)})}},e.createElement("input",{"aria-label":"Staff review note",maxLength:2e3,placeholder:"Add a review note for your colleagues…",value:k,onChange:t=>z(t.target.value)}),e.createElement("button",{className:"primary",disabled:o||!k.trim()},e.createElement(ce,{size:16})," Add note")))):e.createElement("section",{className:"card cloud-setup"},e.createElement("div",{className:"setup-icon"},e.createElement(_,{size:32})),e.createElement("span",{className:"eyebrow"},"TEAM WORKSPACE"),e.createElement("h2",null,"One shared view of inspection."),e.createElement("p",null,"The staff workspace is ready to connect to your own Supabase project. No cloud project or account has been created for you."),e.createElement("div",{className:"setup-grid"},[["01","Create a free project","Use your Supabase account and select an eligible Free plan."],["02","Set up staff access","Run the supplied schema, add your developer account and invite colleagues."],["03","Connect this dashboard","Add the project URL and publishable key to config.js, then reload."]].map(([t,r,a])=>e.createElement("div",{key:t},e.createElement("b",null,t),e.createElement("h3",null,r),e.createElement("p",null,a)))),e.createElement("a",{className:"primary",href:"https://supabase.com/dashboard",target:"_blank",rel:"noreferrer"},"Open Supabase ",e.createElement(re,{size:16})),e.createElement("p",{className:"caption"},"Setup files: deployment/SUPABASE_SETUP.md and deployment/supabase.sql. Never place a service-role key in the browser. Local inspection works without cloud setup."))}export{me as default};
frontend/dist/assets/TeamWorkspace-DqNccP9e.js ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import{c as h,r as n,a as Q,b as d,R as e,L as X,S as $,A as ee,d as te}from"./index-DjPsLnbj.js";/**
2
+ * @license lucide-react v0.468.0 - ISC
3
+ *
4
+ * This source code is licensed under the ISC license.
5
+ * See the LICENSE file in the root directory of this source tree.
6
+ */const ae=h("ArchiveRestore",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]]);/**
7
+ * @license lucide-react v0.468.0 - ISC
8
+ *
9
+ * This source code is licensed under the ISC license.
10
+ * See the LICENSE file in the root directory of this source tree.
11
+ */const _=h("Cloud",[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]]);/**
12
+ * @license lucide-react v0.468.0 - ISC
13
+ *
14
+ * This source code is licensed under the ISC license.
15
+ * See the LICENSE file in the root directory of this source tree.
16
+ */const re=h("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);/**
17
+ * @license lucide-react v0.468.0 - ISC
18
+ *
19
+ * This source code is licensed under the ISC license.
20
+ * See the LICENSE file in the root directory of this source tree.
21
+ */const ne=h("LogIn",[["path",{d:"M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4",key:"u53s6r"}],["polyline",{points:"10 17 15 12 10 7",key:"1ail0h"}],["line",{x1:"15",x2:"3",y1:"12",y2:"12",key:"v6grx8"}]]);/**
22
+ * @license lucide-react v0.468.0 - ISC
23
+ *
24
+ * This source code is licensed under the ISC license.
25
+ * See the LICENSE file in the root directory of this source tree.
26
+ */const le=h("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/**
27
+ * @license lucide-react v0.468.0 - ISC
28
+ *
29
+ * This source code is licensed under the ISC license.
30
+ * See the LICENSE file in the root directory of this source tree.
31
+ */const se=h("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/**
32
+ * @license lucide-react v0.468.0 - ISC
33
+ *
34
+ * This source code is licensed under the ISC license.
35
+ * See the LICENSE file in the root directory of this source tree.
36
+ */const ce=h("Send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]);/**
37
+ * @license lucide-react v0.468.0 - ISC
38
+ *
39
+ * This source code is licensed under the ISC license.
40
+ * See the LICENSE file in the root directory of this source tree.
41
+ */const oe=h("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);function me(){var D;const[c,A]=n.useState(null),[l,x]=n.useState(null),[v,M]=n.useState([]),[S,H]=n.useState({}),[g,F]=n.useState(""),[R,L]=n.useState(""),[o,q]=n.useState(!1),[P,y]=n.useState(""),[E,W]=n.useState(!1),[s,w]=n.useState(null),[B,V]=n.useState([]),[K,G]=n.useState([]),[k,z]=n.useState(""),[Y,I]=n.useState(!1),[U,O]=n.useState(""),[Z,N]=n.useState(!1),C=Q();async function i(t){q(!0),y("");try{await t()}catch(r){y(r.message||"Team request failed.")}finally{q(!1)}}async function b(){const{client:t,staff:r}=await te();x(r);let a=t.from("shared_inspections").select("*").order("created_at",{ascending:!1}).limit(200);a=E?a.not("archived_at","is",null):a.is("archived_at",null);const[{data:m,error:f},{data:u,error:p}]=await Promise.all([a,t.from("staff_members").select("*")]);if(f)throw f;if(p)throw p;M(m||[]),H(Object.fromEntries((u||[]).map(T=>[T.user_id,T.display_name])))}n.useEffect(()=>{if(!C)return;let t=!1,r;return d().then(async a=>{r=a.auth.onAuthStateChange((f,u)=>{t||(A((u==null?void 0:u.user)||null),f==="PASSWORD_RECOVERY"&&I(!0))}).data.subscription;const{data:m}=await a.auth.getUser();t||A(m.user)}).catch(a=>{t||y(a.message)}),()=>{t=!0,r==null||r.unsubscribe()}},[C]),n.useEffect(()=>{if(!c)return;let t=!1;b().catch(a=>{t||y(a.message)});const r=setInterval(()=>b().catch(a=>{t||y(a.message)}),15e3);return()=>{t=!0,clearInterval(r)}},[c==null?void 0:c.id,E]);async function j(t){await i(async()=>{const r=await d(),a=r.storage.from("team-inspections"),m=await Promise.all([t.image_path,t.heatmap_path].map(p=>a.createSignedUrl(p,900)));if(m.some(p=>p.error))throw new Error("Private images could not be loaded. Check staff/storage policies.");const{data:f,error:u}=await r.from("staff_notes").select("*").eq("inspection_id",t.id).order("created_at");if(u)throw u;w(t),V(m.map(p=>p.data.signedUrl)),G(f||[])})}async function J(){await i(async()=>{const t=await d(),r=v.filter(a=>a.owner_id===c.id).map(a=>a.id);if(r.length){const{error:a}=await t.rpc("archive_team_inspections",{p_ids:r});if(a)throw a}w(null),N(!1),await b()})}return C?e.createElement(e.Fragment,null,e.createElement("section",{className:"card"},e.createElement("div",{className:"section-title"},e.createElement("div",null,e.createElement("h2",null,e.createElement(oe,{size:21})," Staff workspace"),e.createElement("p",null,"Signed-in staff share saved inspections and review notes. Live AI runs on the connected inspection backend.")),e.createElement("span",{className:"subtle-tag"},e.createElement(_,{size:13})," SUPABASE")),P&&e.createElement("div",{className:"error",role:"alert"},P),c?e.createElement(e.Fragment,null,e.createElement("div",{className:"team-toolbar"},e.createElement("div",null,e.createElement($,{size:18}),e.createElement("strong",null,(l==null?void 0:l.display_name)||c.email),e.createElement("span",{className:"subtle-tag"},(l==null?void 0:l.role)||"CHECKING MEMBERSHIP")),e.createElement("button",{className:"secondary",disabled:o,onClick:()=>i(b)},e.createElement(se,{size:16})," Refresh"),e.createElement("button",{className:"secondary",onClick:()=>i(async()=>{await(await d()).auth.signOut(),M([]),w(null),x(null)})},e.createElement(le,{size:16})," Sign out")),Y&&e.createElement("form",{className:"login-form",onSubmit:t=>{t.preventDefault(),i(async()=>{const r=await d(),{error:a}=await r.auth.updateUser({password:U});if(a)throw a;O(""),I(!1)})}},e.createElement("label",{className:"field"},"Set a new password",e.createElement("input",{type:"password",minLength:12,autoComplete:"new-password",value:U,onChange:t=>O(t.target.value),required:!0})),e.createElement("button",{className:"primary",disabled:o},"Save password")),e.createElement("div",{className:"team-toolbar"},e.createElement("span",null,"Latest ",v.length," shared records · refreshes every 15 seconds"),(l==null?void 0:l.role)==="developer"&&e.createElement("button",{className:"secondary",onClick:()=>{W(!E),w(null)}},e.createElement(ae,{size:16}),E?"Active history":"Developer recovery"),!E&&e.createElement("button",{className:"secondary danger",disabled:o||!v.some(t=>t.owner_id===c.id),onClick:()=>N(!0)},e.createElement(ee,{size:16})," Archive my visible history")),Z&&e.createElement("div",{className:"note"},e.createElement("div",null,e.createElement("strong",null,"Archive your visible records?"),e.createElement("p",null,"They will leave the shared active history. Original files and conversations remain recoverable by a developer. Other staff members’ records will stay active."),e.createElement("div",{className:"button-row"},e.createElement("button",{className:"primary",disabled:o,onClick:J},"Archive my records"),e.createElement("button",{className:"secondary",onClick:()=>N(!1)},"Cancel")))),e.createElement("div",{className:"table-wrap"},e.createElement("table",null,e.createElement("thead",null,e.createElement("tr",null,e.createElement("th",null,"Inspection"),e.createElement("th",null,"Product"),e.createElement("th",null,"Result"),e.createElement("th",null,"Shared by"),e.createElement("th",null,"Saved"),e.createElement("th",null))),e.createElement("tbody",null,v.map(t=>{var r;return e.createElement("tr",{key:t.id},e.createElement("td",null,e.createElement("strong",null,t.id.slice(0,8))),e.createElement("td",null,t.payload.category),e.createElement("td",null,e.createElement("span",{className:"badge "+((r=t.payload.verdict)==null?void 0:r.toLowerCase())},t.payload.verdict)),e.createElement("td",null,S[t.owner_id]||"Staff member"),e.createElement("td",null,new Date(t.created_at).toLocaleString()),e.createElement("td",null,e.createElement("button",{className:"text-button",onClick:()=>j(t)},"Review"),E&&(l==null?void 0:l.role)==="developer"&&e.createElement("button",{className:"text-button",disabled:o,onClick:()=>i(async()=>{const a=await d(),{error:m}=await a.rpc("restore_team_inspections",{p_ids:[t.id]});if(m)throw m;await b()})},"Restore")))}))),!v.length&&e.createElement("div",{className:"empty"},e.createElement(_,{size:30}),e.createElement("p",null,E?"No archived records to recover.":"No shared inspections yet. In the local app, open a result and select Share with staff.")))):e.createElement("form",{className:"login-form",onSubmit:t=>{t.preventDefault(),i(async()=>{const r=await d(),{error:a}=await r.auth.signInWithPassword({email:g,password:R});if(a)throw a;L("")})}},e.createElement("label",{className:"field"},"Work email",e.createElement("input",{type:"email",autoComplete:"username",value:g,onChange:t=>F(t.target.value),required:!0})),e.createElement("label",{className:"field"},"Password",e.createElement("input",{type:"password",autoComplete:"current-password",value:R,onChange:t=>L(t.target.value),required:!0})),e.createElement("button",{className:"primary",disabled:o},o?e.createElement(X,{className:"spin",size:17}):e.createElement(ne,{size:17})," Sign in"),e.createElement("button",{type:"button",className:"text-button",disabled:!g||o,onClick:()=>i(async()=>{const t=await d(),{error:r}=await t.auth.resetPasswordForEmail(g,{redirectTo:location.origin+location.pathname});if(r)throw r;y("Password reset requested. Check your email.")})},"Reset password"),e.createElement("p",{className:"caption"},"Accounts must be invited and approved by your workspace developer. Signing up alone does not grant staff access."))),c&&s&&e.createElement("section",{className:"card"},e.createElement("div",{className:"section-title"},e.createElement("div",null,e.createElement("h2",null,"Shared inspection · ",s.id.slice(0,8)),e.createElement("p",null,"Saved snapshot from ",S[s.owner_id]||"a colleague",". This page does not run a new prediction.")),e.createElement("button",{className:"text-button",onClick:()=>w(null)},"Close")),e.createElement("div",{className:"shared-images"},B.map((t,r)=>e.createElement("img",{key:t,src:t,alt:r?"Saved anomaly heatmap":"Saved inspected product"}))),e.createElement("div",{className:"observation"},e.createElement("strong",null,"SAVED MEASUREMENTS"),e.createElement("span",null,s.payload.verdict," · score ",Number(s.payload.score).toFixed(5)," · threshold ",Number(s.payload.threshold).toFixed(5))),e.createElement("h3",{className:"section-gap"},"Recorded evidence"),(D=s.conversation)!=null&&D.length?s.conversation.map((t,r)=>e.createElement("p",{className:"cloud-message",key:r},e.createElement("strong",null,t.role==="user"?"Inspector":"Evidence Assistant",": "),t.question||t.answer)):e.createElement("p",{className:"caption"},"No conversation was included when this inspection was shared."),e.createElement("h3",{className:"section-gap"},"Staff review notes"),K.map(t=>e.createElement("div",{className:"cloud-message",key:t.id},e.createElement("strong",null,S[t.author_id]||"Staff member"),e.createElement("p",null,t.body),e.createElement("small",null,new Date(t.created_at).toLocaleString()))),!s.archived_at&&e.createElement("form",{className:"question-form",onSubmit:t=>{t.preventDefault(),i(async()=>{const r=await d(),{error:a}=await r.from("staff_notes").insert({inspection_id:s.id,author_id:c.id,body:k.trim()});if(a)throw a;z(""),await j(s)})}},e.createElement("input",{"aria-label":"Staff review note",maxLength:2e3,placeholder:"Add a review note for your colleagues…",value:k,onChange:t=>z(t.target.value)}),e.createElement("button",{className:"primary",disabled:o||!k.trim()},e.createElement(ce,{size:16})," Add note")))):e.createElement("section",{className:"card cloud-setup"},e.createElement("div",{className:"setup-icon"},e.createElement(_,{size:32})),e.createElement("span",{className:"eyebrow"},"TEAM WORKSPACE"),e.createElement("h2",null,"One shared view of inspection."),e.createElement("p",null,"The staff workspace is ready to connect to your own Supabase project. No cloud project or account has been created for you."),e.createElement("div",{className:"setup-grid"},[["01","Create a free project","Use your Supabase account and select an eligible Free plan."],["02","Set up staff access","Run the supplied schema, add your developer account and invite colleagues."],["03","Connect this dashboard","Add the project URL and publishable key to config.js, then reload."]].map(([t,r,a])=>e.createElement("div",{key:t},e.createElement("b",null,t),e.createElement("h3",null,r),e.createElement("p",null,a)))),e.createElement("a",{className:"primary",href:"https://supabase.com/dashboard",target:"_blank",rel:"noreferrer"},"Open Supabase ",e.createElement(re,{size:16})),e.createElement("p",{className:"caption"},"Setup files: deployment/SUPABASE_SETUP.md and deployment/supabase.sql. Never place a service-role key in the browser. Local inspection works without cloud setup."))}export{me as default};
frontend/dist/assets/index-Ch_CERBq.js ADDED
The diff for this file is too large to render. See raw diff
 
frontend/dist/assets/index-DjPsLnbj.js ADDED
The diff for this file is too large to render. See raw diff
 
frontend/dist/config.js CHANGED
@@ -1,5 +1 @@
1
- // Public settings only. Never put a service-role key or password in this file.
2
- window.DEFECTRAG_PUBLIC_CONFIG = {
3
- supabaseUrl: '',
4
- supabasePublishableKey: ''
5
- };
 
1
+ window.DEFECTRAG_PUBLIC_CONFIG={"supabaseUrl": "https://zrzqpbcomlorfzszolrs.supabase.co", "supabasePublishableKey": "sb_publishable_ff0gl6l7ZWb_zKcklF6e3g_VT7Qi7FF"};
 
 
 
 
frontend/dist/index.html CHANGED
@@ -1,3 +1,3 @@
1
- <!doctype html><html lang="en"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width,initial-scale=1.0"/><meta name="theme-color" content="#132e32"/><meta name="description" content="Local visual anomaly inspection with traceable evidence."/><title>DefectRAG · Inspection intelligence</title><link rel="icon" type="image/svg+xml" href="./logo.svg"><script src="./config.js"></script> <script type="module" crossorigin src="./assets/index-DPvx1g1c.js"></script>
2
  <link rel="stylesheet" crossorigin href="./assets/index-Bn4HF2vD.css">
3
  </head><body><div id="root"></div></body></html>
 
1
+ <!doctype html><html lang="en"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width,initial-scale=1.0"/><meta name="theme-color" content="#132e32"/><meta name="description" content="Local visual anomaly inspection with traceable evidence."/><title>DefectRAG · Inspection intelligence</title><link rel="icon" type="image/svg+xml" href="./logo.svg"><script src="./config.js"></script> <script type="module" crossorigin src="./assets/index-DjPsLnbj.js"></script>
2
  <link rel="stylesheet" crossorigin href="./assets/index-Bn4HF2vD.css">
3
  </head><body><div id="root"></div></body></html>
models/highres/candle.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bb6767014719520899e8d2336ea2811ae8dadabb210a8855f7497f2ac48ab7ad
3
+ size 23244689
models/highres/capsules.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fa34f8c1a203e609450e57156d5f75ca157140d88d07d0bf46947c3029675c55
3
+ size 22108790
models/highres/cashew.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4b908b22f79158fb46c0e591610d5c9470d588d4f0d017dd0bb493a58e64c693
3
+ size 18366576
models/highres/chewinggum.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:37165883dcc6304f60346c2052c7fa4151d4048b44fdb80a4f60ffc48477ed7d
3
+ size 18458527
models/highres/fryum.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ca73c0cd2b2e75d80874f7dd6270f09b13c55292fa93b1da1eeef361d8375ba4
3
+ size 18381371
models/highres/macaroni1.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:28ebf491e124df62266c5c3b72ea5bfebb50ef93c189d5615d3ae866e8675432
3
+ size 23251984
models/highres/macaroni2.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8dfe4f82ece83668ea4a97c18ef134ab16bea8ab6d2913959eb810942537737a
3
+ size 23243554
models/highres/pcb2.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:694689b6703e399ea4076343a40ddff6a920f67c0c344048f0b2ef6402f3abb8
3
+ size 23253151
models/highres/pcb3.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:704ee7d0827ede2b0a795a0efae8eb524751d2d1cb054cf7278c22888550a44c
3
+ size 23242572
models/highres/pcb4.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8847deec2a0b8daab9139e7680d502352161e994bb5d2fe4bc313df6af4cc5d5
3
+ size 23248613
models/highres/pipe_fryum.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e28bf35ca2e553dd21821230f34682b94b11a5d203459f61049a774663c0d819
3
+ size 18401041
requirements.txt CHANGED
@@ -4,7 +4,7 @@ torchvision==0.23.0
4
  gradio==6.30.0
5
  spaces==0.51.3
6
  transformers==5.20.1
7
- huggingface-hub==2.2.0
8
  fastapi==0.142.2
9
  starlette==1.8.0
10
  numpy==2.1.3
 
4
  gradio==6.30.0
5
  spaces==0.51.3
6
  transformers==5.20.1
7
+ huggingface-hub==1.31.0
8
  fastapi==0.142.2
9
  starlette==1.8.0
10
  numpy==2.1.3