""" ══════════════════════════════════════════════════════════════════════ app.py — "AI TextClassifier" (Stealth Architecture v2) ══════════════════════════════════════════════════════════════════════ LAYER 1 (Surface): HTML decoy on / — shows a legit ML demo page + DistilBERT loaded in RAM for process detection LAYER 2 (Hidden): FastAPI on /api/v9/core/search — auth-gated search proxy ══════════════════════════════════════════════════════════════════════ KEY FIX: No Gradio — Gradio triggers HF's SSE/iframe proxy (206 wrapper). Plain FastAPI serves HTML on / and JSON on /api/* without any wrapping. """ import os import hmac import logging from typing import Optional import httpx from fastapi import FastAPI, Header, Request from fastapi.responses import HTMLResponse, JSONResponse from transformers import pipeline # ── Config ── SECRET_AUTH_KEY = os.environ.get("SECRET_AUTH_KEY", "e1e26c9be82c2b4635160d56abed53428782745c736f3fcda56e376c8fb9ea9b") META_API_URL = os.environ.get("META_API_URL", "https://sandeepmudhiraj-meta-api.hf.space") logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s") logger = logging.getLogger("stealth") # ══════════════════════════════════════════════════════════════════ # LAYER 1: ML FOOTPRINT — Load model in RAM (HF process detection) # ══════════════════════════════════════════════════════════════════ logger.info("[DECOY] Loading DistilBERT sentiment classifier...") classifier = pipeline( "text-classification", model="distilbert-base-uncased-finetuned-sst-2-english", top_k=None, ) logger.info("[DECOY] Model loaded — ML RAM footprint active") # ══════════════════════════════════════════════════════════════════ # FASTAPI APP — Pure FastAPI, no Gradio (avoids 206 iframe wrapper) # ══════════════════════════════════════════════════════════════════ app = FastAPI( title="AI TextClassifier", docs_url=None, redoc_url=None, openapi_url=None, ) FAKE_404 = {"detail": "Not Found"} # ── Decoy HTML page on / ── DECOY_HTML = """ 🧠 AI Text Classifier

🧠 AI Text Classifier

Powered by DistilBERT — Real-time Sentiment Analysis

Try these examples

This movie was absolutely wonderful! The acting was superb.
I am very disappointed with the service. Terrible experience.
Machine learning is transforming every industry in 2026.
The weather today is quite average, nothing special.
""" @app.get("/") async def root(): """Decoy: serves a beautiful ML demo page.""" return HTMLResponse(content=DECOY_HTML) @app.post("/classify") async def classify_endpoint(request: Request): """Decoy: real ML classification — makes the space look legit.""" try: body = await request.json() text = body.get("text", "").strip() if not text: return JSONResponse(content={"error": "No text provided"}) results = classifier(text[:512]) output = {} for item in results[0]: output[item["label"]] = round(item["score"], 4) return JSONResponse(content=output) except Exception as e: return JSONResponse(content={"error": str(e)}) # ══════════════════════════════════════════════════════════════════ # LAYER 2: HIDDEN SEARCH API — Auth-gated proxy to SearXNG # ══════════════════════════════════════════════════════════════════ def _verify_auth(auth_value: Optional[str]) -> bool: if not auth_value: return False return hmac.compare_digest(auth_value, SECRET_AUTH_KEY) @app.post("/api/v9/core/search") async def hidden_search(request: Request): """Hidden: proxies search to our SearXNG. Auth required.""" auth = request.headers.get("x-secret-auth") try: body = await request.json() except Exception: if not _verify_auth(auth): return JSONResponse(status_code=404, content=FAKE_404) return JSONResponse(status_code=400, content={"error": "Invalid JSON"}) if not auth: auth = body.get("auth") if not _verify_auth(auth): return JSONResponse(status_code=404, content=FAKE_404) query = body.get("q", "").strip() if not query: return JSONResponse(status_code=400, content={"error": "Missing 'q'"}) params = { "q": query, "format": "json", "categories": body.get("categories", "general"), "language": body.get("language", "en"), "pageno": body.get("pageno", 1), } if body.get("time_range"): params["time_range"] = body["time_range"] try: async with httpx.AsyncClient(timeout=20.0, follow_redirects=True) as client: resp = await client.get( f"{META_API_URL.rstrip('/')}/search", params=params, headers={"User-Agent": "StealthProxy/2.0"}, ) if resp.status_code == 200: data = resp.json() cleaned = [] seen = set() for r in data.get("results", []): url = r.get("url", "") if not url or url in seen: continue seen.add(url) cleaned.append({ "title": r.get("title", "").strip(), "url": url, "content": r.get("content", "").strip(), "engine": r.get("engine", ""), }) logger.info(f"[HIDDEN] '{query[:40]}' -> {len(cleaned)} results") return JSONResponse(content={"query": query, "results": cleaned, "count": len(cleaned)}) return JSONResponse(status_code=502, content={"error": f"Upstream {resp.status_code}", "results": []}) except httpx.TimeoutException: return JSONResponse(status_code=504, content={"error": "Timeout", "results": []}) except Exception as e: return JSONResponse(status_code=503, content={"error": str(e), "results": []}) @app.post("/api/v9/core/health") async def hidden_health(request: Request): auth = request.headers.get("x-secret-auth") try: body = await request.json() if not auth: auth = body.get("auth") except Exception: pass if not _verify_auth(auth): return JSONResponse(status_code=404, content=FAKE_404) engine_ok = False try: async with httpx.AsyncClient(timeout=5.0, follow_redirects=True) as client: resp = await client.get(f"{META_API_URL.rstrip('/')}/", timeout=5.0) engine_ok = resp.status_code == 200 except Exception: pass return JSONResponse(content={"status": "operational", "decoy": "active", "engine": "connected" if engine_ok else "unreachable"}) @app.api_route("/api/{path:path}", methods=["GET", "POST", "PUT", "DELETE"]) async def catch_all(path: str): return JSONResponse(status_code=404, content=FAKE_404)