Spaces:
Sleeping
Sleeping
Update main.py
Browse files
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
|
| 5 |
import os
|
| 6 |
|
| 7 |
-
app = FastAPI(title="Telegram Database API", description="
|
| 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 |
-
|
| 14 |
REPO_ID = "coderpetro/tgtonum-api"
|
| 15 |
FILENAME = "Telegram_27.csv"
|
| 16 |
|
| 17 |
@app.on_event("startup")
|
| 18 |
-
def
|
| 19 |
-
global
|
| 20 |
try:
|
| 21 |
print("Downloading database from private dataset...")
|
| 22 |
token = os.environ.get("HF_TOKEN")
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
print("
|
|
|
|
|
|
|
|
|
|
| 26 |
except Exception as e:
|
| 27 |
-
print(f"Error
|
| 28 |
|
| 29 |
@app.get("/")
|
| 30 |
def read_root():
|
| 31 |
return {
|
| 32 |
-
"message": "
|
| 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
|
| 47 |
-
raise HTTPException(status_code=500, detail="Database
|
| 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 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 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"
|
| 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",
|