tfqdeadlo commited on
Commit
40d60ac
·
verified ·
1 Parent(s): 15a932a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -14
app.py CHANGED
@@ -1,22 +1,44 @@
1
  import os
 
 
2
  from fastapi import FastAPI, HTTPException, Query
3
  import duckdb
4
 
5
  app = FastAPI(title="Fast Mobile Search API")
6
 
7
- # DuckDB connection setup aur httpfs extension load karo
8
  con = duckdb.connect()
9
- con.execute("INSTALL httpfs; LOAD httpfs;")
10
 
11
- # Hugging Face Space ke Secret se token nikalna
12
  HF_TOKEN = os.environ.get("HF_TOKEN", "")
13
-
14
- # Base Parquet URL
15
  PARQUET_URL = "https://huggingface.co/datasets/tfqdeadlo/Inddatainone/resolve/main/users_data.parquet"
16
 
17
- # Agar token maujood hai, toh URL ke sath authenticated request ke liye append karo
18
- if HF_TOKEN:
19
- PARQUET_URL += f"?token={HF_TOKEN}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  @app.get("/")
22
  def home():
@@ -25,15 +47,17 @@ def home():
25
  @app.get("/search")
26
  async def search_mobile(mobile: str = Query(..., description="Enter the mobile number to search")):
27
  try:
28
- # DuckDB query jo seedhe authenticated URL se data fetch karegi
 
 
 
29
  query = f"""
30
  SELECT mobile, name, fname, address, alt, circle, id, email
31
- FROM read_parquet('{PARQUET_URL}')
32
  WHERE mobile = ?
33
  LIMIT 1
34
  """
35
 
36
- # Query execute karo aur result fetch karo
37
  result = con.execute(query, [str(mobile)]).fetchall()
38
 
39
  if not result:
@@ -42,7 +66,6 @@ async def search_mobile(mobile: str = Query(..., description="Enter the mobile n
42
  "message": f"Mobile number {mobile} nahi mila."
43
  }
44
 
45
- # Columns names nikal kar dictionary format me data convert karo
46
  columns = [desc[0] for desc in con.description]
47
  row_dict = dict(zip(columns, result[0]))
48
 
@@ -52,5 +75,6 @@ async def search_mobile(mobile: str = Query(..., description="Enter the mobile n
52
  }
53
 
54
  except Exception as e:
55
- raise HTTPException(status_code=500, detail=f"Kuch gadbad hui: {str(e)}")
56
-
 
 
1
  import os
2
+ import tempfile
3
+ import requests
4
  from fastapi import FastAPI, HTTPException, Query
5
  import duckdb
6
 
7
  app = FastAPI(title="Fast Mobile Search API")
8
 
9
+ # DuckDB connection
10
  con = duckdb.connect()
 
11
 
12
+ # Hugging Face token environment se
13
  HF_TOKEN = os.environ.get("HF_TOKEN", "")
 
 
14
  PARQUET_URL = "https://huggingface.co/datasets/tfqdeadlo/Inddatainone/resolve/main/users_data.parquet"
15
 
16
+ # Global variable to cache the downloaded file path (optional, to avoid re-downloading)
17
+ temp_file_path = None
18
+
19
+ def download_parquet_with_auth():
20
+ global temp_file_path
21
+ if temp_file_path and os.path.exists(temp_file_path):
22
+ return temp_file_path
23
+
24
+ if not HF_TOKEN:
25
+ raise Exception("HF_TOKEN environment variable not set. Please add your token in Space secrets.")
26
+
27
+ headers = {"Authorization": f"Bearer {HF_TOKEN}"}
28
+ response = requests.get(PARQUET_URL, headers=headers, stream=True)
29
+
30
+ if response.status_code != 200:
31
+ raise Exception(f"Download failed with status {response.status_code}: {response.text[:200]}")
32
+
33
+ # Save to a temporary file
34
+ fd, path = tempfile.mkstemp(suffix=".parquet")
35
+ os.close(fd)
36
+ with open(path, "wb") as f:
37
+ for chunk in response.iter_content(chunk_size=8192):
38
+ f.write(chunk)
39
+
40
+ temp_file_path = path
41
+ return path
42
 
43
  @app.get("/")
44
  def home():
 
47
  @app.get("/search")
48
  async def search_mobile(mobile: str = Query(..., description="Enter the mobile number to search")):
49
  try:
50
+ # Download the parquet file (cached after first request)
51
+ local_path = download_parquet_with_auth()
52
+
53
+ # DuckDB query on local file
54
  query = f"""
55
  SELECT mobile, name, fname, address, alt, circle, id, email
56
+ FROM read_parquet('{local_path}')
57
  WHERE mobile = ?
58
  LIMIT 1
59
  """
60
 
 
61
  result = con.execute(query, [str(mobile)]).fetchall()
62
 
63
  if not result:
 
66
  "message": f"Mobile number {mobile} nahi mila."
67
  }
68
 
 
69
  columns = [desc[0] for desc in con.description]
70
  row_dict = dict(zip(columns, result[0]))
71
 
 
75
  }
76
 
77
  except Exception as e:
78
+ # Sanitize error message to hide token
79
+ error_msg = str(e).replace(HF_TOKEN, "[HIDDEN_TOKEN]") if HF_TOKEN else str(e)
80
+ raise HTTPException(status_code=500, detail=f"Kuch gadbad hui: {error_msg}")