Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -12,21 +12,23 @@ from flask import Flask
|
|
| 12 |
# ==========================================
|
| 13 |
# π APNI DETAILS YAHAN DAALEIN π
|
| 14 |
# ==========================================
|
|
|
|
| 15 |
API_ID = "35985614"
|
| 16 |
API_HASH = "6a0df17414daf6935f1f0a71b8af1ee9"
|
| 17 |
STRING_SESSION = "BQIlGM4AkncApFEGc9JNMRHYJCqi-IbbXCuSEw7yrNIcloArm-xwbEM8ksoMYQEK4_uD1NEgro-CIDXnc6yEuaPkm91FGhHVpHJGoUnvv19UeilrIhopSY8dboZ0emUF15IhIgZD6Qqp5Nv2gJobdCrZQuitAS6Xelmm14rn-3kWynpUo3vD4GpeRWh1b8ydh8Rlqi1ALoWOHC5uGyK_zJBAnxDUea2FJUvgX2Q93TuejnVuj4o84M_DqMtHowvf5EGkE4HSZfjPW6c5Qb2VkFtRwFmt1-6hZGoABJjvrJpZQmc94LLApSd45Hme-YXpPrxGWck4mFF0t8SRYrPGMxyyVJRgAAAAHK_kURAA"
|
| 18 |
-
|
|
|
|
| 19 |
|
| 20 |
BOT_TOKEN = "8830608789:AAF7J6I-1H1mzRkpccgCOuTh2wR_yOSOMNA"
|
| 21 |
|
| 22 |
-
|
| 23 |
-
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 24 |
HF_REPO_ID = "Jitendra55566/pdf-notes"
|
| 25 |
FIREBASE_URL = "https://logo-ncc-default-rtdb.asia-southeast1.firebasedatabase.app"
|
| 26 |
|
| 27 |
# ==========================================
|
| 28 |
# 1. DAILY STATS TRACKER
|
| 29 |
# ==========================================
|
|
|
|
| 30 |
def get_ist_date():
|
| 31 |
ist_time = datetime.utcnow() + timedelta(hours=5, minutes=30)
|
| 32 |
return ist_time.strftime("%d-%m-%Y")
|
|
@@ -47,8 +49,9 @@ def add_to_stats(subject, chapter, pdf_name):
|
|
| 47 |
daily_stats["details"].append(f"β
{subject} β {chapter} ({pdf_name})")
|
| 48 |
|
| 49 |
# ==========================================
|
| 50 |
-
# 2. FLASK SERVER
|
| 51 |
# ==========================================
|
|
|
|
| 52 |
web_app = Flask(__name__)
|
| 53 |
|
| 54 |
@web_app.route('/')
|
|
@@ -61,6 +64,7 @@ def run_flask():
|
|
| 61 |
# ==========================================
|
| 62 |
# 3. TELEGRAM CLIENTS SETUP
|
| 63 |
# ==========================================
|
|
|
|
| 64 |
app = Client("user_account", session_string=STRING_SESSION, api_id=API_ID, api_hash=API_HASH)
|
| 65 |
bot_app = Client("report_bot", bot_token=BOT_TOKEN, api_id=API_ID, api_hash=API_HASH)
|
| 66 |
hf_api = HfApi()
|
|
@@ -68,6 +72,7 @@ hf_api = HfApi()
|
|
| 68 |
# ==========================================
|
| 69 |
# 4. REPORT BOT HANDLERS (@BotFather bot)
|
| 70 |
# ==========================================
|
|
|
|
| 71 |
@bot_app.on_message(filters.command("start"))
|
| 72 |
async def start_cmd(client, message):
|
| 73 |
text = "π Hello Sir!\n\nMain auto-upload bot hu.\nπ Aaj ki Report dekhne ke liye π /today"
|
|
@@ -80,7 +85,7 @@ async def today_cmd(client, message):
|
|
| 80 |
daily_stats["date"] = today
|
| 81 |
daily_stats["count"] = 0
|
| 82 |
daily_stats["details"] = []
|
| 83 |
-
|
| 84 |
if daily_stats["count"] == 0:
|
| 85 |
await message.reply_text(f"π
Date: {today}\n\nπ΄ Aaj abhi tak koi PDF upload nahi hui.")
|
| 86 |
else:
|
|
@@ -91,6 +96,7 @@ async def today_cmd(client, message):
|
|
| 91 |
# ==========================================
|
| 92 |
# 5. USER ACCOUNT LOGIC (PDF DOWNLOAD & UPLOAD)
|
| 93 |
# ==========================================
|
|
|
|
| 94 |
def upload_to_huggingface(file_path, file_name):
|
| 95 |
hf_api.upload_file(
|
| 96 |
path_or_fileobj=file_path,
|
|
@@ -111,14 +117,15 @@ def find_or_create_node(base_url, title, create_data=None):
|
|
| 111 |
res = requests.post(f"{base_url}.json", json=create_data)
|
| 112 |
return res.json()['name']
|
| 113 |
|
|
|
|
| 114 |
@app.on_message(filters.chat(TARGET_CHAT) & filters.document)
|
| 115 |
-
def handle_new_pdf(client, message):
|
| 116 |
text = message.caption if message.caption else ""
|
| 117 |
if not text:
|
| 118 |
return
|
| 119 |
|
| 120 |
try:
|
| 121 |
-
#
|
| 122 |
file_name_match = re.search(r"File Name\s*:\s*(.*?)\.pdf", text, re.IGNORECASE)
|
| 123 |
file_name = file_name_match.group(1).strip() if file_name_match else "Unknown"
|
| 124 |
|
|
@@ -131,62 +138,51 @@ def handle_new_pdf(client, message):
|
|
| 131 |
if not batch_name or not subject_name:
|
| 132 |
return
|
| 133 |
|
| 134 |
-
# Chapter (ex: ΰ€΅ΰ€°ΰ₯ΰ€€ΰ€¨ΰ₯) extraction
|
| 135 |
chapter_match = re.search(r"\((.*?)\)(?!\s*ΰ€΅ΰ₯ΰ€° ΰ€¬ΰ₯ΰ€)", file_name)
|
| 136 |
chapter_name = chapter_match.group(1).strip() if chapter_match else "General"
|
| 137 |
|
| 138 |
-
# Clean Video Name extraction
|
| 139 |
parts = file_name.split(')')
|
| 140 |
class_str = parts[-1] if len(parts) > 1 else file_name
|
| 141 |
-
class_str = re.sub(r'(?i)PDF.*', '', class_str).strip()
|
| 142 |
-
video_name = re.sub(r'\s*\d+$', '', class_str).strip()
|
| 143 |
|
| 144 |
-
#
|
| 145 |
-
# 2. FIREBASE PANEL CONNECTION
|
| 146 |
-
# ==========================================
|
| 147 |
cat_id = find_or_create_node(f"{FIREBASE_URL}/categories", batch_name, {"title": batch_name})
|
| 148 |
sub_id = find_or_create_node(f"{FIREBASE_URL}/categories/{cat_id}/subcategories", subject_name, {"title": subject_name})
|
| 149 |
chap_id = find_or_create_node(f"{FIREBASE_URL}/categories/{cat_id}/subcategories/{sub_id}/subcategories", chapter_name, {"title": chapter_name})
|
| 150 |
|
| 151 |
-
# VIDEO (Class) banega YAHAN DUMMY LINK HAI
|
| 152 |
vid_id = find_or_create_node(f"{FIREBASE_URL}/categories/{cat_id}/subcategories/{sub_id}/subcategories/{chap_id}/videos", video_name, {
|
| 153 |
"title": video_name,
|
| 154 |
-
"url": "https://dummy-video-url.com",
|
| 155 |
"date": int(time.time() * 1000)
|
| 156 |
})
|
| 157 |
|
| 158 |
-
# ==========================================
|
| 159 |
-
# 3. PDF DUPLICATE CHECK & AUTO-NAMING (PDF 1 / PDF 2)
|
| 160 |
-
# ==========================================
|
| 161 |
pdf_folder_url = f"{FIREBASE_URL}/categories/{cat_id}/subcategories/{sub_id}/subcategories/{chap_id}/videos/{vid_id}/pdfs"
|
| 162 |
existing_pdfs = requests.get(f"{pdf_folder_url}.json").json() or {}
|
| 163 |
|
| 164 |
pdf_count = 0
|
| 165 |
for pid, pdata in existing_pdfs.items():
|
| 166 |
pdf_count += 1
|
| 167 |
-
# Check duplicate based on original file name
|
| 168 |
if pdata.get('original_name') == file_name:
|
| 169 |
print(f"Skipping! '{file_name}' pehle se maujud hai.")
|
| 170 |
return
|
| 171 |
|
| 172 |
-
# Naya PDF ka Button Name set karna (PDF 1, PDF 2...)
|
| 173 |
pdf_button_name = f"PDF {pdf_count + 1}"
|
| 174 |
|
| 175 |
-
# ==========================================
|
| 176 |
-
# 4. DOWNLOAD & UPLOAD TO HUGGING FACE
|
| 177 |
-
# ==========================================
|
| 178 |
print(f"Downloading: {file_name}.pdf")
|
| 179 |
-
|
| 180 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
os.remove(local_path)
|
| 182 |
|
| 183 |
-
# ==========================================
|
| 184 |
-
# 5. UPLOAD TO FIREBASE PANEL
|
| 185 |
-
# ==========================================
|
| 186 |
pdf_data = {
|
| 187 |
-
"title": pdf_button_name,
|
| 188 |
"url": hf_pdf_url,
|
| 189 |
-
"original_name": file_name,
|
| 190 |
"show_blocker": True
|
| 191 |
}
|
| 192 |
requests.post(f"{pdf_folder_url}.json", json=pdf_data)
|
|
@@ -200,9 +196,11 @@ def handle_new_pdf(client, message):
|
|
| 200 |
# ==========================================
|
| 201 |
# 6. RUN ALL
|
| 202 |
# ==========================================
|
|
|
|
|
|
|
| 203 |
if __name__ == "__main__":
|
| 204 |
threading.Thread(target=run_flask).start()
|
| 205 |
-
|
| 206 |
async def main():
|
| 207 |
print("π Systems Online: Pyrogram + Report Bot + Auto-Uploader")
|
| 208 |
await compose([app, bot_app])
|
|
|
|
| 12 |
# ==========================================
|
| 13 |
# π APNI DETAILS YAHAN DAALEIN π
|
| 14 |
# ==========================================
|
| 15 |
+
|
| 16 |
API_ID = "35985614"
|
| 17 |
API_HASH = "6a0df17414daf6935f1f0a71b8af1ee9"
|
| 18 |
STRING_SESSION = "BQIlGM4AkncApFEGc9JNMRHYJCqi-IbbXCuSEw7yrNIcloArm-xwbEM8ksoMYQEK4_uD1NEgro-CIDXnc6yEuaPkm91FGhHVpHJGoUnvv19UeilrIhopSY8dboZ0emUF15IhIgZD6Qqp5Nv2gJobdCrZQuitAS6Xelmm14rn-3kWynpUo3vD4GpeRWh1b8ydh8Rlqi1ALoWOHC5uGyK_zJBAnxDUea2FJUvgX2Q93TuejnVuj4o84M_DqMtHowvf5EGkE4HSZfjPW6c5Qb2VkFtRwFmt1-6hZGoABJjvrJpZQmc94LLApSd45Hme-YXpPrxGWck4mFF0t8SRYrPGMxyyVJRgAAAAHK_kURAA"
|
| 19 |
+
# YAHAN INT() LAGANA ZAROORI HAI:
|
| 20 |
+
TARGET_CHAT = int("-1002545525249")
|
| 21 |
|
| 22 |
BOT_TOKEN = "8830608789:AAF7J6I-1H1mzRkpccgCOuTh2wR_yOSOMNA"
|
| 23 |
|
| 24 |
+
HF_TOKEN = os.environ.get("HF_TOKEN")
|
|
|
|
| 25 |
HF_REPO_ID = "Jitendra55566/pdf-notes"
|
| 26 |
FIREBASE_URL = "https://logo-ncc-default-rtdb.asia-southeast1.firebasedatabase.app"
|
| 27 |
|
| 28 |
# ==========================================
|
| 29 |
# 1. DAILY STATS TRACKER
|
| 30 |
# ==========================================
|
| 31 |
+
|
| 32 |
def get_ist_date():
|
| 33 |
ist_time = datetime.utcnow() + timedelta(hours=5, minutes=30)
|
| 34 |
return ist_time.strftime("%d-%m-%Y")
|
|
|
|
| 49 |
daily_stats["details"].append(f"β
{subject} β {chapter} ({pdf_name})")
|
| 50 |
|
| 51 |
# ==========================================
|
| 52 |
+
# 2. FLASK SERVER (Keep Awake)
|
| 53 |
# ==========================================
|
| 54 |
+
|
| 55 |
web_app = Flask(__name__)
|
| 56 |
|
| 57 |
@web_app.route('/')
|
|
|
|
| 64 |
# ==========================================
|
| 65 |
# 3. TELEGRAM CLIENTS SETUP
|
| 66 |
# ==========================================
|
| 67 |
+
|
| 68 |
app = Client("user_account", session_string=STRING_SESSION, api_id=API_ID, api_hash=API_HASH)
|
| 69 |
bot_app = Client("report_bot", bot_token=BOT_TOKEN, api_id=API_ID, api_hash=API_HASH)
|
| 70 |
hf_api = HfApi()
|
|
|
|
| 72 |
# ==========================================
|
| 73 |
# 4. REPORT BOT HANDLERS (@BotFather bot)
|
| 74 |
# ==========================================
|
| 75 |
+
|
| 76 |
@bot_app.on_message(filters.command("start"))
|
| 77 |
async def start_cmd(client, message):
|
| 78 |
text = "π Hello Sir!\n\nMain auto-upload bot hu.\nπ Aaj ki Report dekhne ke liye π /today"
|
|
|
|
| 85 |
daily_stats["date"] = today
|
| 86 |
daily_stats["count"] = 0
|
| 87 |
daily_stats["details"] = []
|
| 88 |
+
|
| 89 |
if daily_stats["count"] == 0:
|
| 90 |
await message.reply_text(f"π
Date: {today}\n\nπ΄ Aaj abhi tak koi PDF upload nahi hui.")
|
| 91 |
else:
|
|
|
|
| 96 |
# ==========================================
|
| 97 |
# 5. USER ACCOUNT LOGIC (PDF DOWNLOAD & UPLOAD)
|
| 98 |
# ==========================================
|
| 99 |
+
|
| 100 |
def upload_to_huggingface(file_path, file_name):
|
| 101 |
hf_api.upload_file(
|
| 102 |
path_or_fileobj=file_path,
|
|
|
|
| 117 |
res = requests.post(f"{base_url}.json", json=create_data)
|
| 118 |
return res.json()['name']
|
| 119 |
|
| 120 |
+
# π΄ FIX: Added "async" here
|
| 121 |
@app.on_message(filters.chat(TARGET_CHAT) & filters.document)
|
| 122 |
+
async def handle_new_pdf(client, message):
|
| 123 |
text = message.caption if message.caption else ""
|
| 124 |
if not text:
|
| 125 |
return
|
| 126 |
|
| 127 |
try:
|
| 128 |
+
# EXTRACT DATA
|
| 129 |
file_name_match = re.search(r"File Name\s*:\s*(.*?)\.pdf", text, re.IGNORECASE)
|
| 130 |
file_name = file_name_match.group(1).strip() if file_name_match else "Unknown"
|
| 131 |
|
|
|
|
| 138 |
if not batch_name or not subject_name:
|
| 139 |
return
|
| 140 |
|
|
|
|
| 141 |
chapter_match = re.search(r"\((.*?)\)(?!\s*ΰ€΅ΰ₯ΰ€° ΰ€¬ΰ₯ΰ€)", file_name)
|
| 142 |
chapter_name = chapter_match.group(1).strip() if chapter_match else "General"
|
| 143 |
|
|
|
|
| 144 |
parts = file_name.split(')')
|
| 145 |
class_str = parts[-1] if len(parts) > 1 else file_name
|
| 146 |
+
class_str = re.sub(r'(?i)PDF.*', '', class_str).strip()
|
| 147 |
+
video_name = re.sub(r'\s*\d+$', '', class_str).strip()
|
| 148 |
|
| 149 |
+
# FIREBASE (We keep it synchronous for simplicity, but it's fast)
|
|
|
|
|
|
|
| 150 |
cat_id = find_or_create_node(f"{FIREBASE_URL}/categories", batch_name, {"title": batch_name})
|
| 151 |
sub_id = find_or_create_node(f"{FIREBASE_URL}/categories/{cat_id}/subcategories", subject_name, {"title": subject_name})
|
| 152 |
chap_id = find_or_create_node(f"{FIREBASE_URL}/categories/{cat_id}/subcategories/{sub_id}/subcategories", chapter_name, {"title": chapter_name})
|
| 153 |
|
|
|
|
| 154 |
vid_id = find_or_create_node(f"{FIREBASE_URL}/categories/{cat_id}/subcategories/{sub_id}/subcategories/{chap_id}/videos", video_name, {
|
| 155 |
"title": video_name,
|
| 156 |
+
"url": "https://dummy-video-url.com",
|
| 157 |
"date": int(time.time() * 1000)
|
| 158 |
})
|
| 159 |
|
|
|
|
|
|
|
|
|
|
| 160 |
pdf_folder_url = f"{FIREBASE_URL}/categories/{cat_id}/subcategories/{sub_id}/subcategories/{chap_id}/videos/{vid_id}/pdfs"
|
| 161 |
existing_pdfs = requests.get(f"{pdf_folder_url}.json").json() or {}
|
| 162 |
|
| 163 |
pdf_count = 0
|
| 164 |
for pid, pdata in existing_pdfs.items():
|
| 165 |
pdf_count += 1
|
|
|
|
| 166 |
if pdata.get('original_name') == file_name:
|
| 167 |
print(f"Skipping! '{file_name}' pehle se maujud hai.")
|
| 168 |
return
|
| 169 |
|
|
|
|
| 170 |
pdf_button_name = f"PDF {pdf_count + 1}"
|
| 171 |
|
|
|
|
|
|
|
|
|
|
| 172 |
print(f"Downloading: {file_name}.pdf")
|
| 173 |
+
|
| 174 |
+
# π΄ FIX: Added 'await' before message.download()
|
| 175 |
+
local_path = await message.download()
|
| 176 |
+
|
| 177 |
+
# π΄ FIX: Run HuggingFace upload in background thread so Bot doesn't freeze!
|
| 178 |
+
hf_pdf_url = await asyncio.to_thread(upload_to_huggingface, local_path, f"{int(time.time())}_{file_name}.pdf")
|
| 179 |
+
|
| 180 |
os.remove(local_path)
|
| 181 |
|
|
|
|
|
|
|
|
|
|
| 182 |
pdf_data = {
|
| 183 |
+
"title": pdf_button_name,
|
| 184 |
"url": hf_pdf_url,
|
| 185 |
+
"original_name": file_name,
|
| 186 |
"show_blocker": True
|
| 187 |
}
|
| 188 |
requests.post(f"{pdf_folder_url}.json", json=pdf_data)
|
|
|
|
| 196 |
# ==========================================
|
| 197 |
# 6. RUN ALL
|
| 198 |
# ==========================================
|
| 199 |
+
|
| 200 |
+
# π΄ FIX: Corrected __main__ condition syntax
|
| 201 |
if __name__ == "__main__":
|
| 202 |
threading.Thread(target=run_flask).start()
|
| 203 |
+
|
| 204 |
async def main():
|
| 205 |
print("π Systems Online: Pyrogram + Report Bot + Auto-Uploader")
|
| 206 |
await compose([app, bot_app])
|