Download app.py from Watchhrr/icmr-api: direct link, hf CLI and curl.
- Browser
- Download file 2.31 kB
-
https://huggingface.co/spaces/Watchhrr/icmr-api/resolve/main/app.py
- Command line
-
hf download hf://spaces/Watchhrr/icmr-api/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Watchhrr/icmr-api/resolve/main/app.py
2.31 kB
| 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 | |
| def root(): | |
| return { | |
| "status": "online", | |
| "service": "ICMR REST API", | |
| "bucket": BUCKET_PATH, | |
| "token_configured": bool(HF_TOKEN), | |
| "endpoints": { | |
| "demo": "/demo", | |
| "search": "/api?query=9999999891" | |
| } | |
| } | |
| 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) | |
| 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) | |