coderpetro commited on
Commit
f87e442
·
verified ·
1 Parent(s): 9ed7279

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +36 -25
main.py CHANGED
@@ -1,39 +1,51 @@
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
- # FIXED: Reverted to your exact private dataset name
15
  REPO_ID = "coderpetro/telegram-data"
16
  FILENAME = "Telegram_27.csv"
17
 
18
  @app.on_event("startup")
19
  def load_and_index_database():
20
- global df
21
  try:
22
  print("Downloading database from private dataset...")
23
  token = os.environ.get("HF_TOKEN")
24
  csv_path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME, repo_type="dataset", token=token)
25
 
26
- print("Indexing database using Polars for ultra-fast 1-second search...")
27
- # Polars dynamically indexes columns with very low RAM footprint
28
- df = pl.read_csv(csv_path, separator='|', has_header=True, ignore_errors=True)
29
- print("Database fully indexed and ready for sub-second responses!")
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  except Exception as e:
31
  print(f"Error indexing database: {str(e)}")
32
 
33
  @app.get("/")
34
  def read_root():
35
  return {
36
- "message": "Sub-Second Fast API is running 24/7!",
37
  "developer": "coder petro"
38
  }
39
 
@@ -47,25 +59,24 @@ def search_data(
47
  if not provided_key or provided_key != API_KEY:
48
  raise HTTPException(status_code=401, detail={"developer": "coder petro", "error": "Unauthorized. Invalid or missing API Key."})
49
 
50
- if df is None:
51
- raise HTTPException(status_code=500, detail="Database indexing in progress. Please try again in 1 minute.")
52
 
53
- try:
54
- search_term = query.lower()
55
-
56
- # Parallel horizontal scanning across all columns in less than 2 seconds
57
- expressions = [pl.col(c).cast(pl.Utf8).str.to_lowercase().str.contains(search_term) for c in df.columns]
58
- mask = pl.any_horizontal(expressions)
59
-
60
- # Cap at 500 rows to ensure blazing fast response delivery
61
- filtered_df = df.filter(mask).head(500)
62
- results = filtered_df.to_dicts()
63
-
64
- except Exception as e:
65
- raise HTTPException(status_code=500, detail=f"Search failed: {str(e)}")
66
 
67
  return {
68
  "developer": "coder petro",
69
  "total_results": len(results),
70
  "data": results
71
  }
 
 
 
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="1-Second Ultra 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
+ db_records = []
 
14
  REPO_ID = "coderpetro/telegram-data"
15
  FILENAME = "Telegram_27.csv"
16
 
17
  @app.on_event("startup")
18
  def load_and_index_database():
19
+ global db_records
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("Creating ultra-fast memory index map...")
26
+ # errors='ignore' safely skips invalid utf-8 sequences (Russian character errors)
27
+ with open(csv_path, mode='r', encoding='utf-8', errors='ignore') as f:
28
+ reader = csv.reader(f, delimiter='|')
29
+ header = next(reader, None)
30
+
31
+ if not header:
32
+ print("Error: Empty file.")
33
+ return
34
+
35
+ # Pre-loading and keeping raw data structured into a flat list for instant O(n) array scan
36
+ for row in reader:
37
+ if row:
38
+ row_dict = {header[i]: row[i] for i in range(min(len(header), len(row)))}
39
+ db_records.append(row_dict)
40
+
41
+ print(f"Success! {len(db_records)} rows fully indexed in RAM. Instant search is ready!")
42
  except Exception as e:
43
  print(f"Error indexing database: {str(e)}")
44
 
45
  @app.get("/")
46
  def read_root():
47
  return {
48
+ "message": "Sub-Second Blazing Fast API is running 24/7!",
49
  "developer": "coder petro"
50
  }
51
 
 
59
  if not provided_key or provided_key != API_KEY:
60
  raise HTTPException(status_code=401, detail={"developer": "coder petro", "error": "Unauthorized. Invalid or missing API Key."})
61
 
62
+ if not db_records:
63
+ raise HTTPException(status_code=500, detail="Database indexing is in progress or failed. Check logs.")
64
 
65
+ search_lower = query.lower()
66
+ results = []
67
+
68
+ # Instant sub-second memory iteration
69
+ for record in db_records:
70
+ # Search globally across all field values inside the record dict
71
+ if any(search_lower in str(value).lower() for value in record.values()):
72
+ results.append(record)
73
+ if len(results) >= 500: # Safeguard cap
74
+ break
 
 
 
75
 
76
  return {
77
  "developer": "coder petro",
78
  "total_results": len(results),
79
  "data": results
80
  }
81
+
82
+ }