Watchhrr commited on
Commit
a2d098d
·
verified ·
1 Parent(s): 658f8a6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -16
app.py CHANGED
@@ -1,39 +1,74 @@
1
  import os
2
  import sqlite3
 
3
  from fastapi import FastAPI
 
4
 
5
  app = FastAPI()
 
 
 
6
  DB_PATH = "Telegram_Master_DB.db"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
  @app.get("/search")
9
  def search(q: str = None):
10
  if not os.path.exists(DB_PATH):
11
- return {"error": "DB File Not Found"}
12
 
 
 
 
13
  try:
14
  conn = sqlite3.connect(DB_PATH)
15
  conn.row_factory = sqlite3.Row
16
  cursor = conn.cursor()
17
 
18
- # 1. Table ka naam check karo
19
  cursor.execute("SELECT name FROM sqlite_master WHERE type='table' LIMIT 1;")
20
  table = cursor.fetchone()
21
- t_name = table[0] if table else "No Table Found"
 
22
 
23
- # 2. Columns ke naam check karo
24
  cursor.execute(f"PRAGMA table_info({t_name})")
25
  cols = [c[1] for c in cursor.fetchall()]
26
-
27
- # 3. Pehli 5 rows nikal lo dekhne ke liye
28
- cursor.execute(f"SELECT * FROM {t_name} LIMIT 5")
29
- samples = [dict(row) for row in cursor.fetchall()]
30
 
 
 
31
  conn.close()
32
- return {
33
- "table_name": t_name,
34
- "columns": cols,
35
- "sample_data": samples,
36
- "total_rows_expected": "6.8M"
37
- }
38
- except Exception as e:
39
- return {"error": str(e)}
 
1
  import os
2
  import sqlite3
3
+ import requests
4
  from fastapi import FastAPI
5
+ from fastapi.middleware.cors import CORSMiddleware
6
 
7
  app = FastAPI()
8
+ app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
9
+
10
+ # --- CONFIG (Ab ekdum secure hai) ---
11
  DB_PATH = "Telegram_Master_DB.db"
12
+ DB_URL = "https://huggingface.co/datasets/Watchhrr/Telegram/resolve/main/Telegram_Master_DB.db"
13
+
14
+ # Settings se token uthayega, code mein dikhega nahi
15
+ HF_TOKEN = os.getenv("HF_TOKEN")
16
+
17
+ def download_database():
18
+ if not os.path.exists(DB_PATH):
19
+ print("⏳ DB file missing. Starting secure download...")
20
+ if not HF_TOKEN:
21
+ print("❌ Error: HF_TOKEN setting mein nahi mila!")
22
+ return
23
+
24
+ headers = {"Authorization": f"Bearer {HF_TOKEN}"}
25
+ try:
26
+ r = requests.get(DB_URL, headers=headers, stream=True)
27
+ if r.status_code == 200:
28
+ with open(DB_PATH, 'wb') as f:
29
+ for chunk in r.iter_content(chunk_size=1024*1024):
30
+ f.write(chunk)
31
+ print("✅ Download Complete!")
32
+ else:
33
+ print(f"❌ Download Failed! Status: {r.status_code}")
34
+ except Exception as e:
35
+ print(f"❌ Error during download: {e}")
36
+
37
+ @app.on_event("startup")
38
+ async def startup_event():
39
+ download_database()
40
 
41
  @app.get("/search")
42
  def search(q: str = None):
43
  if not os.path.exists(DB_PATH):
44
+ return {"status": "error", "message": "Database is loading... Try again in 1 minute."}
45
 
46
+ if not q:
47
+ return {"status": "error", "message": "Not Found"}
48
+
49
  try:
50
  conn = sqlite3.connect(DB_PATH)
51
  conn.row_factory = sqlite3.Row
52
  cursor = conn.cursor()
53
 
54
+ # Automatic Table Detection
55
  cursor.execute("SELECT name FROM sqlite_master WHERE type='table' LIMIT 1;")
56
  table = cursor.fetchone()
57
+ if not table: return {"status": "error", "message": "Not Found"}
58
+ t_name = table[0]
59
 
60
+ # Universal Search across all columns
61
  cursor.execute(f"PRAGMA table_info({t_name})")
62
  cols = [c[1] for c in cursor.fetchall()]
63
+ conditions = [f"CAST({c} AS TEXT) LIKE ?" for c in cols]
64
+ query = f"SELECT * FROM {t_name} WHERE {' OR '.join(conditions)} LIMIT 1"
 
 
65
 
66
+ cursor.execute(query, [f"%{q}%"] * len(cols))
67
+ result = cursor.fetchone()
68
  conn.close()
69
+
70
+ if result:
71
+ return {"status": "success", "data": dict(result)}
72
+ return {"status": "error", "message": "Not Found"}
73
+ except:
74
+ return {"status": "error", "message": "Not Found"}