""" Sahih Islam SuperAdmin API (Hugging Face Space - Gradio SDK) FastAPI Backend running natively on Hugging Face Spaces without Docker. Configured for ZeroGPU and CPU hardware compatibility. """ import os os.environ["GRADIO_SSR_MODE"] = "False" # Deployment environment resolution: # Production environments (Hugging Face Spaces, Docker production) must not silently default to test mode. if "APP_ENV" not in os.environ: if os.getenv("SPACE_ID") or os.getenv("HUGGINGFACE_SERVER") or os.getenv("HF_SPACE_ID"): os.environ["APP_ENV"] = "closed_testing" else: os.environ["APP_ENV"] = "closed_testing" import logging import asyncio from fastapi.middleware.cors import CORSMiddleware from slowapi.errors import RateLimitExceeded from slowapi import _rate_limit_exceeded_handler from app.limiter import limiter from app.core.config import settings # ------------------------------------------------------------- # ZeroGPU Support for Hugging Face Spaces # ------------------------------------------------------------- # When a Space is assigned ZeroGPU hardware (zero-a10g), Hugging Face # requires at least one module-level function decorated with @spaces.GPU # during startup. We provide a safe, high-availability wrapper here. # ------------------------------------------------------------- try: import spaces HAS_SPACES = True except ImportError: HAS_SPACES = False try: import torch except ImportError: torch = None if HAS_SPACES: @spaces.GPU def zero_gpu_compute_node(query: str = "ping") -> str: """ ZeroGPU Compute Worker. Decorated with @spaces.GPU to satisfy Hugging Face ZeroGPU runtime supervisor. """ hardware_info = "ZeroGPU Cluster Attached" if torch is not None and torch.cuda.is_available(): try: hardware_info = f"NVIDIA GPU: {torch.cuda.get_device_name(0)}" except Exception: hardware_info = "NVIDIA CUDA Device Active" return f"Operational: {hardware_info} | Query: {query}" else: def zero_gpu_compute_node(query: str = "ping") -> str: return f"Operational: Standard CPU Host | Query: {query}" # ------------------------------------------------------------- # Hugging Face Hub Compatibility Shim # Fixes 'cannot import name HfFolder from huggingface_hub' # ------------------------------------------------------------- try: import huggingface_hub if not hasattr(huggingface_hub, "HfFolder"): class _HfFolderShim: @staticmethod def get_token(): return os.environ.get("HF_TOKEN") @staticmethod def save_token(token): pass @staticmethod def delete_token(): pass huggingface_hub.HfFolder = _HfFolderShim except Exception: pass try: import gradio as gr except ImportError: gr = None # Configure logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) # Import routes and collections from app.superadmin_routes import router as superadmin_router from app.auth import router as auth_router try: from app.masjid_routes import router as masjid_router except Exception: masjid_router = None try: from app.hadith import router as hadith_router except Exception: hadith_router = None try: from app.ads_routes import router as ads_router except Exception: ads_router = None try: from app.payment_routes import router as payment_router except Exception: payment_router = None try: from app.tafsir_routes import router as tafsir_router, quran_pdf_router except Exception: tafsir_router = None quran_pdf_router = None try: from app.r2_routes import router as r2_router except Exception as e: r2_router = None try: from app.mufti_routes import router as mufti_router except Exception: mufti_router = None try: from app.events_routes import router as events_router except Exception: events_router = None try: from app.api.razorpay_standard import router as razorpay_standard_router except Exception: razorpay_standard_router = None try: from app.shop_routes import router as shop_router except Exception: shop_router = None from app.database import sendads_collection class UploadSizeLimiterMiddleware: """ ASGI middleware enforcing strict upload size limits before multipart spooling (P2-UP-01). Rejects payload early if Content-Length exceeds limit or received stream exceeds limit. """ def __init__(self, app, max_upload_bytes: int = 500 * 1024): self.app = app self.max_upload_bytes = max_upload_bytes async def __call__(self, scope, receive, send): if scope["type"] != "http": return await self.app(scope, receive, send) headers = dict(scope.get("headers", [])) content_type = headers.get(b"content-type", b"").decode("latin-1").lower() path = scope.get("path", "").lower() # Check upload endpoints or multipart requests is_upload = ( "multipart/form-data" in content_type or "/upload" in path or "/image" in path ) if is_upload and scope.get("method", "").upper() in ("POST", "PUT", "PATCH"): cl_header = headers.get(b"content-length") if cl_header: try: content_length = int(cl_header.decode("latin-1")) if content_length > self.max_upload_bytes: response_body = b'{"detail": "Upload size exceeds 500 KB limit"}' await send({ "type": "http.response.start", "status": 413, "headers": [ (b"content-type", b"application/json"), (b"content-length", str(len(response_body)).encode("latin-1")), ], }) await send({ "type": "http.response.body", "body": response_body, }) return except ValueError: pass received_bytes = 0 async def custom_receive(): nonlocal received_bytes message = await receive() if message["type"] == "http.request": body = message.get("body", b"") received_bytes += len(body) if received_bytes > self.max_upload_bytes: from fastapi import HTTPException raise HTTPException(status_code=413, detail="Upload size exceeds 500 KB limit") return message try: return await self.app(scope, custom_receive, send) except Exception as exc: if getattr(exc, "status_code", None) == 413 or "413" in str(exc): response_body = b'{"detail": "Upload size exceeds 500 KB limit"}' await send({ "type": "http.response.start", "status": 413, "headers": [ (b"content-type", b"application/json"), (b"content-length", str(len(response_body)).encode("latin-1")), ], }) await send({ "type": "http.response.body", "body": response_body, }) return raise return await self.app(scope, receive, send) def _register_routes(fastapi_app): """Mounts CORS, SuperAdmin routes, auth routes, health check, and ad config onto the FastAPI app.""" from app.core.config import settings if getattr(fastapi_app.state, "superadmin_routes_mounted", False): return fastapi_app.state.superadmin_routes_mounted = True # Centralized configuration validation (SI-SEC-005, NEW-009) try: settings.validate() except Exception as e: if settings.IS_PROD or settings.IS_STAGING: logger.critical(f"FATAL: Production/Staging configuration validation failed: {e}") raise RuntimeError(f"FATAL: Configuration validation failed: {e}") from e logger.warning(f"Configuration Validation Notice: {e}") # Register rate limiter on fastapi_app fastapi_app.state.limiter = limiter fastapi_app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler) @fastapi_app.on_event("startup") async def _on_startup(): try: settings.validate() except Exception as e: if settings.IS_PROD or settings.IS_STAGING: logger.critical(f"FATAL: Startup configuration validation failed: {e}") raise RuntimeError(f"FATAL: Startup configuration validation failed: {e}") from e logger.warning(f"Startup configuration validation notice: {e}") try: from app.infrastructure.mongodb import init_db_indexes await init_db_indexes() logger.info("✅ MongoDB Indexes Initialized via startup hook.") except Exception as e: logger.warning(f"Note on MongoDB index initialization: {e}") try: from app.infrastructure.redis import redis_manager await redis_manager.init() logger.info("✅ Upstash Redis Manager Initialized via startup hook.") except Exception as e: logger.warning(f"Note on Redis initialization: {e}") try: from app.payment_routes import reconcile_unapplied_wallet_transactions reconciled = await reconcile_unapplied_wallet_transactions() if reconciled: logger.info(f"✅ Reconciled {len(reconciled)} unapplied wallet transaction(s) on startup.") except Exception as e: logger.warning(f"Note on wallet reconciliation startup: {e}") try: from app.superadmin_routes import start_account_deletion_worker asyncio.create_task(start_account_deletion_worker()) logger.info("✅ Automated Account Deletion Background Task Started.") except Exception as e: logger.warning(f"Note on Account Deletion Worker startup: {e}") try: from app.services.daily_content.coordinator import daily_coordinator asyncio.create_task(daily_coordinator.start_scheduler()) logger.info("Daily Content Coordinator (12:00 AM Asia/Kolkata) scheduler started.") except Exception as e: logger.warning(f"Note on Daily Content Coordinator startup: {e}") logger.info("Mounting CORS, SuperAdmin routes, Auth routes, /health, and /ads/config onto FastAPI application...") # Dynamic regex CORS matching (NEW-020) if not settings.IS_PROD: cors_regex = r"^https?://(localhost|127\.0\.0\.1|10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}|192\.168\.[0-9]{1,3}\.[0-9]{1,3})(:[0-9]+)?$" elif bool(os.getenv("SPACE_ID") or os.getenv("SPACE_AUTHOR_NAME") or os.getenv("SYSTEM") == "spaces"): cors_regex = r"^https://[a-zA-Z0-9_-]+\.hf\.space$" else: cors_regex = None fastapi_app.add_middleware( CORSMiddleware, allow_origins=settings.ALLOWED_ORIGINS, allow_origin_regex=cors_regex, allow_credentials=True, allow_methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"], allow_headers=["*"], expose_headers=["Content-Length", "Content-Type", "X-Request-ID"], max_age=600, ) fastapi_app.add_middleware(UploadSizeLimiterMiddleware, max_upload_bytes=500 * 1024) # 1. SuperAdmin Control Panel endpoints (/admin/...) fastapi_app.include_router(superadmin_router, prefix="/admin", tags=["SuperAdmin Control Panel"]) # 1b. Razorpay Standard Web Checkout if razorpay_standard_router is not None: fastapi_app.include_router(razorpay_standard_router, tags=["Razorpay Standard Web Checkout"]) # 1c. Contact Form & Believer Support (SI-SEC-017) try: from app.api.contact import router as contact_router fastapi_app.include_router(contact_router, tags=["Contact & Believer Support"]) except Exception as e: logger.warning(f"Could not mount contact_router in app.py: {e}") # 1d. API v1 Unified Routes (/api/v1/...) try: from app.api.v1 import v1_router fastapi_app.include_router(v1_router, prefix="/api", tags=["API v1"]) except Exception as e: logger.warning(f"Could not mount v1_router in app.py: {e}") # 2. Authentication & Profile endpoints (/auth/...) fastapi_app.include_router(auth_router, prefix="/auth", tags=["Authentication & Profile"]) # 3. Masjid endpoints (/masjid/...) if masjid_router is not None: fastapi_app.include_router(masjid_router, prefix="/masjid", tags=["Masjids"]) # 4. Hadith & Daily content endpoints (/api/...) if hadith_router is not None: fastapi_app.include_router(hadith_router, prefix="/api", tags=["Hadith & AI Engine"]) # 5. Ad delivery endpoints (/ads/...) if ads_router is not None: fastapi_app.include_router(ads_router) # 6. Payment & Subscription endpoints (/payment/...) # Note: payment_router already has prefix="/payment" defined on router. # Mounting without an additional prefix avoids duplicate /payment/payment routes. if payment_router is not None: fastapi_app.include_router(payment_router, tags=["Payment & Wallet Engine"]) # 7. Tafsir & Quran PDF Library endpoints (/api/...) if tafsir_router is not None: fastapi_app.include_router(tafsir_router, prefix="/api", tags=["Tafsir Engine"]) if quran_pdf_router is not None: fastapi_app.include_router(quran_pdf_router, prefix="/api", tags=["Quran PDF Library"]) if r2_router is not None: fastapi_app.include_router(r2_router, prefix="/api", tags=["Cloudflare R2 Assets"]) # 8. Events & Mufti if events_router is not None: fastapi_app.include_router(events_router, tags=["Events"]) if mufti_router is not None: fastapi_app.include_router(mufti_router, prefix="/mufti", tags=["Mufti Verification"]) if shop_router is not None: fastapi_app.include_router(shop_router, tags=["Marketplace & Shop"]) has_health = any(getattr(r, "path", None) == "/health" for r in getattr(fastapi_app, "routes", [])) if not has_health: @fastapi_app.get("/health") async def health_check(): return { "status": "healthy", "service": "superadmin-backend", "version": "1.0.0" } @fastapi_app.get("/ads/config") async def get_public_ads_config(): try: config = await sendads_collection.find_one({"_id": "global_ad_config"}) if not config: return { "status": "ok", "ads_enabled": True, "real_ads_enabled": False, "min_seconds_between_ads": 180, "content_rating": "G", "banner_ads_enabled": False, "home_ads": True, "chat_ads": True, "hadith_ads": True, "tafsir_ads": True, "qaza_ads": True, } return { "status": "ok", "ads_enabled": config.get("ads_enabled", True), "real_ads_enabled": config.get("real_ads_enabled", False), "min_seconds_between_ads": config.get("min_seconds_between_ads", 180), "content_rating": config.get("content_rating", "G"), "banner_ads_enabled": config.get("banner_ads_enabled", False), "home_ads": config.get("home_ads", True), "chat_ads": config.get("chat_ads", True), "hadith_ads": config.get("hadith_ads", True), "tafsir_ads": config.get("tafsir_ads", True), "qaza_ads": config.get("qaza_ads", True), "instant_ad": config.get("instant_ad"), "updated_at": config.get("updated_at") } except Exception: return { "status": "ok", "ads_enabled": True, "real_ads_enabled": False, "min_seconds_between_ads": 180, "content_rating": "G", "banner_ads_enabled": False, "home_ads": True, "chat_ads": True, "hadith_ads": True, "tafsir_ads": True, "qaza_ads": True, } # Hook gr.routes.App.create_app so our routes are embedded inside demo.launch() try: if hasattr(gr, "routes") and hasattr(gr.routes, "App") and hasattr(gr.routes.App, "create_app"): _original_create_app = gr.routes.App.create_app def _custom_create_app(*args, **kwargs): app = _original_create_app(*args, **kwargs) _register_routes(app) return app gr.routes.App.create_app = _custom_create_app logger.info("Successfully hooked gr.routes.App.create_app for seamless FastAPI route injection.") except Exception as e: logger.warning(f"Could not hook gr.routes.App.create_app: {e}") demo = None if gr is not None: # Build Gradio Status Dashboard for visual monitoring on Hugging Face with gr.Blocks(title="Sahih Islam SuperAdmin API", theme=gr.themes.Soft()) as demo: gr.Markdown("# 🕌 Sahih Islam SuperAdmin API Server") gr.Markdown("### ✅ Status: **ONLINE & OPERATIONAL** (Hugging Face Gradio SDK)") gr.Markdown(""" This Space hosts the SuperAdmin backend for **Sahih Islam**. #### 🚀 Quick Links: - **Interactive API Docs (Swagger)**: [/docs](/docs) - **ReDoc Documentation**: [/redoc](/redoc) - **Health Probe**: [/health](/health) - **Remote Ad Config Endpoint**: [/ads/config](/ads/config) - **SuperAdmin Routes**: `/admin/...` #### 🛡️ Authentication: All `/admin/*` operations require a valid Firebase ID Token with SuperAdmin privileges. """) # Interactive diagnostics connected to @spaces.GPU with gr.Accordion("⚡ Compute & ZeroGPU Hardware Status", open=False): status_input = gr.Textbox(label="Test Input", value="Ping") status_btn = gr.Button("Inspect GPU Compute Node") status_output = gr.Textbox(label="Compute Node Response") status_btn.click(fn=zero_gpu_compute_node, inputs=status_input, outputs=status_output) # Also attempt to register on demo.app if already instantiated if hasattr(demo, "app") and demo.app: _register_routes(demo.app) # Launch the Gradio app and keep the main process alive permanently if __name__ == "__main__": if demo is not None: logger.info("Starting SuperAdmin API Server via demo.launch()...") demo.launch(server_name="0.0.0.0", server_port=7860) else: logger.info("Starting SuperAdmin API Server via uvicorn...") import uvicorn from fastapi import FastAPI standalone_app = FastAPI(title="Sahih Islam SuperAdmin API") _register_routes(standalone_app) uvicorn.run(standalone_app, host="0.0.0.0", port=7860) # Keep the server thread active permanently on Hugging Face Spaces (prevents exit) import time while True: time.sleep(3600)