Cxops commited on
Commit
61bfa47
Β·
verified Β·
1 Parent(s): e040a5f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -38
app.py CHANGED
@@ -136,9 +136,14 @@ def format_size(bytes_val):
136
  def format_speed(bytes_per_sec):
137
  return f"{format_size(bytes_per_sec)}/s"
138
 
139
- # --------------- PROGRESS UPDATER ---------------
140
  def start_progress_updater(job_id: int, status_msg, cancel_event: asyncio.Event,
141
- total_bytes: Optional[int] = None, is_upload: bool = True):
 
 
 
 
 
142
  bytes_holder = [0]
143
  start_time = time.time()
144
 
@@ -151,7 +156,7 @@ def start_progress_updater(job_id: int, status_msg, cancel_event: asyncio.Event,
151
  if total_bytes and total_bytes > 0:
152
  pct = min(100 * current / total_bytes, 100)
153
  text = f"{pct:.1f}% of {format_size(total_bytes)}\n"
154
- text += f"{format_size(current)} {'uploaded' if is_upload else 'downloaded'}\n"
155
  text += f"Speed: {format_speed(speed)}\n"
156
  if total_bytes and speed > 0:
157
  eta = (total_bytes - current) / speed
@@ -180,15 +185,21 @@ async def do_upload_job(user_id: int, chat_id: int, file_msg, orig_filename: str
180
  temp_dir = tempfile.mkdtemp()
181
  local_path = None
182
  try:
183
- # Download from Telegram with progress
184
- download_bytes_holder = [0]
185
- start_time = time.time()
 
 
 
186
 
187
  async def download_progress(current, total):
188
- download_bytes_holder[0] = current
189
- elapsed = max(time.time() - start_time, 0.01)
 
 
 
190
  speed = current / elapsed
191
- pct = min(100 * current / total, 100) if total else 0
192
  text = f"⬇️ Downloading from Telegram...\n{pct:.1f}% of {format_size(total)}\n{format_size(current)} downloaded\nSpeed: {format_speed(speed)}"
193
  try:
194
  await status_msg.edit_text(
@@ -200,6 +211,7 @@ async def do_upload_job(user_id: int, chat_id: int, file_msg, orig_filename: str
200
  except Exception:
201
  pass
202
 
 
203
  local_path = await file_msg.download(
204
  file_name=os.path.join(temp_dir, orig_filename),
205
  progress=download_progress
@@ -208,16 +220,17 @@ async def do_upload_job(user_id: int, chat_id: int, file_msg, orig_filename: str
208
  return
209
  file_size = os.path.getsize(local_path)
210
 
211
- # Upload to Hugging Face
212
  enc_folder = get_encrypted_folder(user_id)
213
  enc_filename = get_encrypted_filename(orig_filename)
214
  repo_path = f"{enc_folder}/{enc_filename}"
215
 
216
  prog = start_progress_updater(job_id, status_msg, cancel_event,
217
- total_bytes=file_size, is_upload=True)
218
  upload_prog_task = prog['task']
219
  upload_bytes_holder = prog['bytes']
220
 
 
221
  async def simulate_upload():
222
  start = time.time()
223
  while not cancel_event.is_set():
@@ -248,6 +261,7 @@ async def do_upload_job(user_id: int, chat_id: int, file_msg, orig_filename: str
248
  await asyncio.sleep(1)
249
 
250
  if cancel_event.is_set():
 
251
  try:
252
  hf.delete_file(
253
  path_in_repo=repo_path,
@@ -258,10 +272,7 @@ async def do_upload_job(user_id: int, chat_id: int, file_msg, orig_filename: str
258
  pass
259
  upload_prog_task.cancel()
260
  sim_task.cancel()
261
- try:
262
- await status_msg.edit_text("❌ Upload cancelled.", reply_markup=None)
263
- except Exception:
264
- pass
265
  return
266
 
267
  await task
@@ -271,7 +282,6 @@ async def do_upload_job(user_id: int, chat_id: int, file_msg, orig_filename: str
271
  sim_task.cancel()
272
 
273
  db_add_file(user_id, repo_path, orig_filename, file_size)
274
-
275
  await status_msg.edit_text(f"βœ… Uploaded: `{orig_filename}`", reply_markup=None)
276
 
277
  except Exception as e:
@@ -286,27 +296,22 @@ async def do_download_job(chat_id: int, enc_path: str, orig_name: str,
286
  try:
287
  loop = asyncio.get_event_loop()
288
 
289
- # Correct way to get file size: build URL with hf_hub_url
290
- file_url = hf_hub_url(
291
- repo_id=DATASET_REPO,
292
- filename=enc_path,
293
- repo_type="dataset"
294
- )
295
  metadata = await loop.run_in_executor(
296
  None,
297
  lambda: get_hf_file_metadata(url=file_url, token=HF_TOKEN)
298
  )
299
  total_size = metadata.size
300
 
 
301
  prog = start_progress_updater(job_id, status_msg, cancel_event,
302
- total_bytes=total_size, is_upload=False)
303
  prog_task = prog['task']
304
  bytes_holder = prog['bytes']
305
 
306
  local_file = os.path.join(temp_dir, "downloaded_file")
307
 
308
- download_done = loop.create_future()
309
-
310
  def sync_download_with_progress():
311
  headers = {"Authorization": f"Bearer {HF_TOKEN}"}
312
  resp = requests.get(file_url, stream=True, headers=headers)
@@ -339,9 +344,26 @@ async def do_download_job(chat_id: int, enc_path: str, orig_name: str,
339
  prog_task.cancel()
340
 
341
  file_size = os.path.getsize(local_file)
 
 
342
  if file_size <= MAX_FILE_SIZE_TG:
343
- await status_msg.edit_text("πŸ“€ Sending file to Telegram...", reply_markup=None)
344
- await app.send_document(chat_id, document=local_file, file_name=orig_name, caption=orig_name)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
345
  await status_msg.delete()
346
  else:
347
  part_size = MAX_FILE_SIZE_TG
@@ -367,6 +389,26 @@ async def do_download_job(chat_id: int, enc_path: str, orig_name: str,
367
  finally:
368
  cleanup(temp_dir)
369
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
370
  # --------------- QUEUE WORKER ---------------
371
  async def upload_worker():
372
  while True:
@@ -401,7 +443,7 @@ async def start_cmd(_, message):
401
  )
402
 
403
  @app.on_message(filters.command("files"))
404
- async def list_files(_, message):
405
  user_id = message.from_user.id
406
  user_files = db_get_user_files(user_id)
407
 
@@ -418,11 +460,7 @@ async def list_files(_, message):
418
  except Exception:
419
  orig_name = enc_name
420
  try:
421
- file_url = hf_hub_url(
422
- repo_id=DATASET_REPO,
423
- filename=path,
424
- repo_type="dataset"
425
- )
426
  meta = get_hf_file_metadata(url=file_url, token=HF_TOKEN)
427
  size = meta.size
428
  except Exception:
@@ -436,22 +474,27 @@ async def list_files(_, message):
436
  return await message.reply_text("You have no uploaded files.")
437
 
438
  buttons = []
439
- for enc_path, orig_name, _ in user_files:
440
  token = make_token()
441
  file_callback_map[token] = enc_path
442
- buttons.append([InlineKeyboardButton(orig_name[:60], callback_data=f"get:{token}")])
 
 
 
 
 
443
 
444
  await message.reply_text(
445
- "Your uploaded files:",
446
  reply_markup=InlineKeyboardMarkup(buttons)
447
  )
448
 
449
  @app.on_callback_query(filters.regex("^get:"))
450
  async def get_file_callback(_, query):
451
  token = query.data.replace("get:", "")
452
- enc_path = file_callback_map.pop(token, None)
453
  if not enc_path:
454
- return await query.answer("This file list is no longer valid. Please use /files again.", show_alert=True)
455
 
456
  job_id = int(time.time() * 1000)
457
  cancel_event = asyncio.Event()
@@ -479,6 +522,33 @@ async def get_file_callback(_, query):
479
  status_msg
480
  ))
481
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
482
  @app.on_callback_query(filters.regex("^cancel_job:"))
483
  async def cancel_job_callback(_, query):
484
  _, job_id_str = query.data.split(":")
 
136
  def format_speed(bytes_per_sec):
137
  return f"{format_size(bytes_per_sec)}/s"
138
 
139
+ # --------------- PROGRESS UPDATER (GENERIC) ---------------
140
  def start_progress_updater(job_id: int, status_msg, cancel_event: asyncio.Event,
141
+ total_bytes: Optional[int] = None, action: str = "uploading"):
142
+ """
143
+ Launches a background task that edits status_msg every 3 seconds with progress.
144
+ action is a string like "uploading", "downloading", "sending"
145
+ Returns {'task': asyncio.Task, 'bytes': list} where bytes[0] should be updated regularly.
146
+ """
147
  bytes_holder = [0]
148
  start_time = time.time()
149
 
 
156
  if total_bytes and total_bytes > 0:
157
  pct = min(100 * current / total_bytes, 100)
158
  text = f"{pct:.1f}% of {format_size(total_bytes)}\n"
159
+ text += f"{format_size(current)} {action}\n"
160
  text += f"Speed: {format_speed(speed)}\n"
161
  if total_bytes and speed > 0:
162
  eta = (total_bytes - current) / speed
 
185
  temp_dir = tempfile.mkdtemp()
186
  local_path = None
187
  try:
188
+ # Step 1: Download from Telegram with progress
189
+ await status_msg.edit_text("⬇️ Downloading from Telegram...",
190
+ reply_markup=InlineKeyboardMarkup([
191
+ [InlineKeyboardButton("❌ Cancel", callback_data=f"cancel_job:{job_id}")]
192
+ ]))
193
+ last_update = [0]
194
 
195
  async def download_progress(current, total):
196
+ now = time.time()
197
+ if now - last_update[0] < 3:
198
+ return
199
+ last_update[0] = now
200
+ elapsed = max(time.time() - download_start, 0.01)
201
  speed = current / elapsed
202
+ pct = (100 * current / total) if total else 0
203
  text = f"⬇️ Downloading from Telegram...\n{pct:.1f}% of {format_size(total)}\n{format_size(current)} downloaded\nSpeed: {format_speed(speed)}"
204
  try:
205
  await status_msg.edit_text(
 
211
  except Exception:
212
  pass
213
 
214
+ download_start = time.time()
215
  local_path = await file_msg.download(
216
  file_name=os.path.join(temp_dir, orig_filename),
217
  progress=download_progress
 
220
  return
221
  file_size = os.path.getsize(local_path)
222
 
223
+ # Step 2: Upload to Hugging Face (no real-time progress from library)
224
  enc_folder = get_encrypted_folder(user_id)
225
  enc_filename = get_encrypted_filename(orig_filename)
226
  repo_path = f"{enc_folder}/{enc_filename}"
227
 
228
  prog = start_progress_updater(job_id, status_msg, cancel_event,
229
+ total_bytes=file_size, action="uploaded")
230
  upload_prog_task = prog['task']
231
  upload_bytes_holder = prog['bytes']
232
 
233
+ # Simulate progress based on time (assume ~10 MB/s)
234
  async def simulate_upload():
235
  start = time.time()
236
  while not cancel_event.is_set():
 
261
  await asyncio.sleep(1)
262
 
263
  if cancel_event.is_set():
264
+ # Try to delete the partially uploaded file
265
  try:
266
  hf.delete_file(
267
  path_in_repo=repo_path,
 
272
  pass
273
  upload_prog_task.cancel()
274
  sim_task.cancel()
275
+ await status_msg.edit_text("❌ Upload cancelled.", reply_markup=None)
 
 
 
276
  return
277
 
278
  await task
 
282
  sim_task.cancel()
283
 
284
  db_add_file(user_id, repo_path, orig_filename, file_size)
 
285
  await status_msg.edit_text(f"βœ… Uploaded: `{orig_filename}`", reply_markup=None)
286
 
287
  except Exception as e:
 
296
  try:
297
  loop = asyncio.get_event_loop()
298
 
299
+ # Get file metadata
300
+ file_url = hf_hub_url(repo_id=DATASET_REPO, filename=enc_path, repo_type="dataset")
 
 
 
 
301
  metadata = await loop.run_in_executor(
302
  None,
303
  lambda: get_hf_file_metadata(url=file_url, token=HF_TOKEN)
304
  )
305
  total_size = metadata.size
306
 
307
+ # Progress for download
308
  prog = start_progress_updater(job_id, status_msg, cancel_event,
309
+ total_bytes=total_size, action="downloaded")
310
  prog_task = prog['task']
311
  bytes_holder = prog['bytes']
312
 
313
  local_file = os.path.join(temp_dir, "downloaded_file")
314
 
 
 
315
  def sync_download_with_progress():
316
  headers = {"Authorization": f"Bearer {HF_TOKEN}"}
317
  resp = requests.get(file_url, stream=True, headers=headers)
 
344
  prog_task.cancel()
345
 
346
  file_size = os.path.getsize(local_file)
347
+
348
+ # Send file (split if needed) with upload progress
349
  if file_size <= MAX_FILE_SIZE_TG:
350
+ # Progress for sending
351
+ prog_send = start_progress_updater(job_id, status_msg, cancel_event,
352
+ total_bytes=file_size, action="sent")
353
+ prog_send_task = prog_send['task']
354
+ send_bytes_holder = prog_send['bytes']
355
+
356
+ async def send_progress(current, total):
357
+ send_bytes_holder[0] = current
358
+
359
+ await app.send_document(
360
+ chat_id,
361
+ document=local_file,
362
+ file_name=orig_name,
363
+ caption=orig_name,
364
+ progress=send_progress
365
+ )
366
+ prog_send_task.cancel()
367
  await status_msg.delete()
368
  else:
369
  part_size = MAX_FILE_SIZE_TG
 
389
  finally:
390
  cleanup(temp_dir)
391
 
392
+ # --------------- DELETE FILE ---------------
393
+ async def delete_user_file(chat_id: int, user_id: int, enc_path: str, token: str, query):
394
+ try:
395
+ # Delete from Hugging Face
396
+ hf.delete_file(
397
+ path_in_repo=enc_path,
398
+ repo_id=DATASET_REPO,
399
+ repo_type="dataset",
400
+ )
401
+ # Remove from database
402
+ db_remove_file(enc_path)
403
+ # Remove from callback map
404
+ file_callback_map.pop(token, None)
405
+ await query.answer("File deleted successfully.", show_alert=True)
406
+ # Refresh the file list message
407
+ await list_files(_, query.message) # we'll need to call the actual handler, but we don't have the client here; simpler: edit the message
408
+ # Instead, we'll just remove the button row (or update the message)
409
+ except Exception as e:
410
+ await query.answer(f"Error deleting file: {e}", show_alert=True)
411
+
412
  # --------------- QUEUE WORKER ---------------
413
  async def upload_worker():
414
  while True:
 
443
  )
444
 
445
  @app.on_message(filters.command("files"))
446
+ async def list_files_cmd(_, message):
447
  user_id = message.from_user.id
448
  user_files = db_get_user_files(user_id)
449
 
 
460
  except Exception:
461
  orig_name = enc_name
462
  try:
463
+ file_url = hf_hub_url(repo_id=DATASET_REPO, filename=path, repo_type="dataset")
 
 
 
 
464
  meta = get_hf_file_metadata(url=file_url, token=HF_TOKEN)
465
  size = meta.size
466
  except Exception:
 
474
  return await message.reply_text("You have no uploaded files.")
475
 
476
  buttons = []
477
+ for enc_path, orig_name, size in user_files:
478
  token = make_token()
479
  file_callback_map[token] = enc_path
480
+ # Two buttons: Download and Delete
481
+ row = [
482
+ InlineKeyboardButton(f"πŸ“₯ {orig_name[:40]}", callback_data=f"get:{token}"),
483
+ InlineKeyboardButton("πŸ—‘ Delete", callback_data=f"delete:{token}")
484
+ ]
485
+ buttons.append(row)
486
 
487
  await message.reply_text(
488
+ "Your uploaded files (click to download, delete to remove):",
489
  reply_markup=InlineKeyboardMarkup(buttons)
490
  )
491
 
492
  @app.on_callback_query(filters.regex("^get:"))
493
  async def get_file_callback(_, query):
494
  token = query.data.replace("get:", "")
495
+ enc_path = file_callback_map.get(token)
496
  if not enc_path:
497
+ return await query.answer("Invalid or expired file link. Use /files again.", show_alert=True)
498
 
499
  job_id = int(time.time() * 1000)
500
  cancel_event = asyncio.Event()
 
522
  status_msg
523
  ))
524
 
525
+ @app.on_callback_query(filters.regex("^delete:"))
526
+ async def delete_file_callback(_, query):
527
+ token = query.data.replace("delete:", "")
528
+ enc_path = file_callback_map.pop(token, None)
529
+ if not enc_path:
530
+ return await query.answer("File not found or already deleted.", show_alert=True)
531
+
532
+ user_id = query.from_user.id
533
+ chat_id = query.message.chat.id
534
+
535
+ # Delete from HF and DB
536
+ try:
537
+ hf.delete_file(
538
+ path_in_repo=enc_path,
539
+ repo_id=DATASET_REPO,
540
+ repo_type="dataset",
541
+ )
542
+ db_remove_file(enc_path)
543
+ await query.answer("File deleted.", show_alert=True)
544
+
545
+ # Remove the button row by editing the message (optional)
546
+ # We'll just remove that specific button row from the keyboard.
547
+ # Better: refresh the whole list.
548
+ await list_files_cmd(_, query.message) # this will edit the same message with the updated list
549
+ except Exception as e:
550
+ await query.answer(f"Error deleting file: {e}", show_alert=True)
551
+
552
  @app.on_callback_query(filters.regex("^cancel_job:"))
553
  async def cancel_job_callback(_, query):
554
  _, job_id_str = query.data.split(":")