Spaces:
Runtime error
Runtime error
Update app.py
#2
by Kzzr0x - opened
Files changed (5)
- Dockerfile+5-15
- README.md+7-29
- app.py+61-55
- pinger.py+8-22
- requirements.txt+2-2
1234567891011121314151617181920FROM python:3.11-slimRUN apt-get update && \apt-get install -y --no-install-recommends ca-certificates && \rm -rf /var/lib/apt/lists/*WORKDIR /appCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txtCOPY . .ENV PING_URL=http://127.0.0.1:7860/healthENV PING_INTERVAL=240ENV PYTHONUNBUFFERED=1EXPOSE 7860CMD ["sh", "-c", "python pinger.py & uvicorn app:app --host 0.0.0.0 --port 7860"]12345678910FROM python:3.9WORKDIR /codeCOPY ./requirements.txt /code/requirements.txtRUN pip install --no-cache-dir --upgrade -r /code/requirements.txtCOPY . .CMD ["sh", "-c", "python pinger.py & uvicorn app:app --host 0.0.0.0 --port 7860"]
12345678910111213141516171819202122232425262728293031---title: Fast Search APIemoji: ⚡colorFrom: bluecolorTo: purplesdk: dockerapp_port: 7860pinned: truelicense: mit---# Fast Search API (1.78B)- ⚡ **Mobile** → sorted `mobile` column (~2-3s)- 🆔 **Aadhaar** → `id` column as aadharNumber (unsorted, slow scan)## API```GET /search?q=<mobile>&limit=5GET /search?mobile=<number>GET /search?aadhar=<aadhaar>GET /healthGET /docs```## Source- DB: [tfqdeadlo/Inddatainonefile](https://huggingface.co/datasets/tfqdeadlo/Inddatainonefile)- Developer: @kzr0x- Team: TEAM DARK KNIGHT APIs123456789------title: ICMR FastAPI Searchemoji: 🚀colorFrom: yellowcolorTo: indigosdk: dockerpinned: false---
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283from fastapi import FastAPI, HTTPException, Queryimport duckdbfrom contextlib import asynccontextmanager# Global connection objectcon = duckdb.connect()# Lifespan use karke app start hote hi heavy initialization ek baar karenge@asynccontextmanagerasync def lifespan(app: FastAPI):print("DuckDB extensions load ho rahi hain aur View ban raha hai...")con.execute("INSTALL httpfs; LOAD httpfs;")# Parquet file ka correct URLPARQUET_URL = "https://huggingface.co/datasets/tfqdeadlo/Inddatainonefile/resolve/main/users_data.parquet"# Startup par hi Ek baar View bana kar metadata cache kar lete hain# Isse har API request par network par load nahi padegacon.execute(f"CREATE OR REPLACE VIEW users_view AS SELECT * FROM read_parquet('{PARQUET_URL}')")print("View taiyar hai! API requests ke liye taiyar hai.")yieldcon.close()app = FastAPI(title="Super Fast Search API", lifespan=lifespan)@app.get("/")def home():return {"message": "Fast API online hai! Use /search?mobile=YOUR_NUMBER"}@app.get("/health")def health():return {"status": "ok"}@app.get("/search")async def search_mobile(mobile: str | None = Query(None),q: str | None = Query(None),num: str | None = Query(None),number: str | None = Query(None),phone: str | None = Query(None),aadhar: str | None = Query(None),aadhaar: str | None = Query(None),):target = (q or mobile or num or number or phone or aadhar or aadhaar or "").strip()if not target:raise HTTPException(status_code=422, detail="Enter mobile number to search")try:# Mobile pehle (sorted, fast)query = """SELECT mobile, name, fname, address, alt, circle, id, emailFROM users_viewWHERE mobile = ?LIMIT 1"""result = con.execute(query, [str(target)]).fetchall()# 12-digit mobile pe na mile to id (aadhar) pe tryif not result and target.isdigit() and len(target) == 12:query2 = """SELECT mobile, name, fname, address, alt, circle, id, emailFROM users_viewWHERE id = ?LIMIT 1"""result = con.execute(query2, [str(target)]).fetchall()if not result:return {"status": "error","message": f"Mobile number {target} nahi mila."}# Data mappingcolumns = [desc[0] for desc in con.description]row_dict = dict(zip(columns, result[0]))return {"status": "success","data": row_dict}except Exception as e:# Internal error ko secure rakhne ke liye mask kiya hairaise HTTPException(status_code=500, detail="Query timeout ya process nahi ho payi.")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889from fastapi import FastAPI, HTTPException, Queryimport duckdbfrom contextlib import asynccontextmanagerfrom datetime import datetime, timedelta# === VALIDITY CHECK ===DEPLOYMENT_DATE = datetime(2026, 6, 27) # Tune aaj deploy kiya haiEXPIRY_DAYS = 21 # 3 weeksdef is_api_valid():return datetime.now() < DEPLOYMENT_DATE + timedelta(days=EXPIRY_DAYS)# Global Connectioncon = None@asynccontextmanagerasync def lifespan(app: FastAPI):global conprint("🟢 DuckDB initialize ho raha hai...")con = duckdb.connect()con.execute("PRAGMA memory_limit='800MB'")con.execute("PRAGMA threads=2")con.execute("SET enable_object_cache=true")con.execute("SET preserve_insertion_order=false")con.execute("INSTALL httpfs; LOAD httpfs;")URL_ICMR = "https://huggingface.co/datasets/kzropx/icmr-parquet/resolve/main/icmr.parquet"con.execute(f"SELECT 1 FROM read_parquet('{URL_ICMR}') LIMIT 1")print("🟢 DuckDB ready!")yieldcon.close()app = FastAPI(lifespan=lifespan)VALID_KEY = "@kzr0x"@app.get("/")def home(key: str = Query(..., description="API Key required")):if not is_api_valid():return {"status": "error", "message": "API Expired! Valid only for 3 weeks from 27-June-2026."}if key != VALID_KEY:return {"status": "error", "message": "Invalid API key"}return {"status": "success", "message": "API Live! Use /search"}@app.get("/search")async def search_data(key: str = Query(..., description="API Key required"),number: str = Query(None, description="Search by Phone Number"),aadhar: str = Query(None, description="Search by Aadhar Number"),q: str = Query(None, description="Generic search")):# === EXPIRY CHECK (SAB SE PEHLE) ===if not is_api_valid():return {"status": "error", "message": "This API has expired. Valid only for 3 weeks (till 18-July-2026)."}if key != VALID_KEY:return {"status": "error", "message": "Invalid or missing API key"}if not number and not aadhar and not q:raise HTTPException(status_code=400, detail="Provide number, aadhar, or q")search_term = q or number or aadharURL_ICMR = "https://huggingface.co/datasets/kzropx/icmr-parquet/resolve/main/icmr.parquet"try:query = f"""SELECT name, fathersName, phoneNumber, aadharNumber, address, district, pincode, state, townFROM read_parquet('{URL_ICMR}')WHERE phoneNumber = ? OR aadharNumber = ?LIMIT 1"""result = con.execute(query, [search_term, search_term]).fetchall()if not result:return {"status": "error","message": f"'{search_term}' not found.","developer": {"name": "@kzr0x", "team": "TEAM DARK KNIGHT APIs"}}columns = [desc[0] for desc in con.description]return {"status": "success","data": dict(zip(columns, result[0])),"developer": {"name": "@kzr0x", "team": "TEAM DARK KNIGHT APIs"}}except Exception as e:return {"status": "error", "message": str(e)}
1234567891011121314151617181920212223242526"""Keep-alive pinger: pings the Space's /health endpoint every few minutesso the container doesn't sleep. Runs as a background process inside the Space(started from Dockerfile CMD)."""import osimport timeimport requestsPORT = os.environ.get("APP_PORT", "7860")URL = os.environ.get("PING_URL", f"http://127.0.0.1:{PORT}/health")INTERVAL = int(os.environ.get("PING_INTERVAL", "240"))def _ping_loop():while True:try:r = requests.get(URL, timeout=10)print(f"[pinger] {URL} -> {r.status_code}", flush=True)except Exception as e:print(f"[pinger] error: {e}", flush=True)time.sleep(INTERVAL)if __name__ == "__main__":print(f"[pinger] starting, target={URL} interval={INTERVAL}s", flush=True)_ping_loop()123456789101112import timeimport requestsURL = "https://kzropx-icmr-data.hf.space"while True:try:requests.get(URL)print(f"Pinged {URL} successfully!")except Exception as e:print(f"Error: {e}")time.sleep(300)
1234fastapiduckdb==1.5.3uvicornrequests1234fastapiduckdbuvicornrequests
Dockerfile+5-15
README.md+7-29
app.py+61-55
pinger.py+8-22
requirements.txt+2-2