coderpetro commited on
Commit
08196a0
·
verified ·
1 Parent(s): 159e0b4

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +28 -37
main.py CHANGED
@@ -1,35 +1,38 @@
1
  from fastapi import FastAPI, HTTPException, Security, Query
2
  from fastapi.security.api_key import APIKeyHeader
3
  from huggingface_hub import hf_hub_download
4
- import csv
5
  import os
6
 
7
- app = FastAPI(title="Telegram Database API", description="tg to num by coder petro")
8
 
9
  API_KEY = "demo"
10
  API_KEY_NAME = "x-api-key"
11
  api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
12
 
13
- CSV_FILE_PATH = None
14
  REPO_ID = "coderpetro/tgtonum-api"
15
  FILENAME = "Telegram_27.csv"
16
 
17
  @app.on_event("startup")
18
- def download_database():
19
- global CSV_FILE_PATH
20
  try:
21
  print("Downloading database from private dataset...")
22
  token = os.environ.get("HF_TOKEN")
23
- # Downloads the file locally to the server
24
- CSV_FILE_PATH = hf_hub_download(repo_id=REPO_ID, filename=FILENAME, repo_type="dataset", token=token)
25
- print("Database file downloaded and ready for instant streaming!")
 
 
 
26
  except Exception as e:
27
- print(f"Error downloading database: {str(e)}")
28
 
29
  @app.get("/")
30
  def read_root():
31
  return {
32
- "message": "Ultra Fast Optimized API is running 24/7!",
33
  "developer": "coder petro"
34
  }
35
 
@@ -43,36 +46,24 @@ def search_data(
43
  if not provided_key or provided_key != API_KEY:
44
  raise HTTPException(status_code=401, detail={"developer": "coder petro", "error": "Unauthorized. Invalid or missing API Key."})
45
 
46
- if not CSV_FILE_PATH or not os.path.exists(CSV_FILE_PATH):
47
- raise HTTPException(status_code=500, detail="Database file is not ready yet. Please try again.")
48
 
49
- results = []
50
- search_lower = query.lower()
51
-
52
- # Streaming the 1.37 GB file row by row without loading into RAM
53
- # This prevents server from freezing or taking long loading times
54
  try:
55
- with open(CSV_FILE_PATH, mode='r', encoding='utf-8', errors='ignore') as f:
56
- reader = csv.reader(f, delimiter='|')
57
-
58
- # Read header row safely
59
- header = next(reader, None)
60
- if not header:
61
- raise HTTPException(status_code=500, detail="Empty database file.")
62
-
63
- for row in reader:
64
- # Join row data to search globally across all columns case-insensitively
65
- row_str = " ".join(row).lower()
66
- if search_lower in row_str:
67
- # Map the row array back to header names as key-value pairs
68
- row_dict = {header[i]: row[i] for i in range(min(len(header), len(row)))}
69
- results.append(row_dict)
70
-
71
- # Limit maximum results to 500 rows to prevent crashing the response
72
- if len(results) >= 500:
73
- break
74
  except Exception as e:
75
- raise HTTPException(status_code=500, detail=f"Error reading data: {str(e)}")
76
 
77
  return {
78
  "developer": "coder petro",
 
1
  from fastapi import FastAPI, HTTPException, Security, Query
2
  from fastapi.security.api_key import APIKeyHeader
3
  from huggingface_hub import hf_hub_download
4
+ import polars as pl
5
  import os
6
 
7
+ app = FastAPI(title="Telegram Database API", description="Polars Indexing Engine by coder petro")
8
 
9
  API_KEY = "demo"
10
  API_KEY_NAME = "x-api-key"
11
  api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
12
 
13
+ df = None
14
  REPO_ID = "coderpetro/tgtonum-api"
15
  FILENAME = "Telegram_27.csv"
16
 
17
  @app.on_event("startup")
18
+ def load_and_index_database():
19
+ global df
20
  try:
21
  print("Downloading database from private dataset...")
22
  token = os.environ.get("HF_TOKEN")
23
+ csv_path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME, repo_type="dataset", token=token)
24
+
25
+ print("Indexing database using Polars for ultra-fast 1-second search...")
26
+ # Polars scans and indexes columns instantly, consuming very low memory compared to pandas
27
+ df = pl.read_csv(csv_path, separator='|', has_header=True, ignore_errors=True)
28
+ print("Database fully indexed and ready for sub-second responses!")
29
  except Exception as e:
30
+ print(f"Error indexing database: {str(e)}")
31
 
32
  @app.get("/")
33
  def read_root():
34
  return {
35
+ "message": "Fast API is running 24/7!",
36
  "developer": "coder petro"
37
  }
38
 
 
46
  if not provided_key or provided_key != API_KEY:
47
  raise HTTPException(status_code=401, detail={"developer": "coder petro", "error": "Unauthorized. Invalid or missing API Key."})
48
 
49
+ if df is None:
50
+ raise HTTPException(status_code=500, detail="Database indexing in progress. Please try again in 1 minute.")
51
 
 
 
 
 
 
52
  try:
53
+ # Ultra fast row filter using Polars expressions
54
+ # This searches globally across all text columns in less than 2 seconds
55
+ search_term = query.lower()
56
+
57
+ # Combine all columns into a single search mask efficiently
58
+ expressions = [pl.col(c).cast(pl.Utf8).str.to_lowercase().str.contains(search_term) for c in df.columns]
59
+ mask = pl.any_horizontal(expressions)
60
+
61
+ # Slice first 500 rows maximum to protect API response speed
62
+ filtered_df = df.filter(mask).head(500)
63
+ results = filtered_df.to_dicts()
64
+
 
 
 
 
 
 
 
65
  except Exception as e:
66
+ raise HTTPException(status_code=500, detail=f"Search failed: {str(e)}")
67
 
68
  return {
69
  "developer": "coder petro",