File size: 19,093 Bytes
2274b3a | 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 | """Allowlisted incremental commits; no private runtime, dataset or secrets upload."""
import argparse
import hashlib
import json
import os
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
REPO = 'Wizzas/DefectRAG'
OUT = ROOT/'development-support/space'
def checked_frontend():
checked=subprocess.run(['node',str(ROOT/'deployment/space/frontend_release.mjs'),'check',str(OUT/'ui-dist')],
cwd=ROOT,capture_output=True,text=True,check=False,timeout=60)
if checked.returncode:
raise SystemExit('Frontend release blocked: '+checked.stderr.strip())
return json.loads(checked.stdout)
def entry_cache_headers(source):
"""Patch only the two known HTML/config responses in the installed server."""
text=source.decode('utf-8')
for name in ('index.html','config.js'):
original="return FileResponse(UI/'"+name+"')"
fixed="return FileResponse(UI/'"+name+"',headers={'Cache-Control':'no-store'})"
if text.count(fixed)==1:continue
if text.count(original)!=1:raise SystemExit('Live entry response changed; review it before patching')
text=text.replace(original,fixed)
return text.encode('utf-8')
INSPECTION_COMPATIBILITY_FILES=('backend/inspection_routes.py','backend/batch_names.py','backend/inspection_report.py')
def inspection_host_compatibility(source):
"""Only the reviewed read-only batch/report mount; no model/auth changes."""
text=source.decode('utf-8').replace('\r\n','\n')
changes=(
('from backend.storage import now\n', 'from backend.storage import now\nfrom backend.inspection_routes import mount_inspection_experience, INSPECTION_UX_PATHS\n'),
(" 'history':'anonymous browser history", " 'api_features':['batch-name-v1','inspection-report-v2'],\n 'history':'anonymous browser history"),
('for route in cpu_app.routes:\n', '# Mount the shared UX routes explicitly. A frontend-only release must not rely\n# on a newer, undeployed backend.main for batch validation or printable reports.\nmount_inspection_experience(server, REPO)\nfor route in cpu_app.routes:\n'),
("path not in {'/api/health','/api/inspect','/api/batch','/api/assistant'}:", "path not in {'/api/health','/api/inspect','/api/batch','/api/assistant'} | INSPECTION_UX_PATHS:"))
for original,fixed in changes:
if text.count(fixed)==1:continue
if text.count(original)!=1:raise SystemExit('Live inspection host changed; review before patching')
text=text.replace(original,fixed)
compile(text,'deployment/space/app.py','exec')
return text.encode('utf-8')
def publish_frontend(frontend, dry_run=False, refresh_html_cache=False, inspection_compatibility=False):
"""Publish verified browser assets only; preserve the installed server/settings."""
from huggingface_hub import HfApi, CommitOperationAdd, hf_hub_download
api=HfApi()
before=api.space_info(REPO)
remote=set(api.list_repo_files(REPO,repo_type='space',revision=before.sha))
rollback=OUT/('frontend-rollback-'+before.sha[:12])
payloads={}
previous_file=OUT/'publish-frontend.json'
previous=json.loads(previous_file.read_text()) if previous_file.exists() else {}
for name,digest in frontend['files'].items():
payload=(OUT/'ui-dist'/name).read_bytes()
if hashlib.sha256(payload).hexdigest()!=digest:raise SystemExit('Frontend changed before publication')
target='frontend/dist/'+name
if target in remote:
# The last successful immutable commit proves these unchanged files.
# Still verify live config explicitly; no flag changes are inferred.
if name!='config.js' and previous.get('commit')==before.sha and previous.get('manifest',{}).get(name)==digest:continue
original=Path(hf_hub_download(REPO,target,repo_type='space',revision=before.sha)).read_bytes()
if name=='config.js' and original!=payload:
raise SystemExit('Live public configuration differs; preserve/reconcile it before publishing')
if original==payload:continue
if not dry_run:
saved=rollback/name
saved.parent.mkdir(parents=True,exist_ok=True)
saved.write_bytes(original)
payloads[target]=payload
if refresh_html_cache:
target='deployment/space/app.py'
original=Path(hf_hub_download(REPO,target,repo_type='space',revision=before.sha)).read_bytes()
patched=entry_cache_headers(original)
if patched!=original:
payloads[target]=patched
if not dry_run:
saved=rollback/'server-entry-cache.py'
saved.parent.mkdir(parents=True,exist_ok=True)
saved.write_bytes(original)
if inspection_compatibility:
target='deployment/space/app.py'
original=Path(hf_hub_download(REPO,target,repo_type='space',revision=before.sha)).read_bytes()
patched=inspection_host_compatibility(original)
if patched.decode()!= (ROOT/target).read_text(encoding='utf-8'):
raise SystemExit('Local host has unrelated changes; compatible release blocked')
if patched!=original:
payloads[target]=patched
if not dry_run:
saved=rollback/'inspection-compatibility'/target;saved.parent.mkdir(parents=True,exist_ok=True);saved.write_bytes(original)
for target in INSPECTION_COMPATIBILITY_FILES:
payload=(ROOT/target).read_bytes();compile(payload,target,'exec')
if target in remote:
original=Path(hf_hub_download(REPO,target,repo_type='space',revision=before.sha)).read_bytes()
if original==payload:continue
if not dry_run:
saved=rollback/'inspection-compatibility'/target;saved.parent.mkdir(parents=True,exist_ok=True);saved.write_bytes(original)
payloads[target]=payload
summary={'source_git_commit':subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,text=True).strip(),
'parent':before.sha,'frontend_only':not(refresh_html_cache or inspection_compatibility),'entry_cache_headers_only_server_patch':refresh_html_cache,
'inspection_compatibility':inspection_compatibility,
'payload_hashes':{name:hashlib.sha256(value).hexdigest() for name,value in payloads.items()},
'changed_files':list(payloads),'dry_run':dry_run}
if dry_run:
print(json.dumps(summary));return
if checked_frontend()!=frontend:raise SystemExit('Frontend inputs changed before publication')
if inspection_compatibility and any((ROOT/name).read_bytes()!=value for name,value in payloads.items() if name in INSPECTION_COMPATIBILITY_FILES):
raise SystemExit('Compatible server inputs changed before publication')
if not payloads:
print(json.dumps({**summary,'commit':before.sha,'already_current':True}));return
commit=api.create_commit(repo_id=REPO,repo_type='space',parent_commit=before.sha,
operations=[CommitOperationAdd(path_in_repo=name,path_or_fileobj=value) for name,value in payloads.items()],
commit_message=('Fix batch API compatibility, reports and audited dashboard UX' if inspection_compatibility else
'Add optional dashboard tutorial and refresh entry cache headers' if refresh_html_cache else 'Update verified React dashboard'))
receipt={**summary,'commit':commit.oid,'rollback_directory':str(rollback),'manifest':frontend['files']}
(OUT/'publish-frontend.json').write_text(json.dumps(receipt,indent=2))
print(json.dumps({k:v for k,v in receipt.items() if k!='manifest'}))
def unix_lines(data):
"""Windows checkouts use CRLF; the Space stores LF. Compare and upload as LF."""
return data.replace(bytes((13,10)),bytes((10,)))
def publish_server_files(names, dry_run=False):
"""Publish a few reviewed server files only (for example backend/rag.py).
Refuses unless each live file still equals this repository's last commit, so the
upload contains only the local changes you reviewed with `git diff <file>` and no
other drift. The replaced files are saved for rollback. Frontend, models and
settings are untouched. The Space restarts after the commit."""
from huggingface_hub import HfApi, CommitOperationAdd, hf_hub_download
api=HfApi()
before=api.space_info(REPO)
remote=set(api.list_repo_files(REPO,repo_type='space',revision=before.sha))
rollback=OUT/('server-rollback-'+before.sha[:12])
payloads={}
for name in names:
name=Path(name).as_posix()
if not (name.startswith(('backend/','deployment/space/')) and name.endswith('.py') and '..' not in name):
raise SystemExit(f'{name}: only backend/*.py or deployment/space/*.py can be published this way')
if name not in remote:raise SystemExit(f'{name}: not on the Space; use a full phase publish for new files')
local=(ROOT/name).read_bytes()
compile(local,name,'exec')
committed=subprocess.run(['git','show','HEAD:'+name],cwd=ROOT,capture_output=True,check=False).stdout
live=Path(hf_hub_download(REPO,name,repo_type='space',revision=before.sha)).read_bytes()
same=lambda a,b:unix_lines(a)==unix_lines(b)
if not committed or not same(live,committed):
raise SystemExit(f'{name}: the live file differs from the last commit; review that drift first')
if same(live,local):continue
payloads[name]=unix_lines(local)
if not dry_run:
saved=rollback/name;saved.parent.mkdir(parents=True,exist_ok=True);saved.write_bytes(live)
summary={'parent':before.sha,'server_files_only':True,'changed_files':list(payloads),'dry_run':dry_run,
'source_git_commit':subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,text=True).strip()}
if dry_run or not payloads:
print(json.dumps({**summary,'already_current':not payloads}));return
commit=api.create_commit(repo_id=REPO,repo_type='space',parent_commit=before.sha,
operations=[CommitOperationAdd(path_in_repo=name,path_or_fileobj=value) for name,value in payloads.items()],
commit_message='Update reviewed server files: '+', '.join(payloads))
receipt={**summary,'commit':commit.oid,'rollback_directory':str(rollback)}
(OUT/'publish-server-files.json').write_text(json.dumps(receipt,indent=2))
print(json.dumps(receipt))
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--phase', type=int, choices=(2,3,4,5))
parser.add_argument('--check-frontend',action='store_true',help='Offline readiness check only; never contacts Hugging Face')
parser.add_argument('--frontend-only',action='store_true',help='Publish only verified frontend files; preserve server and settings')
parser.add_argument('--dry-run',action='store_true',help='Read-only frontend release plan; no upload')
parser.add_argument('--refresh-html-cache',action='store_true',help='With --frontend-only, patch only live HTML/config no-store headers')
parser.add_argument('--inspection-compatibility',action='store_true',help='With --frontend-only, co-publish the reviewed read-only batch/report routes')
parser.add_argument('--server-files',nargs='+',metavar='FILE',help='Publish only these reviewed backend/*.py or deployment/space/*.py files')
args = parser.parse_args()
if args.server_files:
publish_server_files(args.server_files,args.dry_run)
return
frontend=checked_frontend()
if args.check_frontend:
print(json.dumps({'verified':True,'files':len(frontend['files']),'source_fingerprint':frontend['source_fingerprint']}))
return
if args.frontend_only:
publish_frontend(frontend,args.dry_run,args.refresh_html_cache,args.inspection_compatibility)
return
if args.refresh_html_cache:parser.error('--refresh-html-cache requires --frontend-only')
if args.inspection_compatibility:parser.error('--inspection-compatibility requires --frontend-only')
if args.dry_run:parser.error('--dry-run requires --frontend-only')
if args.phase is None:parser.error('--phase is required for an authorized deployment')
from huggingface_hub import HfApi, CommitOperationAdd
if args.phase>=4:
confirmation=OUT/'migration-confirmed.json'
assert confirmation.exists() and json.loads(confirmation.read_text()).get('user_confirmed_manual_execution'), 'Wait for the user to confirm manual SQL execution before enabling staff persistence.'
from deployment.space.supabase_repository import read_public_config
read_public_config(OUT/'ui-dist/config.js') # Refuse a blank example before changing a working Space.
files = {}
for relative in ('docs/THIRD_PARTY_NOTICES.md','docs/FRONTEND_LICENSES.txt','models/BGE-LICENSE.txt'):
path=ROOT/relative
if path.exists():
files[relative]=path
for relative in ('results/sensitive_deployment_evaluation.json','results/macaroni_recall_deployment_evaluation.json','results/highres_deployment_evaluation.json','results/tuned_deployment_evaluation.json'):
files[relative]=ROOT/relative
for directory in ('backend','deployment/space'):
for path in (ROOT/directory).glob('*.py'):
files[path.relative_to(ROOT).as_posix()] = path
for name in frontend['files']:
files['frontend/dist/'+name] = OUT/'ui-dist'/name
frontend_bytes={name:files['frontend/dist/'+name].read_bytes() for name in frontend['files']}
if any(hashlib.sha256(content).hexdigest()!=frontend['files'][name] for name,content in frontend_bytes.items()):
raise SystemExit('Frontend changed while assembling release')
for path in (ROOT/'models/highres').glob('*.npz'):
files[path.relative_to(ROOT).as_posix()] = path
# Fine-tuned encoder and coreset banks (profile dinov2_tuned_v1); the previous profile's files stay for rollback.
for directory in ('models/highres_tuned','models/encoder_dinov2_tuned'):
for path in (ROOT/directory).glob('*'):
if path.is_file():
files[path.relative_to(ROOT).as_posix()] = path
if args.phase>=3:
for path in (ROOT/'models/embedding').rglob('*'):
if path.is_file() and path.suffix not in ('.py','.pyc'):
files[path.relative_to(ROOT).as_posix()] = path
for path in (ROOT/'knowledge').glob('*.md'):
files[path.relative_to(ROOT).as_posix()] = path
requirements = (ROOT/'deployment/zerogpu_phase1/requirements-space.txt').read_text(encoding='utf-8')
# The platform's unused preinstalled datasets 5 requires Hub <2. Gradio needs
# >=1.16; pin the compatible intersection rather than upgrading unrelated libs.
requirements = requirements.replace('huggingface-hub==2.2.0','huggingface-hub==1.31.0')
root_app = ("import os\nfrom pathlib import Path\n"
"os.environ['DEFECTRAG_SPACE_UI']=str(Path(__file__).parent/'frontend/dist')\n"
"os.environ['GRADIO_ANALYTICS_ENABLED']='False'\n"
f"os.environ['DEFECTRAG_LIVE_RAG']='{'1' if args.phase>=3 else '0'}'\n"
f"os.environ['DEFECTRAG_STAFF_BACKEND']='{'1' if args.phase>=4 else '0'}'\n"
"from deployment.space.app import server\n"
"server.launch(server_name='0.0.0.0',server_port=7860,ssr_mode=False,show_error=True,run_history=False)\n")
readme = (ROOT/'deployment/zerogpu_phase1/SPACE_README.md').read_text(encoding='utf-8')
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')
body = f'''\n# DefectRAG — migration phase {args.phase}\n
Existing React UI, real DINOv2 inspection across all 12 VisA categories with an
encoder fine-tuned on synthetic defects, 32,768-patch coreset normal-reference banks
and heatmaps, and normal-only decision thresholds. The q95 sensitivity policy trades
more false alarms for higher recall; one rule is used for every product.
Historical inspection decisions are preserved.
Anonymous browser history is isolated and temporary. Sign in to the configured
staff workspace for durable shared records when available. Do not treat anomaly
scores as probabilities or diagnoses. The operator selects the product category.
Gradio client requests use bounded GPU leases. Quotas and cold starts apply.
Local application and static showcase are preserved separately.
VisA: Amazon Science, CC BY 4.0, Zou et al., ECCV 2022.
DINOv2: Meta, Apache-2.0. See docs/THIRD_PARTY_NOTICES.md.
'''
raw = {'app.py':root_app.encode(),'requirements.txt':requirements.encode(),
'README.md':('---'+header+'---\n'+body).encode()}
assert not any(part in ('.env','runtime','node_modules','experiments','.venv') for name in files for part in Path(name).parts)
api = HfApi()
before = api.space_info(REPO)
assert api.get_space_runtime(REPO).requested_hardware=='zero-a10g'
# Deduplicate unchanged allowlisted files between phase commits.
state_file = OUT/'published-hashes.json'
previous = json.loads(state_file.read_text()) if state_file.exists() else {}
hashes = {name:hashlib.sha256(path.read_bytes()).hexdigest() for name,path in files.items()}
hashes.update({name:hashlib.sha256(value).hexdigest() for name,value in raw.items()})
operations = [CommitOperationAdd(path_in_repo=name,path_or_fileobj=frontend_bytes[name.removeprefix('frontend/dist/')] if name.startswith('frontend/dist/')
else path.read_bytes() if path.suffix in ('.py','.js','.json','.md','.html','.css','.svg') else path)
for name,path in files.items() if previous.get(name)!=hashes[name]]
operations += [CommitOperationAdd(path_in_repo=name,path_or_fileobj=value)
for name,value in raw.items() if previous.get(name)!=hashes[name]]
if checked_frontend()!=frontend:raise SystemExit('Frontend inputs changed before publication; rebuild and verify')
commit = api.create_commit(repo_id=REPO,repo_type='space',operations=operations,
parent_commit=before.sha,commit_message=f'DefectRAG phase {args.phase}: incremental real-model application migration')
state_file.write_text(json.dumps(hashes,indent=2))
receipt = {'phase':args.phase,'commit':commit.oid,'parent':before.sha,'changed_files':len(operations),'manifest':hashes}
(OUT/f'publish-phase{args.phase}.json').write_text(json.dumps(receipt,indent=2))
print(json.dumps({key:value for key,value in receipt.items() if key!='manifest'}))
if __name__=='__main__':
main()
|