File size: 16,584 Bytes
3784513
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9b5fd9
3784513
 
0db4e63
3784513
 
e4188c6
57a57f5
4946331
3784513
 
 
0db4e63
 
 
 
 
 
 
 
 
3784513
 
 
 
 
 
 
 
 
0db4e63
3784513
 
 
e4188c6
 
3784513
 
 
 
 
 
 
 
 
 
 
 
 
e4188c6
 
3784513
 
 
 
 
 
 
0db4e63
3784513
 
 
 
 
 
d09a296
 
 
 
 
b9b5fd9
4946331
 
3784513
d09a296
 
 
 
cd9f54c
 
d09a296
 
 
d49c762
 
 
 
 
 
 
3784513
ebbcf47
 
 
 
 
 
 
 
 
 
 
3784513
 
 
 
 
 
d49c762
3784513
 
 
4946331
 
3784513
 
 
4946331
3784513
 
4946331
3784513
 
d09a296
 
 
4946331
 
d09a296
3784513
 
 
 
 
 
 
 
4946331
3784513
 
 
 
 
 
 
 
 
 
 
e1a6941
3784513
 
 
 
 
 
e1a6941
 
 
3784513
 
 
 
 
 
 
e1a6941
3784513
 
 
 
 
e1a6941
3784513
 
 
 
 
 
 
e4188c6
3784513
 
e1a6941
0db4e63
3784513
 
 
 
 
 
 
 
 
4946331
 
 
d09a296
e1a6941
3784513
 
d09a296
4946331
d09a296
 
 
 
4946331
d09a296
 
 
 
 
 
 
 
 
 
3784513
 
 
15fe847
3717008
d49c762
4946331
b9b5fd9
57a57f5
3717008
3784513
 
d09a296
 
 
 
4946331
b9b5fd9
 
d09a296
 
 
 
 
 
 
 
 
 
 
 
 
 
57a57f5
 
 
3784513
 
57a57f5
3784513
 
 
 
 
 
 
e1a6941
 
 
 
3784513
 
 
47cc36c
3784513
 
47cc36c
3784513
 
 
 
 
 
d09a296
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
"""Incremental Gradio/ZeroGPU host for the existing DefectRAG React dashboard."""
import os
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
RUNTIME = Path(os.getenv('DEFECTRAG_SPACE_RUNTIME', ROOT/'runtime/space-development'))
os.environ['DEFECTRAG_DATA'] = str(RUNTIME)
os.environ['DEFECTRAG_FACTORY_ONLY'] = '1'
os.environ['USE_TF'] = '0'
import spaces
import base64
from io import BytesIO
import importlib.metadata
import json
import platform
import re
import time
import uuid
import warnings
import numpy as np
from PIL import Image, ImageOps, UnidentifiedImageError
import torch
import torch.nn.functional as F
from gradio import Server
from fastapi import HTTPException
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse, Response
from fastapi.staticfiles import StaticFiles
from backend.config import CATEGORIES, Settings
from backend.highres import HighResolutionEncoder, PROFILES, foreground_mask, profile_card, score_tokens, restore_map
from backend.vision import sha256, display_map
from backend.storage import now
from backend.references import ReferenceIndex
from backend.inspection_routes import mount_inspection_experience, INSPECTION_UX_PATHS
from deployment.space.sessions import SessionRepository, identity, namespace, NAMESPACE, STAFF_TOKEN, WORKSPACE, artifact_workspace, authorize_artifact, capability, remember_staff, stored_staff

ZERO = os.getenv('SPACES_ZERO_GPU') == '1'
DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
# The fine-tuned encoder with coreset banks is the default; DEFECTRAG_SPACE_PROFILE=dinov2_highres_v1 restores the
# previous frozen-encoder profile (its files stay in the Space).
PROFILE = os.getenv('DEFECTRAG_SPACE_PROFILE', 'dinov2_tuned_v1')
assert PROFILE in PROFILES, 'Unknown detector profile'
BANK_DIRECTORY = ROOT/PROFILES[PROFILE]['directory']
ENCODER_DIRECTORY = ROOT/PROFILES[PROFILE]['encoder']
CARDS = {category: profile_card(ROOT,PROFILE,json.loads((BANK_DIRECTORY/f'{category}.json').read_text())) for category in CATEGORIES}
ENCODER = HighResolutionEncoder(ENCODER_DIRECTORY, device='cpu')
encoder_digest = sha256(ENCODER_DIRECTORY/'model.safetensors')
assert all(card['encoder_sha256'] == encoder_digest for card in CARDS.values())
if DEVICE == 'cuda':
    ENCODER.model.half().to('cuda')
    ENCODER.device = torch.device('cuda')
    ENCODER.dtype = torch.float16
    ENCODER.mean = ENCODER.mean.half().to('cuda')
    ENCODER.std = ENCODER.std.half().to('cuda')
BANKS = {}
for category, card in CARDS.items():
    file = BANK_DIRECTORY/f'{category}.npz'
    assert sha256(file) == card['bank_sha256'], f'Invalid bank checksum: {category}'
    with np.load(file, allow_pickle=False) as saved:
        BANKS[category] = F.normalize(torch.from_numpy(saved['patches'].astype('float32')), dim=-1).to(DEVICE)
# Nearest normal reference photos (an explanation aid only; the score and verdict never use it).
REFERENCES = ReferenceIndex(BANK_DIRECTORY/'references') if PROFILE == 'dinov2_tuned_v1' else None


@spaces.GPU(duration=20)
@torch.inference_mode()
def compute(rgb: np.ndarray, category: str) -> dict:
    start = time.perf_counter()
    if DEVICE == 'cuda':
        torch.cuda.reset_peak_memory_stats()
    tokens, geometry = ENCODER.encode(Image.fromarray(rgb))
    mask = foreground_mask(tokens, geometry['grid'])
    raw, score = score_tokens(tokens, BANKS[category], mask)
    if DEVICE == 'cuda':
        torch.cuda.synchronize()
    references = REFERENCES.nearest(category, tokens, mask) if REFERENCES is not None else []
    return {'raw': raw, 'geometry': geometry, 'score': score, 'references': references,
            'foreground_fraction': float(mask.mean()), 'device': DEVICE,
            'gpu_name': torch.cuda.get_device_name() if DEVICE == 'cuda' else None,
            'peak_gpu_mb': round(torch.cuda.max_memory_allocated()/1024**2, 2) if DEVICE == 'cuda' else None,
            'inference_ms': round((time.perf_counter()-start)*1000, 2)}


class MetadataDetector:
    profile_name = PROFILE
    def cards(self):
        return list(CARDS.values())


ARTIFACTS = RUNTIME/'artifacts'
ARTIFACTS.mkdir(parents=True, exist_ok=True)
UI = Path(os.getenv('DEFECTRAG_SPACE_UI', ROOT/'development-support/space/ui-dist'))
CLOUD_CONFIG=None
if os.getenv('DEFECTRAG_STAFF_BACKEND')=='1':
    from deployment.space.supabase_repository import read_public_config
    CLOUD_CONFIG=read_public_config(UI/'config.js')
    CLOUD_CONFIG['auth_workflow_enabled']=os.getenv('DEFECTRAG_AUTH_WORKFLOW')=='1'
PERSONAL_ENABLED=os.getenv('DEFECTRAG_PERSONAL_WORKSPACE')=='1' and CLOUD_CONFIG is not None
REPO = SessionRepository(RUNTIME/'sessions',cloud_config=CLOUD_CONFIG,artifacts=ARTIFACTS,personal_enabled=PERSONAL_ENABLED)
from backend.main import create_app
from backend.rag import KnowledgeIndex, EvidenceWorkflow
if os.getenv('DEFECTRAG_LIVE_RAG')=='1':
    from deployment.space.generation import CpuBGE, generate_text
    INDEX=KnowledgeIndex(ROOT,RUNTIME/'index',embeddings_factory=CpuBGE)
    # Retrieval initializes on its first CPU request, not during the ZeroGPU
    # fork snapshot. Eager CPU attention avoids CUDA/SDPA capability probing.
    WORKFLOW=EvidenceWorkflow(Settings(),INDEX,generator=generate_text if ZERO else None)
else:
    WORKFLOW=None
GALLERY=None
if os.getenv('DEFECTRAG_GALLERY_ENABLED')=='1' and CLOUD_CONFIG:
    from backend.gallery import SupabaseGallery
    gallery_key=os.getenv('DEFECTRAG_GALLERY_KEY','')
    if re.fullmatch('[a-f0-9]{64}',gallery_key):
        GALLERY=SupabaseGallery(CLOUD_CONFIG,gallery_key)
cpu_app = create_app(Settings(), detector=MetadataDetector(), repository=REPO,workflow=WORKFLOW,gallery=GALLERY)
server = Server(title='DefectRAG')
server.exception_handlers.update(cpu_app.exception_handlers)


@server.exception_handler(ValueError)
async def staff_access_error(request,exc):
    return JSONResponse({'error':{'message':str(exc)}},status_code=403)


@server.exception_handler(RuntimeError)
async def cloud_storage_error(request,exc):
    return JSONResponse({'error':{'message':str(exc)}},status_code=503)


@server.middleware('http')
async def workspace_access(request, call_next):
    path = request.url.path
    public = path in ('/api/health', '/api/models', '/api/evaluation', '/api/benchmark/official', '/api/samples') or path.startswith('/api/samples/')
    public = public or (request.method=='GET' and (path=='/api/gallery' or re.fullmatch(r'/api/gallery/[a-f0-9-]{32,36}',path)))
    if not path.startswith('/api/') or public:
        return await call_next(request)
    try:
        requested_scope=request.headers.get('X-DefectRAG-Workspace','personal')
        if requested_scope not in ('personal','team'):raise ValueError('Invalid workspace')
        match = re.fullmatch(r'/api/inspections/([a-f0-9]{32})/(image|heatmap|report)', path)
        if match and 'access' in request.query_params:
            owner = authorize_artifact(request.query_params['access'], *match.groups())
            requested_scope=artifact_workspace(request.query_params['access'])
        elif path == '/api/export.csv' and 'access' in request.query_params:
            owner = authorize_artifact(request.query_params['access'],'workspace','csv')
            requested_scope=artifact_workspace(request.query_params['access'])
        else:
            owner = namespace(request.headers.get('X-DefectRAG-Session',''))
        bearer=request.headers.get('authorization','').removeprefix('Bearer ')
        if request.headers.get('X-DefectRAG-Session'):
            remember_staff(owner,bearer)
        context = NAMESPACE.set(owner)
        scope_context=WORKSPACE.set(requested_scope)
        token = STAFF_TOKEN.set(bearer or stored_staff(owner))
    except ValueError as exc:
        return JSONResponse({'error': {'message': str(exc)}}, status_code=401)
    try:
        response = await call_next(request)
        response.headers['X-DefectRAG-Export'] = '/api/export.csv?access='+capability('workspace','csv')
        response.headers['Cache-Control'] = 'private, no-store'
        return response
    finally:
        WORKSPACE.reset(scope_context)
        STAFF_TOKEN.reset(token)
        NAMESPACE.reset(context)


@server.api(name='ready', concurrency_limit=1)
def ready(message: str) -> dict:
    return {'message': message, 'zero_gpu_environment': ZERO, 'python': platform.python_version(),
            'device': DEVICE, 'categories': list(CARDS), 'versions': {name: importlib.metadata.version(name)
             for name in ('gradio','spaces','torch','transformers','huggingface-hub')}}


def inspect_one(image_b64, filename, category, batch, request_id=''):
    if category not in CARDS or len(batch)>80 or len(image_b64)>14*1024*1024:
        raise ValueError('Choose a supported category, image up to 10 MB and batch label up to 80 characters.')
    try:
        content = base64.b64decode(image_b64, validate=True)
        if len(content)>10*1024*1024:
            raise ValueError('Image limit is 10 MB')
        from backend.inspection_requests import existing_request,fingerprint
        existing=existing_request(REPO,request_id,content,category,batch)
        if existing:return existing
        with warnings.catch_warnings():
            warnings.simplefilter('error', Image.DecompressionBombWarning)
            with Image.open(BytesIO(content)) as opened:
                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):
                    raise ValueError('Use JPEG, PNG or WebP, 32px minimum, up to 25 MP and 4:1 aspect ratio.')
                image = ImageOps.exif_transpose(opened).convert('RGB')
    except (ValueError, OSError, UnidentifiedImageError, Image.DecompressionBombWarning, Image.DecompressionBombError) as exc:
        raise ValueError('Invalid image. Use a readable JPEG, PNG or WebP: at least 32 pixels per side, up to 25 MP, 10 MB and 4:1 aspect ratio.') from None
    start = time.perf_counter()
    output = compute(np.asarray(image), category)
    card = CARDS[category]
    threshold, margin, score = card['threshold'], card['uncertainty_margin'], output['score']
    verdict = 'Uncertain' if abs(score-threshold)<=margin else 'Anomalous' if score>=threshold else 'Good'
    identifier = request_id or uuid.uuid4().hex
    preview = image.copy()
    preview.thumbnail((1000,1000))
    heatmap = display_map(restore_map(output['raw'],output['geometry'],preview.size),preview,card['heatmap_scale'])
    image.thumbnail((1600,1600))
    image.save(ARTIFACTS/f'{identifier}.jpg', quality=92)
    heatmap.save(ARTIFACTS/f'{identifier}_heatmap.jpg', quality=92)
    record = {key:output[key] for key in ('inference_ms','device','gpu_name','peak_gpu_mb','foreground_fraction')}
    if output.get('references'):record['references']=output['references']
    record.update(id=identifier,created_at=now(),category=category,batch=batch.strip(),filename=Path(filename).name[:160],
        verdict=verdict,score=score,threshold=threshold,uncertainty_margin=margin,defect_category=None,
        request_fingerprint=fingerprint(content,category,batch),
        model_id=card['model_id'],model_sha256=card['bank_sha256'],profile=PROFILE,calibration=card['calibration'],
        total_model_ms=round((time.perf_counter()-start)*1000,2),
        localization=f"{output['geometry']['grid'][0]} x {output['geometry']['grid'][1]} DINOv2 patch distances with PCA foreground heuristic; interpolated, not supervised segmentation",
        scope='VisA appearance anomaly screening; operator-selected category is not verified; foreground heuristic can fail.',
        deployment={'transport':'@gradio/client','zero_gpu_environment':ZERO},
        image_url=f'/api/inspections/{identifier}/image',heatmap_url=f'/api/inspections/{identifier}/heatmap')
    return REPO.save(record)


@server.api(name='inspect',concurrency_limit=1,concurrency_id='model-work')
def inspect(image_b64: str, filename: str, category: str, batch: str, session: str, token: str='', request_id: str='', workspace: str='personal') -> dict:
    if PERSONAL_ENABLED and workspace!='personal':raise ValueError('New inspections must run in Personal workspace; sharing is a separate action.')
    with identity(session,token,workspace):
        REPO.current()  # Validate signed-in staff membership before consuming GPU.
        return inspect_one(image_b64,filename,category,batch,request_id)


@server.api(name='assistant',concurrency_limit=1,concurrency_id='model-work')
def assistant(inspection_id: str, question: str, session: str, token: str='', workspace: str='personal') -> dict:
    if not 3<=len(question)<=1200 or not re.fullmatch('[a-f0-9]{32}',inspection_id):
        raise ValueError('Use a saved inspection and a question of 3–1200 characters.')
    if WORKFLOW is None:
        raise ValueError('Live evidence generation is not enabled in this deployment yet.')
    with identity(session,token,workspace):
        record=REPO.get(inspection_id)
        if record is None:
            raise ValueError('Inspection is unavailable in your workspace')
        history=[{'role':row['role'],'text':row.get('question',row.get('answer','')),
                  'knowledge_fingerprint':row.get('knowledge_fingerprint')} for row in REPO.messages(inspection_id)]
        answer=WORKFLOW.run(question,record,history)
        REPO.add_conversation(inspection_id,question,answer)
        return {**answer,'observation':{key:record[key] for key in ('id','category','verdict','score','threshold')}}


@server.get('/api/health')
def health():
    return {'data':{'status':'ok','mode':'cloud_session_workspace','models':list(CARDS.values()),
        'encoder_configured':True,'llm_model':'Qwen2.5-3B-Instruct fine-tuned for DefectRAG (QLoRA, merged)' if WORKFLOW and ZERO else 'Qwen2.5:3b (local Ollama)' if WORKFLOW else 'generation migration in progress','zero_gpu':ZERO,
        'staff_persistence_enabled':CLOUD_CONFIG is not None,
        'community_gallery_enabled':GALLERY is not None,
        'personal_workspace_enabled':PERSONAL_ENABLED,
        'auth_workflow_enabled':bool(CLOUD_CONFIG and CLOUD_CONFIG.get('auth_workflow_enabled')),
        'api_features':['batch-name-v1','inspection-report-v2'],
        'history':'anonymous browser history is temporary; signed-in approved staff use Supabase' if CLOUD_CONFIG else 'anonymous browser history is temporary; staff backend disabled'}}


def artifact(identifier: str,kind: str):
    record=REPO.get(identifier)
    if record is None:
        raise HTTPException(404,'Inspection not found')
    if record.get('storage','').startswith('supabase'):
        if CLOUD_CONFIG and CLOUD_CONFIG.get('auth_workflow_enabled'):
            return Response(REPO.current().private_artifact(identifier,kind),media_type='image/jpeg',headers={'Cache-Control':'private, no-store'})
        return RedirectResponse(record[kind+'_url'],status_code=307)
    return FileResponse(ARTIFACTS/f"{identifier}{'_heatmap' if kind=='heatmap' else ''}.jpg")


@server.get('/api/inspections/{identifier}/image')
def original_image(identifier: str):
    return artifact(identifier,'image')


@server.get('/api/inspections/{identifier}/heatmap')
def heatmap_image(identifier: str):
    return artifact(identifier,'heatmap')


# Mount the shared UX routes explicitly. A frontend-only release must not rely
# on a newer, undeployed backend.main for batch validation or printable reports.
mount_inspection_experience(server, REPO)
for route in cpu_app.routes:
    path = getattr(route,'path','')
    if path.startswith('/api/') and path not in {'/api/health','/api/inspect','/api/batch','/api/assistant'} | INSPECTION_UX_PATHS:
        server.router.routes.append(route)


@server.post('/api/{operation}')
def queued_only(operation: str):
    raise HTTPException(409,'Use the dashboard Gradio queue for model execution.')

@server.get('/api/{unknown:path}')
def unknown_api(unknown: str):
    raise HTTPException(404,'API route not found')


@server.get('/')
def dashboard():
    return FileResponse(UI/'index.html',headers={'Cache-Control':'no-store'})
@server.get('/config.js')
def public_config():
    return FileResponse(UI/'config.js',headers={'Cache-Control':'no-store'})
@server.get('/logo.svg')
def logo():
    return FileResponse(UI/'logo.svg')
server.mount('/assets',StaticFiles(directory=UI/'assets'),name='react-assets')

if __name__ == '__main__':
    server.launch(server_name='0.0.0.0',server_port=int(os.getenv('PORT','8784')),show_error=True,ssr_mode=False,run_history=False)