Download deployment/space/app.py from Wizzas/DefectRAG: direct link, hf CLI and curl.
- Browser
- Download file 16.6 kB
-
https://huggingface.co/spaces/Wizzas/DefectRAG/resolve/main/deployment/space/app.py
- Command line
-
hf download hf://spaces/Wizzas/DefectRAG/deployment/space/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Wizzas/DefectRAG/resolve/main/deployment/space/app.py
16.6 kB
| """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 | |
| 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) | |
| async def staff_access_error(request,exc): | |
| return JSONResponse({'error':{'message':str(exc)}},status_code=403) | |
| async def cloud_storage_error(request,exc): | |
| return JSONResponse({'error':{'message':str(exc)}},status_code=503) | |
| 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) | |
| 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) | |
| 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) | |
| 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')}} | |
| 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") | |
| def original_image(identifier: str): | |
| return artifact(identifier,'image') | |
| 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) | |
| def queued_only(operation: str): | |
| raise HTTPException(409,'Use the dashboard Gradio queue for model execution.') | |
| def unknown_api(unknown: str): | |
| raise HTTPException(404,'API route not found') | |
| def dashboard(): | |
| return FileResponse(UI/'index.html',headers={'Cache-Control':'no-store'}) | |
| def public_config(): | |
| return FileResponse(UI/'config.js',headers={'Cache-Control':'no-store'}) | |
| 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) | |