Spaces:
Running
Running
Update main.py
Browse files
main.py
CHANGED
|
@@ -12,7 +12,7 @@ import requests
|
|
| 12 |
from flask import Flask
|
| 13 |
from flask_cors import CORS
|
| 14 |
from pyrogram import Client, filters, idle
|
| 15 |
-
from pyrogram.errors import FloodWait
|
| 16 |
from internetarchive import upload
|
| 17 |
|
| 18 |
# --- LOGGING ---
|
|
@@ -139,11 +139,10 @@ def parse_caption(caption, is_pdf=False):
|
|
| 139 |
|
| 140 |
return batch, subject, chapter, title
|
| 141 |
|
| 142 |
-
# π₯ PROGRESS TRACKER
|
| 143 |
async def progress(current, total, message, start_time, header_card):
|
| 144 |
now = time.time()
|
| 145 |
diff = now - start_time
|
| 146 |
-
# Telegram spam limits ke liye update time ko 5 seconds kar diya gaya hai
|
| 147 |
if round(diff % 5.0) == 0 or current == total:
|
| 148 |
percentage = current * 100 / total
|
| 149 |
speed = current / diff if diff > 0 else 0
|
|
@@ -158,7 +157,6 @@ async def progress(current, total, message, start_time, header_card):
|
|
| 158 |
try:
|
| 159 |
await message.edit(text)
|
| 160 |
except FloodWait as e:
|
| 161 |
-
# Agar telegram rokega, toh bot shaanti se wait karega!
|
| 162 |
await asyncio.sleep(e.value)
|
| 163 |
except Exception:
|
| 164 |
pass
|
|
@@ -184,12 +182,11 @@ def patch_firebase(url, payload):
|
|
| 184 |
if res.status_code >= 400:
|
| 185 |
raise Exception(f"Firebase Rejected Request (Status {res.status_code}): {res.text}")
|
| 186 |
|
| 187 |
-
# π₯ DYNAMIC FOLDER RESOLVER
|
| 188 |
global_firebase_cache = {}
|
| 189 |
|
| 190 |
def fetch_firebase_keys(parent_url):
|
| 191 |
-
if parent_url in global_firebase_cache:
|
| 192 |
-
return
|
| 193 |
global_firebase_cache[parent_url] = {}
|
| 194 |
if not FIREBASE_URL: return
|
| 195 |
try:
|
|
@@ -198,7 +195,7 @@ def fetch_firebase_keys(parent_url):
|
|
| 198 |
for k, v in res.json().items():
|
| 199 |
if isinstance(v, dict) and 'title' in v:
|
| 200 |
global_firebase_cache[parent_url][v['title']] = k
|
| 201 |
-
except Exception
|
| 202 |
pass
|
| 203 |
|
| 204 |
def resolve_fb_id(parent_url, title, msg_id):
|
|
@@ -251,7 +248,6 @@ async def text_handler(c, m):
|
|
| 251 |
extracted_count = 0
|
| 252 |
video_memory_cache = {}
|
| 253 |
last_fallback_video = None
|
| 254 |
-
|
| 255 |
stop_keywords = ["chapter complete", "stop extract", "subject complete", "topic complete"]
|
| 256 |
|
| 257 |
while True:
|
|
@@ -270,7 +266,6 @@ async def text_handler(c, m):
|
|
| 270 |
break
|
| 271 |
|
| 272 |
if not isinstance(messages, list): messages = [messages]
|
| 273 |
-
|
| 274 |
chunk_has_media = False
|
| 275 |
|
| 276 |
for msg in messages:
|
|
@@ -283,10 +278,8 @@ async def text_handler(c, m):
|
|
| 283 |
break
|
| 284 |
|
| 285 |
target_msg = None
|
| 286 |
-
if msg.media and not msg.web_page:
|
| 287 |
-
|
| 288 |
-
elif msg.reply_to_message and msg.reply_to_message.media:
|
| 289 |
-
target_msg = msg.reply_to_message
|
| 290 |
|
| 291 |
if not target_msg: continue
|
| 292 |
|
|
@@ -307,15 +300,12 @@ async def text_handler(c, m):
|
|
| 307 |
try: ext = fname.split(".")[-1].lower()
|
| 308 |
except: ext = "pdf"
|
| 309 |
|
| 310 |
-
if ext in ['mp4', 'mkv', 'webm', 'ts'] or "video" in mime.lower():
|
| 311 |
-
|
| 312 |
-
else:
|
| 313 |
-
is_pdf = True
|
| 314 |
else:
|
| 315 |
is_pdf = True
|
| 316 |
|
| 317 |
file_type_text = "Video π¬" if is_video else "PDF π"
|
| 318 |
-
|
| 319 |
caption = msg.text if msg.text else (target_msg.caption or "")
|
| 320 |
batch_name, sub_name, chap_name, item_title = parse_caption(caption, is_pdf=is_pdf)
|
| 321 |
|
|
@@ -332,11 +322,13 @@ async def text_handler(c, m):
|
|
| 332 |
unique_id = uuid.uuid4().hex[:5]
|
| 333 |
safe_file_name = f"AdminData_{target_msg.id}_{unique_id}.{ext}"
|
| 334 |
save_path = f"./{safe_file_name}"
|
|
|
|
| 335 |
|
| 336 |
try:
|
| 337 |
-
# π₯
|
| 338 |
max_retries = 3
|
| 339 |
download_success = False
|
|
|
|
| 340 |
|
| 341 |
for attempt in range(max_retries):
|
| 342 |
try:
|
|
@@ -346,21 +338,25 @@ async def text_handler(c, m):
|
|
| 346 |
await userbot.download_media(target_msg, file_name=save_path, progress=progress, progress_args=(status, start_t, header_card))
|
| 347 |
|
| 348 |
if not os.path.exists(save_path) or os.path.getsize(save_path) == 0:
|
| 349 |
-
raise Exception("0
|
| 350 |
|
| 351 |
download_success = True
|
| 352 |
break
|
| 353 |
except FloodWait as e:
|
| 354 |
await asyncio.sleep(e.value)
|
| 355 |
except Exception as e:
|
|
|
|
|
|
|
| 356 |
if os.path.exists(save_path): os.remove(save_path)
|
|
|
|
|
|
|
| 357 |
if attempt < max_retries - 1:
|
| 358 |
-
await asyncio.sleep(
|
| 359 |
else:
|
| 360 |
-
raise Exception(f"Failed
|
| 361 |
|
| 362 |
if not download_success:
|
| 363 |
-
raise Exception("Download
|
| 364 |
|
| 365 |
# π₯ UPLOAD PROCESS π₯
|
| 366 |
final_link = ""
|
|
@@ -373,35 +369,25 @@ async def text_handler(c, m):
|
|
| 373 |
except Exception as upload_err:
|
| 374 |
if is_pdf and "unacceptable" in str(upload_err).lower():
|
| 375 |
await status.edit(f"{header_card}\nββββββββββββββββββ\nβ οΈ **Archive.org Rejected PDF!**\nπ Uploading to Backup Server...")
|
| 376 |
-
|
| 377 |
def backup_upload():
|
| 378 |
with open(save_path, 'rb') as f:
|
| 379 |
res = requests.post("https://jitendra55566-bot-uplod.hf.space/api/upload", files={'file': f})
|
| 380 |
-
if res.status_code == 200 and 'file_url' in res.json():
|
| 381 |
-
|
| 382 |
-
else:
|
| 383 |
-
raise Exception(f"Backup Server Failed: {res.text}")
|
| 384 |
-
|
| 385 |
final_link = await asyncio.to_thread(backup_upload)
|
| 386 |
else:
|
| 387 |
raise Exception(f"Upload Failed: {upload_err}")
|
| 388 |
|
| 389 |
await status.edit(f"{header_card}\nββββββββββββββββββ\nπ **Status:** Updating Firebase Database...")
|
| 390 |
|
| 391 |
-
if not FIREBASE_URL:
|
| 392 |
-
raise Exception("FIREBASE_URL Variable Empty hai. HuggingFace Secrets check karein.")
|
| 393 |
-
|
| 394 |
cat_id = get_id(batch_name)
|
| 395 |
sub_id = get_id(f"{batch_name}_{sub_name}")
|
| 396 |
-
|
| 397 |
chap_url = f"{FIREBASE_URL}/categories/{cat_id}/subcategories/{sub_id}/subcategories"
|
| 398 |
chap_id = await asyncio.to_thread(resolve_fb_id, chap_url, chap_name, target_msg.id)
|
| 399 |
|
| 400 |
title_hash = get_id(f"{chap_name}_{item_title}")[:6]
|
| 401 |
item_id = f"z_{target_msg.id:08d}_{title_hash}"
|
| 402 |
-
|
| 403 |
-
base_match_title = get_base_title(item_title)
|
| 404 |
-
memory_key = f"{chap_id}_{base_match_title}"
|
| 405 |
|
| 406 |
def push_to_firebase():
|
| 407 |
patch_firebase(f"{FIREBASE_URL}/categories/{cat_id}.json", {"title": batch_name, "show_on_home": True, "show_on_batches": True})
|
|
@@ -409,39 +395,18 @@ async def text_handler(c, m):
|
|
| 409 |
patch_firebase(f"{FIREBASE_URL}/categories/{cat_id}/subcategories/{sub_id}/subcategories/{chap_id}.json", {"title": chap_name})
|
| 410 |
|
| 411 |
if is_video:
|
| 412 |
-
patch_firebase(f"{FIREBASE_URL}/categories/{cat_id}/subcategories/{sub_id}/subcategories/{chap_id}/videos/{item_id}.json", {
|
| 413 |
-
"title": item_title,
|
| 414 |
-
"url": final_link,
|
| 415 |
-
"priority": 0,
|
| 416 |
-
"timestamp": target_msg.id
|
| 417 |
-
})
|
| 418 |
video_memory_cache[memory_key] = item_id
|
| 419 |
-
|
| 420 |
else:
|
| 421 |
-
pdf_data = {
|
| 422 |
-
|
| 423 |
-
"url": final_link,
|
| 424 |
-
"allow_download": True,
|
| 425 |
-
"allow_google": True,
|
| 426 |
-
"priority": 0,
|
| 427 |
-
"timestamp": target_msg.id
|
| 428 |
-
}
|
| 429 |
-
|
| 430 |
-
matched_video_id = None
|
| 431 |
-
if memory_key in video_memory_cache:
|
| 432 |
-
matched_video_id = video_memory_cache[memory_key]
|
| 433 |
-
elif last_fallback_video and last_fallback_video["chap_id"] == chap_id:
|
| 434 |
-
matched_video_id = last_fallback_video["video_id"]
|
| 435 |
|
| 436 |
-
if matched_video_id:
|
| 437 |
-
|
| 438 |
-
else:
|
| 439 |
-
patch_firebase(f"{FIREBASE_URL}/categories/{cat_id}/subcategories/{sub_id}/subcategories/{chap_id}/pdfs/{item_id}.json", pdf_data)
|
| 440 |
|
| 441 |
await asyncio.to_thread(push_to_firebase)
|
| 442 |
|
| 443 |
-
if is_video:
|
| 444 |
-
last_fallback_video = {"chap_id": chap_id, "video_id": item_id}
|
| 445 |
|
| 446 |
await m.reply_text(f"β
**{file_type_text} UPLOADED!**\nπ¬ **Title:** {item_title}\nπ’ **MSG ID:** #{target_msg.id}")
|
| 447 |
extracted_count += 1
|
|
@@ -452,7 +417,9 @@ async def text_handler(c, m):
|
|
| 452 |
await m.reply_text(f"β **Error on MSG #{target_msg.id}:**\n`{e}`")
|
| 453 |
|
| 454 |
finally:
|
|
|
|
| 455 |
if os.path.exists(save_path): os.remove(save_path)
|
|
|
|
| 456 |
|
| 457 |
if not chunk_has_media:
|
| 458 |
no_media_count += 10
|
|
|
|
| 12 |
from flask import Flask
|
| 13 |
from flask_cors import CORS
|
| 14 |
from pyrogram import Client, filters, idle
|
| 15 |
+
from pyrogram.errors import FloodWait
|
| 16 |
from internetarchive import upload
|
| 17 |
|
| 18 |
# --- LOGGING ---
|
|
|
|
| 139 |
|
| 140 |
return batch, subject, chapter, title
|
| 141 |
|
| 142 |
+
# π₯ PROGRESS TRACKER π₯
|
| 143 |
async def progress(current, total, message, start_time, header_card):
|
| 144 |
now = time.time()
|
| 145 |
diff = now - start_time
|
|
|
|
| 146 |
if round(diff % 5.0) == 0 or current == total:
|
| 147 |
percentage = current * 100 / total
|
| 148 |
speed = current / diff if diff > 0 else 0
|
|
|
|
| 157 |
try:
|
| 158 |
await message.edit(text)
|
| 159 |
except FloodWait as e:
|
|
|
|
| 160 |
await asyncio.sleep(e.value)
|
| 161 |
except Exception:
|
| 162 |
pass
|
|
|
|
| 182 |
if res.status_code >= 400:
|
| 183 |
raise Exception(f"Firebase Rejected Request (Status {res.status_code}): {res.text}")
|
| 184 |
|
| 185 |
+
# π₯ DYNAMIC FOLDER RESOLVER π₯
|
| 186 |
global_firebase_cache = {}
|
| 187 |
|
| 188 |
def fetch_firebase_keys(parent_url):
|
| 189 |
+
if parent_url in global_firebase_cache: return
|
|
|
|
| 190 |
global_firebase_cache[parent_url] = {}
|
| 191 |
if not FIREBASE_URL: return
|
| 192 |
try:
|
|
|
|
| 195 |
for k, v in res.json().items():
|
| 196 |
if isinstance(v, dict) and 'title' in v:
|
| 197 |
global_firebase_cache[parent_url][v['title']] = k
|
| 198 |
+
except Exception:
|
| 199 |
pass
|
| 200 |
|
| 201 |
def resolve_fb_id(parent_url, title, msg_id):
|
|
|
|
| 248 |
extracted_count = 0
|
| 249 |
video_memory_cache = {}
|
| 250 |
last_fallback_video = None
|
|
|
|
| 251 |
stop_keywords = ["chapter complete", "stop extract", "subject complete", "topic complete"]
|
| 252 |
|
| 253 |
while True:
|
|
|
|
| 266 |
break
|
| 267 |
|
| 268 |
if not isinstance(messages, list): messages = [messages]
|
|
|
|
| 269 |
chunk_has_media = False
|
| 270 |
|
| 271 |
for msg in messages:
|
|
|
|
| 278 |
break
|
| 279 |
|
| 280 |
target_msg = None
|
| 281 |
+
if msg.media and not msg.web_page: target_msg = msg
|
| 282 |
+
elif msg.reply_to_message and msg.reply_to_message.media: target_msg = msg.reply_to_message
|
|
|
|
|
|
|
| 283 |
|
| 284 |
if not target_msg: continue
|
| 285 |
|
|
|
|
| 300 |
try: ext = fname.split(".")[-1].lower()
|
| 301 |
except: ext = "pdf"
|
| 302 |
|
| 303 |
+
if ext in ['mp4', 'mkv', 'webm', 'ts'] or "video" in mime.lower(): is_video = True
|
| 304 |
+
else: is_pdf = True
|
|
|
|
|
|
|
| 305 |
else:
|
| 306 |
is_pdf = True
|
| 307 |
|
| 308 |
file_type_text = "Video π¬" if is_video else "PDF π"
|
|
|
|
| 309 |
caption = msg.text if msg.text else (target_msg.caption or "")
|
| 310 |
batch_name, sub_name, chap_name, item_title = parse_caption(caption, is_pdf=is_pdf)
|
| 311 |
|
|
|
|
| 322 |
unique_id = uuid.uuid4().hex[:5]
|
| 323 |
safe_file_name = f"AdminData_{target_msg.id}_{unique_id}.{ext}"
|
| 324 |
save_path = f"./{safe_file_name}"
|
| 325 |
+
temp_save_path = save_path + ".temp" # Telegram temporary file
|
| 326 |
|
| 327 |
try:
|
| 328 |
+
# π₯ SMART DOWNLOAD RETRY WITH DEEP CLEANUP π₯
|
| 329 |
max_retries = 3
|
| 330 |
download_success = False
|
| 331 |
+
last_err = ""
|
| 332 |
|
| 333 |
for attempt in range(max_retries):
|
| 334 |
try:
|
|
|
|
| 338 |
await userbot.download_media(target_msg, file_name=save_path, progress=progress, progress_args=(status, start_t, header_card))
|
| 339 |
|
| 340 |
if not os.path.exists(save_path) or os.path.getsize(save_path) == 0:
|
| 341 |
+
raise Exception("0 Bytes (Corrupted by Telegram Drop)")
|
| 342 |
|
| 343 |
download_success = True
|
| 344 |
break
|
| 345 |
except FloodWait as e:
|
| 346 |
await asyncio.sleep(e.value)
|
| 347 |
except Exception as e:
|
| 348 |
+
last_err = str(e)
|
| 349 |
+
# Deep Cleanup of broken files
|
| 350 |
if os.path.exists(save_path): os.remove(save_path)
|
| 351 |
+
if os.path.exists(temp_save_path): os.remove(temp_save_path)
|
| 352 |
+
|
| 353 |
if attempt < max_retries - 1:
|
| 354 |
+
await asyncio.sleep(5) # Telegram needs 5s to reset connection
|
| 355 |
else:
|
| 356 |
+
raise Exception(f"Failed after 3 attempts. Last Error: {last_err}")
|
| 357 |
|
| 358 |
if not download_success:
|
| 359 |
+
raise Exception(f"Download Error: {last_err}")
|
| 360 |
|
| 361 |
# π₯ UPLOAD PROCESS π₯
|
| 362 |
final_link = ""
|
|
|
|
| 369 |
except Exception as upload_err:
|
| 370 |
if is_pdf and "unacceptable" in str(upload_err).lower():
|
| 371 |
await status.edit(f"{header_card}\nββββββββββββββββββ\nβ οΈ **Archive.org Rejected PDF!**\nπ Uploading to Backup Server...")
|
|
|
|
| 372 |
def backup_upload():
|
| 373 |
with open(save_path, 'rb') as f:
|
| 374 |
res = requests.post("https://jitendra55566-bot-uplod.hf.space/api/upload", files={'file': f})
|
| 375 |
+
if res.status_code == 200 and 'file_url' in res.json(): return res.json()['file_url']
|
| 376 |
+
else: raise Exception(f"Backup Server Failed: {res.text}")
|
|
|
|
|
|
|
|
|
|
| 377 |
final_link = await asyncio.to_thread(backup_upload)
|
| 378 |
else:
|
| 379 |
raise Exception(f"Upload Failed: {upload_err}")
|
| 380 |
|
| 381 |
await status.edit(f"{header_card}\nββββββββββββββββββ\nπ **Status:** Updating Firebase Database...")
|
| 382 |
|
|
|
|
|
|
|
|
|
|
| 383 |
cat_id = get_id(batch_name)
|
| 384 |
sub_id = get_id(f"{batch_name}_{sub_name}")
|
|
|
|
| 385 |
chap_url = f"{FIREBASE_URL}/categories/{cat_id}/subcategories/{sub_id}/subcategories"
|
| 386 |
chap_id = await asyncio.to_thread(resolve_fb_id, chap_url, chap_name, target_msg.id)
|
| 387 |
|
| 388 |
title_hash = get_id(f"{chap_name}_{item_title}")[:6]
|
| 389 |
item_id = f"z_{target_msg.id:08d}_{title_hash}"
|
| 390 |
+
memory_key = f"{chap_id}_{get_base_title(item_title)}"
|
|
|
|
|
|
|
| 391 |
|
| 392 |
def push_to_firebase():
|
| 393 |
patch_firebase(f"{FIREBASE_URL}/categories/{cat_id}.json", {"title": batch_name, "show_on_home": True, "show_on_batches": True})
|
|
|
|
| 395 |
patch_firebase(f"{FIREBASE_URL}/categories/{cat_id}/subcategories/{sub_id}/subcategories/{chap_id}.json", {"title": chap_name})
|
| 396 |
|
| 397 |
if is_video:
|
| 398 |
+
patch_firebase(f"{FIREBASE_URL}/categories/{cat_id}/subcategories/{sub_id}/subcategories/{chap_id}/videos/{item_id}.json", {"title": item_title, "url": final_link, "priority": 0, "timestamp": target_msg.id})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 399 |
video_memory_cache[memory_key] = item_id
|
|
|
|
| 400 |
else:
|
| 401 |
+
pdf_data = {"title": item_title, "url": final_link, "allow_download": True, "allow_google": True, "priority": 0, "timestamp": target_msg.id}
|
| 402 |
+
matched_video_id = video_memory_cache.get(memory_key) or (last_fallback_video["video_id"] if last_fallback_video and last_fallback_video["chap_id"] == chap_id else None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 403 |
|
| 404 |
+
if matched_video_id: patch_firebase(f"{FIREBASE_URL}/categories/{cat_id}/subcategories/{sub_id}/subcategories/{chap_id}/videos/{matched_video_id}/pdfs/{item_id}.json", pdf_data)
|
| 405 |
+
else: patch_firebase(f"{FIREBASE_URL}/categories/{cat_id}/subcategories/{sub_id}/subcategories/{chap_id}/pdfs/{item_id}.json", pdf_data)
|
|
|
|
|
|
|
| 406 |
|
| 407 |
await asyncio.to_thread(push_to_firebase)
|
| 408 |
|
| 409 |
+
if is_video: last_fallback_video = {"chap_id": chap_id, "video_id": item_id}
|
|
|
|
| 410 |
|
| 411 |
await m.reply_text(f"β
**{file_type_text} UPLOADED!**\nπ¬ **Title:** {item_title}\nπ’ **MSG ID:** #{target_msg.id}")
|
| 412 |
extracted_count += 1
|
|
|
|
| 417 |
await m.reply_text(f"β **Error on MSG #{target_msg.id}:**\n`{e}`")
|
| 418 |
|
| 419 |
finally:
|
| 420 |
+
# π₯ DEEP CLEANUP: Ensure NO garbage is left behind
|
| 421 |
if os.path.exists(save_path): os.remove(save_path)
|
| 422 |
+
if os.path.exists(temp_save_path): os.remove(temp_save_path)
|
| 423 |
|
| 424 |
if not chunk_has_media:
|
| 425 |
no_media_count += 10
|