"""Apply additive migrations before serving the Space backend.""" import os import subprocess import sys import time import redis for attempt in range(30): try: redis.Redis.from_url(os.environ['REDIS_URL'], socket_connect_timeout=2).ping() break except redis.RedisError: time.sleep(1) else: raise SystemExit('Redis startup failed') subprocess.run([sys.executable, '-m', 'alembic', 'upgrade', 'head'], check=True) # Read-only model discovery: no inference or billing, never prints credentials. try: sys.path.insert(0, os.getcwd()) from src.services.image_generation import cloudflare_image_ready from src.services.ai_router import TextProvider import json if cloudflare_image_ready(): from src.services.image_gateway import public_key, health_check from src.config import settings print(json.dumps({'event':'image.gateway_public_key','public_key':public_key()}), flush=True) image_health = (health_check() if settings.cloudflare_image_gateway_url else TextProvider('cloudflare', '@cf/black-forest-labs/flux-1-schnell').healthCheck()) print(json.dumps({'event':'image.provider_health','provider':'cloudflare','available':image_health['available'],'reason':image_health['reason'],'http_status':image_health.get('http_status'),'error_codes':image_health.get('error_codes',[]),'error_kind':image_health.get('error_kind'),'network_cause':image_health.get('network_cause'),'network_errno':image_health.get('network_errno'),'verify_code':image_health.get('verify_code'),'ipv4_required':image_health.get('ipv4_required',False)}), flush=True) if image_health['reason'] == 'authentication': import httpx from src.config import settings # Read-only token verification distinguishes invalid token from wrong # account scope/permissions. No token, account ID or error text is logged. for token_kind, verify_path in [('user','/user/tokens/verify'),('account','/accounts/'+settings.cloudflare_account_id+'/tokens/verify')]: try: response = httpx.get('https://api.cloudflare.com/client/v4'+verify_path,headers={'Authorization':'Bearer '+settings.cloudflare_api_token.strip()},timeout=5) body = response.json() token_status = (body.get('result') or {}).get('status') print(json.dumps({'event':'image.token_verification','token_kind':token_kind,'http_status':response.status_code,'active':bool(response.is_success and body.get('success') is True and token_status == 'active')}),flush=True) if response.is_success and token_status == 'active': break except Exception: print(json.dumps({'event':'image.token_verification','token_kind':token_kind,'result':'unavailable'}),flush=True) else: print('Image provider: Hugging Face; free Cloudflare configuration unavailable', flush=True) except Exception as exc: print('Image provider preflight unavailable ('+type(exc).__name__+'); app startup continues', flush=True) os.execvp('uvicorn', ['uvicorn', 'src.main:app', '--host', '0.0.0.0', '--port', '8000', '--workers', '1', '--no-access-log'])