Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FastAPI backend over DuckDB - Flipkart Dataset."""
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import threading
|
| 5 |
+
import traceback
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import duckdb
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pandas as pd
|
| 11 |
+
from fastapi import FastAPI, Query, Response
|
| 12 |
+
|
| 13 |
+
# Flipkart Dataset Path
|
| 14 |
+
HF_FILE = "hf://datasets/HiTeckGroup/Flipkart@main/*.parquet"
|
| 15 |
+
HF_TOKEN = os.environ.get("HF_TOKEN", "")
|
| 16 |
+
|
| 17 |
+
# 🔑 API KEY
|
| 18 |
+
API_KEY = os.environ.get("API_KEY_1", "")
|
| 19 |
+
VALID_KEYS = {}
|
| 20 |
+
if API_KEY:
|
| 21 |
+
VALID_KEYS[API_KEY] = {}
|
| 22 |
+
|
| 23 |
+
app = FastAPI(title="Flipkart Search API")
|
| 24 |
+
|
| 25 |
+
_conn = None
|
| 26 |
+
_conn_lock = threading.Lock()
|
| 27 |
+
|
| 28 |
+
def _get_conn() -> duckdb.DuckDBPyConnection:
|
| 29 |
+
global _conn
|
| 30 |
+
if _conn is not None:
|
| 31 |
+
return _conn
|
| 32 |
+
with _conn_lock:
|
| 33 |
+
if _conn is not None:
|
| 34 |
+
return _conn
|
| 35 |
+
con = duckdb.connect()
|
| 36 |
+
con.execute("INSTALL httpfs; LOAD httpfs;")
|
| 37 |
+
con.execute("INSTALL parquet; LOAD parquet;")
|
| 38 |
+
if HF_TOKEN:
|
| 39 |
+
con.execute(f"SET http_headers = {{'Authorization': 'Bearer {HF_TOKEN}'}};")
|
| 40 |
+
|
| 41 |
+
# Speed settings
|
| 42 |
+
con.execute("SET enable_http_metadata_cache = true;")
|
| 43 |
+
con.execute("SET http_keep_alive = true;")
|
| 44 |
+
con.execute("SET http_timeout = 600000;")
|
| 45 |
+
con.execute("SET threads = 4;")
|
| 46 |
+
|
| 47 |
+
_conn = con
|
| 48 |
+
print("🌐 DuckDB ready (Flipkart API)", flush=True)
|
| 49 |
+
return con
|
| 50 |
+
|
| 51 |
+
def _check_key(key: str | None) -> tuple[bool, dict | None]:
|
| 52 |
+
if not key or key not in VALID_KEYS:
|
| 53 |
+
return False, {"message": "Provide correct key", "contact": "@dmforbans"}
|
| 54 |
+
return True, VALID_KEYS[key]
|
| 55 |
+
|
| 56 |
+
def _pretty(data: dict[str, Any], pretty: bool = True) -> Response:
|
| 57 |
+
if pretty:
|
| 58 |
+
return Response(content=json.dumps(data, indent=2, ensure_ascii=False), media_type="application/json")
|
| 59 |
+
return Response(content=json.dumps(data, ensure_ascii=False), media_type="application/json")
|
| 60 |
+
|
| 61 |
+
@app.on_event("startup")
|
| 62 |
+
async def startup_event():
|
| 63 |
+
try:
|
| 64 |
+
_get_conn()
|
| 65 |
+
except Exception as e:
|
| 66 |
+
print(f"Startup failed: {e}", flush=True)
|
| 67 |
+
|
| 68 |
+
@app.get("/")
|
| 69 |
+
def home():
|
| 70 |
+
return {"app": "Flipkart Search API", "status": "active", "contact": "@dmforbans"}
|
| 71 |
+
|
| 72 |
+
@app.get("/search")
|
| 73 |
+
async def search(
|
| 74 |
+
key: str = Query(..., description="API Key"),
|
| 75 |
+
phone: str = Query(None, description="Search by Phone (10 digit)"),
|
| 76 |
+
email: str = Query(None, description="Search by Email"),
|
| 77 |
+
pretty: bool = Query(True)
|
| 78 |
+
):
|
| 79 |
+
valid, err = _check_key(key)
|
| 80 |
+
if not valid:
|
| 81 |
+
return Response(content=json.dumps(err, ensure_ascii=False), status_code=403, media_type="application/json")
|
| 82 |
+
|
| 83 |
+
if not phone and not email:
|
| 84 |
+
return Response(content=json.dumps({"message": "Provide phone or email", "contact": "@dmforbans"}), status_code=400, media_type="application/json")
|
| 85 |
+
|
| 86 |
+
if phone and (not phone.isdigit() or len(phone) != 10):
|
| 87 |
+
return Response(content=json.dumps({"message": "Provide valid 10 digit phone", "contact": "@dmforbans"}), status_code=400, media_type="application/json")
|
| 88 |
+
|
| 89 |
+
try:
|
| 90 |
+
con = _get_conn()
|
| 91 |
+
query = "SELECT * FROM read_parquet(?) WHERE 1=1"
|
| 92 |
+
params = [HF_FILE]
|
| 93 |
+
|
| 94 |
+
if phone:
|
| 95 |
+
query += " AND CAST(CustomerPhone AS VARCHAR) = ?"
|
| 96 |
+
params.append(phone)
|
| 97 |
+
if email:
|
| 98 |
+
query += " AND CAST(CustomerEmail AS VARCHAR) ILIKE ?"
|
| 99 |
+
params.append(f"%{email}%")
|
| 100 |
+
|
| 101 |
+
query += " LIMIT 50"
|
| 102 |
+
df = con.execute(query, params).fetchdf()
|
| 103 |
+
|
| 104 |
+
if df is None or df.empty:
|
| 105 |
+
return _pretty({"found": 0, "data": [], "developer": "@dmforbans"}, pretty)
|
| 106 |
+
|
| 107 |
+
df = df.replace([np.inf, -np.inf], np.nan)
|
| 108 |
+
df = df.where(pd.notnull(df), None)
|
| 109 |
+
records = df.to_dict(orient="records")
|
| 110 |
+
|
| 111 |
+
return _pretty({"found": len(records), "data": records, "developer": "@dmforbans"}, pretty)
|
| 112 |
+
|
| 113 |
+
except Exception:
|
| 114 |
+
traceback.print_exc()
|
| 115 |
+
return Response(content=json.dumps({"found": 0, "data": [], "message": "Data not found"}), status_code=500, media_type="application/json")
|