File size: 2,307 Bytes
78a17c2 155ede9 78a17c2 84e3a36 78a17c2 84e3a36 78a17c2 554d4e5 78a17c2 554d4e5 78a17c2 155ede9 78a17c2 155ede9 78a17c2 155ede9 78a17c2 155ede9 78a17c2 554d4e5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | import os
import traceback
import duckdb
from fastapi import FastAPI, Query, HTTPException
from huggingface_hub import HfFileSystem
import uvicorn
app = FastAPI(title="ICMR Dataset API")
BUCKET_PATH = "hf://buckets/Watchhrr/num/users_data.parquet"
HF_TOKEN = os.getenv("HF_TOKEN")
def get_db_connection():
conn = duckdb.connect(database=":memory:")
conn.execute("PRAGMA threads=2;")
conn.execute("PRAGMA memory_limit='10GB';")
fs = HfFileSystem(token=HF_TOKEN)
conn.register_filesystem(fs)
return conn
@app.get("/")
def root():
return {
"status": "online",
"service": "ICMR REST API",
"bucket": BUCKET_PATH,
"token_configured": bool(HF_TOKEN),
"endpoints": {
"demo": "/demo",
"search": "/api?query=9999999891"
}
}
@app.get("/demo")
def demo():
try:
conn = get_db_connection()
sql = f"SELECT * FROM read_parquet('{BUCKET_PATH}') LIMIT 5"
res = conn.execute(sql).fetchdf()
return {
"status": "success",
"count": len(res),
"data": res.fillna("").to_dict(orient="records")
}
except Exception as e:
err_msg = traceback.format_exc()
print(err_msg)
raise HTTPException(status_code=500, detail=str(e) + " || Traceback: " + err_msg)
@app.get("/api")
def search_db(query: str = Query(..., min_length=3)):
clean_q = query.strip()
try:
conn = get_db_connection()
sql = f"""
SELECT * FROM read_parquet('{BUCKET_PATH}')
WHERE TRIM(CAST(mobile AS VARCHAR)) = ?
OR TRIM(CAST(alt AS VARCHAR)) = ?
OR TRIM(CAST(id AS VARCHAR)) = ?
LIMIT 50
"""
res = conn.execute(sql, [clean_q, clean_q, clean_q]).fetchdf()
records = res.fillna("").to_dict(orient="records")
return {
"status": "success",
"query": clean_q,
"count": len(records),
"data": records
}
except Exception as e:
err_msg = traceback.format_exc()
print(err_msg)
raise HTTPException(status_code=500, detail=str(e) + " || Traceback: " + err_msg)
if __name__ == "__main__":
uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=False)
|