Watchhrr commited on
Commit
1d4e97b
·
verified ·
1 Parent(s): 3bd7448

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +57 -11
main.py CHANGED
@@ -1,28 +1,74 @@
1
  import os
 
 
2
  import duckdb
3
  from fastapi import FastAPI, Query
 
4
 
5
- app = FastAPI()
6
  DB_PATH = "insta_hitech.duckdb"
 
7
 
8
- @app.on_event("startup")
9
- def check_db():
10
- if os.path.exists(DB_PATH):
11
- print(f"✅ Database found! Size: {os.path.getsize(DB_PATH)} bytes")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  else:
13
- print(" Database NOT found at startup!")
 
 
 
 
 
 
 
 
 
14
 
15
  @app.get("/search")
16
  async def search(q: str = Query(None)):
17
- if not q: return {"error": "Query missing"}
 
18
 
 
 
 
19
  conn = duckdb.connect(DB_PATH, read_only=True)
20
  try:
21
- res = conn.execute("SELECT * FROM users WHERE u = ? OR id = ? OR t = ?", [q, q, q]).df()
22
- if res.empty: return {"status": "error", "message": "No Record Found"}
 
 
 
 
 
 
 
 
 
23
 
24
- data = res.rename(columns={'t':'phone', 'u':'username', 'e':'email', 'n':'name', 'id':'user_id'}).to_dict(orient='records')
25
  return {"status": "success", "data": data}
 
 
26
  finally:
27
  conn.close()
28
-
 
 
 
 
1
  import os
2
+ import requests
3
+ import uvicorn
4
  import duckdb
5
  from fastapi import FastAPI, Query
6
+ from contextlib import asynccontextmanager
7
 
 
8
  DB_PATH = "insta_hitech.duckdb"
9
+ DB_URL = "https://huggingface.co/datasets/Watchhrr/Insta17m/resolve/main/insta_hitech.duckdb"
10
 
11
+ # Yahan humne secret variable ka naam use kiya hai jo aapne Settings mein dala tha
12
+ TOKEN = os.getenv("MY_HF_TOKEN")
13
+
14
+ # 1. Download Function
15
+ def download_db():
16
+ if not os.path.exists(DB_PATH):
17
+ print("📥 Database missing. Downloading from Dataset...")
18
+ if not TOKEN:
19
+ print("❌ Error: MY_HF_TOKEN not found in Secrets!")
20
+ return
21
+
22
+ headers = {"Authorization": f"Bearer {TOKEN}"}
23
+ try:
24
+ with requests.get(DB_URL, headers=headers, stream=True) as r:
25
+ r.raise_for_status()
26
+ with open(DB_PATH, 'wb') as f:
27
+ for chunk in r.iter_content(chunk_size=8192):
28
+ f.write(chunk)
29
+ print("✅ Download Complete!")
30
+ except Exception as e:
31
+ print(f"❌ Download Failed: {e}")
32
  else:
33
+ print(f" Database found! Size: {os.path.getsize(DB_PATH)} bytes")
34
+
35
+ # 2. Lifespan Handler
36
+ @asynccontextmanager
37
+ async def lifespan(app: FastAPI):
38
+ download_db()
39
+ yield
40
+ print("Shutting down...")
41
+
42
+ app = FastAPI(lifespan=lifespan)
43
 
44
  @app.get("/search")
45
  async def search(q: str = Query(None)):
46
+ if not q:
47
+ return {"error": "Query parameter 'q' is missing"}
48
 
49
+ if not os.path.exists(DB_PATH):
50
+ return {"error": "Database file not ready yet. Please wait a few minutes."}
51
+
52
  conn = duckdb.connect(DB_PATH, read_only=True)
53
  try:
54
+ # Smart search: username (u), id, and phone (t)
55
+ query = "SELECT * FROM users WHERE u = ? OR id = ? OR t = ?"
56
+ res = conn.execute(query, [q, q, q]).df()
57
+
58
+ if res.empty:
59
+ return {"status": "error", "message": "No Record Found"}
60
+
61
+ data = res.rename(columns={
62
+ 't':'phone', 'u':'username', 'e':'email',
63
+ 'n':'name', 'id':'user_id', 'a':'extra'
64
+ }).to_dict(orient='records')
65
 
 
66
  return {"status": "success", "data": data}
67
+ except Exception as e:
68
+ return {"status": "error", "message": str(e)}
69
  finally:
70
  conn.close()
71
+
72
+ if __name__ == "__main__":
73
+ uvicorn.run("main:app", host="0.0.0.0", port=7860)
74
+