tfqdeadlo commited on
Commit
002a8d0
·
verified ·
1 Parent(s): fc1df7c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -143
app.py CHANGED
@@ -1,163 +1,61 @@
1
- from fastapi import FastAPI, HTTPException, Request, BackgroundTasks
2
- import telebot
3
- from telebot import apihelper
4
- import httpx
5
- import os
6
- import time
7
  from contextlib import asynccontextmanager
8
 
9
- # ⚡ PRODUCTION TIMEOUTS: Safe values proxy networks ke liye
10
- apihelper.CONNECT_TIMEOUT = 30
11
- apihelper.READ_TIMEOUT = 30
12
-
13
- BOT_TOKEN = os.environ.get("BOT_TOKEN")
14
- API_URL = os.environ.get("API_URL", "https://tfqdeadlo-1-78bapi.hf.space/search")
15
- BOT_SPACE_URL = "https://tfqdeadlo-tgbotc.hf.space"
16
-
17
- # threaded=False zaroori hai jab hum FastAPI background tasks use karte hain
18
- bot = telebot.TeleBot(BOT_TOKEN, threaded=False)
19
 
 
20
  @asynccontextmanager
21
  async def lifespan(app: FastAPI):
22
- if not BOT_TOKEN:
23
- print("❌ ERROR: BOT_TOKEN Missing!")
24
- yield
25
- return
 
26
 
27
- # Webhook set karne ke liye retry mechanism
28
- for attempt in range(3):
29
- try:
30
- webhook_url = f"{BOT_SPACE_URL}/telegram-webhook"
31
- bot.remove_webhook()
32
- bot.set_webhook(url=webhook_url, timeout=30)
33
- print("✅ Webhook successfully set ho gaya startup par!")
34
- break
35
- except Exception as e:
36
- print(f"⚠️ Webhook attempt {attempt+1} fail hua: {e}")
37
- time.sleep(2)
38
  yield
 
39
 
40
- app = FastAPI(title="Lakhs-Users Production Bot", lifespan=lifespan)
41
 
42
  @app.get("/")
43
  def home():
44
- return {"status": "running", "message": "Master-Handler Production Bot Active!"}
45
 
46
- # --- BACKGROUND WORKER ---
47
- def process_telegram_update(json_string: dict):
48
  try:
49
- update = telebot.types.Update.de_json(json_string)
50
- bot.process_new_updates([update])
51
- except Exception as e:
52
- print(f"❌ Processing me error: {e}")
53
-
54
- # --- TELEGRAM WEBHOOK ENDPOINT ---
55
- @app.post("/telegram-webhook")
56
- async def telegram_webhook(request: Request, background_tasks: BackgroundTasks):
57
- if request.headers.get("content-type") == "application/json":
58
- json_string = await request.json()
59
- # Telegram ko turant 200 OK dekar free karo, taaki request line me na fase
60
- background_tasks.add_task(process_telegram_update, json_string)
61
- return {"status": "ok"}
62
- else:
63
- raise HTTPException(status_code=403, detail="Bad Request")
64
-
65
- # --- HELPER: RETRY DRIVEN SEND MESSAGE ---
66
- def send_message_with_retry(chat_id, text, parse_mode=None):
67
- """Network failure se bachne ke liye automatic 3-times retry system"""
68
- for attempt in range(3):
69
- try:
70
- return bot.send_message(chat_id, text, parse_mode=parse_mode)
71
- except Exception as e:
72
- print(f"⚠️ Message send attempt {attempt+1} fail hua: {e}")
73
- if attempt < 2:
74
- time.sleep(1)
75
- else:
76
- print("❌ Saare attempts fail ho gaye.")
77
-
78
- # --- 🎯 MASTER HANDLER (Unbreakable Routing) ---
79
- @bot.message_handler(func=lambda message: True)
80
- def handle_all_messages(message):
81
- if not message.text:
82
- return
83
-
84
- raw_input = message.text.strip()
85
- chat_id = message.chat.id
86
-
87
- # ⭐ 1. Check if it is a command (/start or /help)
88
- if raw_input.startswith('/start') or raw_input.startswith('/help'):
89
- print(f"⚙️ [COMMAND] /start received for Chat ID: {chat_id}")
90
- welcome_text = (
91
- "👋 **Welcome to Search Bot!**\n\n"
92
- "Mujhe koi bhi mobile number bhejiye, mai backend se data nikal kar dunga.\n"
93
- "⚡ *Safe, Secure & Fast*"
94
- )
95
- send_message_with_retry(chat_id, welcome_text, parse_mode="Markdown")
96
- print(f"➡️ [COMMAND] /start reply successfully sent to Chat ID: {chat_id}")
97
- return # Yahin se process khatam, aage mobile search par nahi jayega
98
-
99
- # ⭐ 2. If it's NOT a command, process it as a Mobile Number Search
100
- print(f"📥 [SEARCH] Mobile search request: '{raw_input}' | Chat ID: {chat_id}")
101
-
102
- if len(raw_input) > 20:
103
- send_message_with_retry(chat_id, "❌ Input bohot lamba hai! Kripya sirf ek valid mobile number bhejein.")
104
- return
105
-
106
- cleaned_mobile = "".join(c for c in raw_input if c.isdigit())
107
-
108
- if len(cleaned_mobile) == 12 and cleaned_mobile.startswith("91"):
109
- mobile = cleaned_mobile[-10:]
110
- elif len(cleaned_mobile) == 10:
111
- mobile = cleaned_mobile
112
- else:
113
- mobile = cleaned_mobile
114
-
115
- if not mobile or len(mobile) < 10 or len(mobile) > 11:
116
- send_message_with_retry(chat_id, "❌ Kripya ek sahi 10-digit ka mobile number bhejein.")
117
- return
118
 
119
- try:
120
- bot.send_chat_action(chat_id, 'typing')
121
- except Exception:
122
- pass
123
-
124
- send_message_with_retry(chat_id, f"🔍 Searching for `{mobile}`... Please wait...")
125
-
126
- try:
127
- # Backend API hit karna
128
- response = httpx.get(f"{API_URL}?mobile={mobile}", timeout=15.0)
129
 
130
- if response.status_code != 200:
131
- send_message_with_retry(chat_id, "⚠️ Main API se sampark nahi ho paya. Kripya thodi der baad try karein.")
132
- return
133
-
134
- res_data = response.json()
135
 
136
- if res_data.get("status") == "error":
137
- send_message_with_retry(chat_id, f"❌ {res_data.get('message', 'Mobile number nahi mila.')}")
138
- return
139
-
140
- row_dict = res_data.get("data", {})
141
 
142
- if not row_dict or not isinstance(row_dict, dict):
143
- send_message_with_retry(chat_id, f"❌ Mobile number `{mobile}` ka koi valid record nahi mila.")
144
- return
145
-
146
- response_msg = f"✅ **Record Found for {mobile}!**\n\n"
147
- for key, value in row_dict.items():
148
- display_value = value if value else "N/A"
149
- response_msg += f"🔹 **{key.upper()}**: `{display_value}`\n"
150
-
151
- send_message_with_retry(chat_id, response_msg, parse_mode="Markdown")
152
- print(f"➡️ Success: Data reply successfully sent for {mobile}")
153
 
154
- except (httpx.ConnectTimeout, httpx.ReadTimeout):
155
- send_message_with_retry(
156
- chat_id,
157
- "⏳ **Main Data API sleep mode se jaag rahi hai.**\n\n"
158
- "Kripya 5 seconds baad wapas se wahi number bhejein, data aa jayega!"
159
- )
160
  except Exception as e:
161
- print(f"❌ Main logic crash prevented: {e}")
162
- send_message_with_retry(chat_id, "⚠️ Kuch temporary dikkat aayi hai. Baad me try karein.")
163
 
 
1
+ From fastapi import FastAPI, HTTPException, Query
2
+ import duckdb
 
 
 
 
3
  from contextlib import asynccontextmanager
4
 
5
+ # Global connection object
6
+ con = duckdb.connect()
 
 
 
 
 
 
 
 
7
 
8
+ # Lifespan use karke app start hote hi heavy initialization ek baar karenge
9
  @asynccontextmanager
10
  async def lifespan(app: FastAPI):
11
+ print("DuckDB extensions load ho rahi hain aur View ban raha hai...")
12
+ con.execute("INSTALL httpfs; LOAD httpfs;")
13
+
14
+ # Parquet file ka correct URL
15
+ PARQUET_URL = "https://huggingface.co/datasets/tfqdeadlo/Inddatainonefile/resolve/main/users_data.parquet"
16
 
17
+ # Startup par hi Ek baar View bana kar metadata cache kar lete hain
18
+ # Isse har API request par network par load nahi padega
19
+ con.execute(f"CREATE OR REPLACE VIEW users_view AS SELECT * FROM read_parquet('{PARQUET_URL}')")
20
+ print("View taiyar hai! API requests ke liye taiyar hai.")
 
 
 
 
 
 
 
21
  yield
22
+ con.close()
23
 
24
+ app = FastAPI(title="Super Fast Search API", lifespan=lifespan)
25
 
26
  @app.get("/")
27
  def home():
28
+ return {"message": "Fast API online hai! Use /search?mobile=YOUR_NUMBER"}
29
 
30
+ @app.get("/search")
31
+ async def search_mobile(mobile: str = Query(..., description="Enter mobile number to search")):
32
  try:
33
+ # Ab hum direct cache kiye hue 'users_view' se data nikalenge
34
+ query = """
35
+ SELECT mobile, name, fname, address, alt, circle, id, email
36
+ FROM users_view
37
+ WHERE mobile = ?
38
+ LIMIT 1
39
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
+ result = con.execute(query, [str(mobile)]).fetchall()
 
 
 
 
 
 
 
 
 
42
 
43
+ if not result:
44
+ return {
45
+ "status": "error",
46
+ "message": f"Mobile number {mobile} nahi mila."
47
+ }
48
 
49
+ # Data mapping
50
+ columns = [desc[0] for desc in con.description]
51
+ row_dict = dict(zip(columns, result[0]))
 
 
52
 
53
+ return {
54
+ "status": "success",
55
+ "data": row_dict
56
+ }
 
 
 
 
 
 
 
57
 
 
 
 
 
 
 
58
  except Exception as e:
59
+ # Internal error ko secure rakhne ke liye mask kiya hai
60
+ raise HTTPException(status_code=500, detail="Query timeout ya process nahi ho payi.")
61