pmrony commited on
Commit
0f1a29e
·
verified ·
1 Parent(s): 9a2953f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -10
app.py CHANGED
@@ -1090,17 +1090,23 @@ async def process_single_video(task, redis_client):
1090
  wm_text = task['watermark_text']
1091
  task_id = f"{owner_id}_{message_id}"
1092
 
 
 
1093
  clone_client = Client(f"clone_wm_{task_id}", bot_token=clone_token, api_id=API_ID, api_hash=API_HASH, in_memory=True)
1094
- await clone_client.start()
1095
 
1096
  try:
 
 
 
1097
  msg = await clone_client.get_messages(owner_id, message_id)
1098
  if not msg or not (msg.video or msg.document):
1099
- raise Exception("Video not found or deleted.")
1100
 
1101
  status_msg = await clone_client.send_message(owner_id, "⏳ <b>Video processing started...</b>", parse_mode=enums.ParseMode.HTML)
 
1102
 
1103
  raw_video_path = await clone_client.download_media(msg)
 
1104
 
1105
  await clone_client.edit_message_text(owner_id, status_msg.id, "⏳ <b>Uploading original file to secure storage...</b>", parse_mode=enums.ParseMode.HTML)
1106
 
@@ -1112,6 +1118,7 @@ async def process_single_video(task, redis_client):
1112
  raw_storage_id = raw_sent.id
1113
  stream_link = f"{BACKEND_URL}/stream/{raw_storage_id}"
1114
  download_link = f"{BACKEND_URL}/download/{raw_storage_id}"
 
1115
 
1116
  await clone_client.edit_message_text(owner_id, status_msg.id, "⏳ <b>Applying Custom Watermark... (This may take a few minutes)</b>", parse_mode=enums.ParseMode.HTML)
1117
 
@@ -1124,12 +1131,15 @@ async def process_single_video(task, redis_client):
1124
  "-c:a", "copy", "-movflags", "+faststart", watermarked_path
1125
  ]
1126
 
 
1127
  process = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
1128
- await process.communicate()
1129
 
1130
- if not os.path.exists(watermarked_path) or os.path.getsize(watermarked_path) == 0:
1131
- raise Exception("FFmpeg processing failed.")
 
1132
 
 
1133
  await clone_client.edit_message_text(owner_id, status_msg.id, "⏳ <b>Uploading final video...</b>", parse_mode=enums.ParseMode.HTML)
1134
 
1135
  await bot.send_video(
@@ -1137,6 +1147,7 @@ async def process_single_video(task, redis_client):
1137
  video=watermarked_path,
1138
  caption=f"Watermarked Backup for Clone Owner {owner_id}"
1139
  )
 
1140
 
1141
  final_caption = (
1142
  f"✅ <b>Watermark Successfully Added!</b>\n\n"
@@ -1150,6 +1161,7 @@ async def process_single_video(task, redis_client):
1150
  caption=final_caption,
1151
  parse_mode=enums.ParseMode.HTML
1152
  )
 
1153
 
1154
  await clone_client.delete_messages(owner_id, status_msg.id)
1155
 
@@ -1157,14 +1169,17 @@ async def process_single_video(task, redis_client):
1157
  if os.path.exists(watermarked_path): os.remove(watermarked_path)
1158
 
1159
  except Exception as e:
 
1160
  try:
1161
  await clone_client.send_message(owner_id, f"❌ <b>Error processing video:</b> {e}", parse_mode=enums.ParseMode.HTML)
1162
- except: pass
 
1163
 
1164
  finally:
1165
  await clone_client.stop()
1166
  await redis_client.delete(f"wm_processing:{owner_id}")
1167
  processing_owners.discard(owner_id)
 
1168
 
1169
  async def watermark_processor_loop():
1170
  global processing_owners
@@ -1181,6 +1196,7 @@ async def watermark_processor_loop():
1181
  print(f"❌ Redis Connection Failed in Hugging Face: {e}")
1182
  return
1183
 
 
1184
  try:
1185
  async for key in redis_client.scan_iter("wm_processing:*"):
1186
  await redis_client.delete(key)
@@ -1192,19 +1208,23 @@ async def watermark_processor_loop():
1192
  await asyncio.sleep(2)
1193
  continue
1194
 
1195
- result = await redis_client.brpop("watermark_task_queue", timeout=5)
 
1196
 
1197
  if result:
1198
- _, task_json = result
1199
- task = json.loads(task_json)
1200
  owner_id = task['owner_id']
1201
 
1202
  processing_owners.add(owner_id)
1203
  asyncio.create_task(process_single_video(task, redis_client))
 
 
1204
 
1205
  except Exception as e:
 
1206
  await asyncio.sleep(2)
1207
-
1208
  def run_flask(): app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 7860)), threaded=True)
1209
 
1210
  async def main():
 
1090
  wm_text = task['watermark_text']
1091
  task_id = f"{owner_id}_{message_id}"
1092
 
1093
+ print(f"▶️ [WM] Task Started for User: {owner_id}, Msg: {message_id}")
1094
+
1095
  clone_client = Client(f"clone_wm_{task_id}", bot_token=clone_token, api_id=API_ID, api_hash=API_HASH, in_memory=True)
 
1096
 
1097
  try:
1098
+ await clone_client.start()
1099
+ print(f"▶️ [WM] Clone Client Started Successfully")
1100
+
1101
  msg = await clone_client.get_messages(owner_id, message_id)
1102
  if not msg or not (msg.video or msg.document):
1103
+ raise Exception("Video not found or deleted by user.")
1104
 
1105
  status_msg = await clone_client.send_message(owner_id, "⏳ <b>Video processing started...</b>", parse_mode=enums.ParseMode.HTML)
1106
+ print(f"▶️ [WM] Status Message Sent to User")
1107
 
1108
  raw_video_path = await clone_client.download_media(msg)
1109
+ print(f"▶️ [WM] Original Video Downloaded: {raw_video_path}")
1110
 
1111
  await clone_client.edit_message_text(owner_id, status_msg.id, "⏳ <b>Uploading original file to secure storage...</b>", parse_mode=enums.ParseMode.HTML)
1112
 
 
1118
  raw_storage_id = raw_sent.id
1119
  stream_link = f"{BACKEND_URL}/stream/{raw_storage_id}"
1120
  download_link = f"{BACKEND_URL}/download/{raw_storage_id}"
1121
+ print(f"▶️ [WM] Original Backup Uploaded to Storage")
1122
 
1123
  await clone_client.edit_message_text(owner_id, status_msg.id, "⏳ <b>Applying Custom Watermark... (This may take a few minutes)</b>", parse_mode=enums.ParseMode.HTML)
1124
 
 
1131
  "-c:a", "copy", "-movflags", "+faststart", watermarked_path
1132
  ]
1133
 
1134
+ print(f"▶️ [WM] Starting FFmpeg processing...")
1135
  process = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
1136
+ stdout, stderr = await process.communicate()
1137
 
1138
+ if process.returncode != 0 or not os.path.exists(watermarked_path) or os.path.getsize(watermarked_path) == 0:
1139
+ print(f"❌ [WM] FFmpeg Error: {stderr.decode()}")
1140
+ raise Exception("FFmpeg processing failed! The video format might be unsupported.")
1141
 
1142
+ print(f"▶️ [WM] FFmpeg Processing Complete!")
1143
  await clone_client.edit_message_text(owner_id, status_msg.id, "⏳ <b>Uploading final video...</b>", parse_mode=enums.ParseMode.HTML)
1144
 
1145
  await bot.send_video(
 
1147
  video=watermarked_path,
1148
  caption=f"Watermarked Backup for Clone Owner {owner_id}"
1149
  )
1150
+ print(f"▶️ [WM] Watermarked Backup Uploaded to Storage")
1151
 
1152
  final_caption = (
1153
  f"✅ <b>Watermark Successfully Added!</b>\n\n"
 
1161
  caption=final_caption,
1162
  parse_mode=enums.ParseMode.HTML
1163
  )
1164
+ print(f"▶️ [WM] Final Video Sent to User Successfully!")
1165
 
1166
  await clone_client.delete_messages(owner_id, status_msg.id)
1167
 
 
1169
  if os.path.exists(watermarked_path): os.remove(watermarked_path)
1170
 
1171
  except Exception as e:
1172
+ print(f"❌ [WM] Process Error: {e}")
1173
  try:
1174
  await clone_client.send_message(owner_id, f"❌ <b>Error processing video:</b> {e}", parse_mode=enums.ParseMode.HTML)
1175
+ except Exception as ex:
1176
+ print(f"❌ [WM] Failed to send error msg to user: {ex}")
1177
 
1178
  finally:
1179
  await clone_client.stop()
1180
  await redis_client.delete(f"wm_processing:{owner_id}")
1181
  processing_owners.discard(owner_id)
1182
+ print(f"▶️ [WM] Task Cleaned Up and Client Stopped")
1183
 
1184
  async def watermark_processor_loop():
1185
  global processing_owners
 
1196
  print(f"❌ Redis Connection Failed in Hugging Face: {e}")
1197
  return
1198
 
1199
+ # সার্ভার রিস্টার্ট হলে আটকে থাকা লকগুলো ক্লিয়ার করবে
1200
  try:
1201
  async for key in redis_client.scan_iter("wm_processing:*"):
1202
  await redis_client.delete(key)
 
1208
  await asyncio.sleep(2)
1209
  continue
1210
 
1211
+ # BRPOP এর বদলে RPOP ব্যবহার করা হলো (Upstash Connection Drop এড়াতে)
1212
+ result = await redis_client.rpop("watermark_task_queue")
1213
 
1214
  if result:
1215
+ print(f"📥 [WM] Received New Video Task from Queue!")
1216
+ task = json.loads(result)
1217
  owner_id = task['owner_id']
1218
 
1219
  processing_owners.add(owner_id)
1220
  asyncio.create_task(process_single_video(task, redis_client))
1221
+ else:
1222
+ await asyncio.sleep(2) # ভিডিও না থাকলে ২ সেকেন্ড পর আবার চেক করবে
1223
 
1224
  except Exception as e:
1225
+ print(f"❌ [WM] Loop Error: {e}")
1226
  await asyncio.sleep(2)
1227
+
1228
  def run_flask(): app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 7860)), threaded=True)
1229
 
1230
  async def main():