Gemini CLI commited on
Commit
197e4fa
Β·
1 Parent(s): f4f368d

feat: upgrade compression to 7-zip and add video compression with ffmpeg

Browse files
Files changed (4) hide show
  1. Dockerfile +2 -0
  2. app.py +28 -4
  3. bot.py +128 -7
  4. features.txt +2 -1
Dockerfile CHANGED
@@ -7,6 +7,8 @@ WORKDIR /app
7
  # Install system dependencies
8
  RUN apt-get update && apt-get install -y \
9
  build-essential \
 
 
10
  && rm -rf /var/lib/apt/lists/*
11
 
12
  # Copy the requirements file into the container
 
7
  # Install system dependencies
8
  RUN apt-get update && apt-get install -y \
9
  build-essential \
10
+ p7zip-full \
11
+ ffmpeg \
12
  && rm -rf /var/lib/apt/lists/*
13
 
14
  # Copy the requirements file into the container
app.py CHANGED
@@ -49,6 +49,7 @@ async def start_bot_safe():
49
  BotCommand("start", "Start the bot"),
50
  BotCommand("zip", "Create ZIP"),
51
  BotCommand("pdf_merge", "Merge PDFs"),
 
52
  BotCommand("search", "Search your files"),
53
  BotCommand("settings", "Bot settings"),
54
  BotCommand("files", "My files"),
@@ -123,25 +124,48 @@ def get_password_wall(target_name: str, error: bool = False):
123
  @app.get("/view/{user_id}/{batch_id}")
124
  async def view_batch(user_id: str, batch_id: str, password: Optional[str] = Query(None)):
125
  user_dir = os.path.join(UPLOAD_DIR, user_id)
126
- if not os.path.exists(user_dir): raise HTTPException(404)
127
 
128
  meta = get_metadata(batch_id)
129
  if meta and meta.get("password") and meta.get("password") != password:
130
  return HTMLResponse(get_password_wall(f"Batch: {batch_id}", error=password is not None))
131
 
132
  files_data = []
 
133
  for f in os.listdir(user_dir):
134
- if f.startswith(f"{batch_id}_") and not f.endswith(".zip"):
 
 
 
135
  fpath = os.path.join(user_dir, f)
136
  files_data.append({
137
- "name": "_".join(f.split("_")[2:]),
138
  "url": f"/download/{user_id}/{f}?password={password or ''}",
139
  "stream": f"/player/{user_id}/{f}?password={password or ''}" if f.lower().endswith(('.mp4', '.mkv', '.webm')) else None,
140
  "size": round(os.path.getsize(fpath)/1024/1024, 2),
141
  "raw": f
142
  })
143
 
144
- if not files_data: raise HTTPException(404)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  files_data.sort(key=lambda x: x["raw"])
146
 
147
  items_html = "".join([f"""
 
49
  BotCommand("start", "Start the bot"),
50
  BotCommand("zip", "Create ZIP"),
51
  BotCommand("pdf_merge", "Merge PDFs"),
52
+ BotCommand("vcompress", "Compress Video"),
53
  BotCommand("search", "Search your files"),
54
  BotCommand("settings", "Bot settings"),
55
  BotCommand("files", "My files"),
 
124
  @app.get("/view/{user_id}/{batch_id}")
125
  async def view_batch(user_id: str, batch_id: str, password: Optional[str] = Query(None)):
126
  user_dir = os.path.join(UPLOAD_DIR, user_id)
127
+ if not os.path.exists(user_dir): raise HTTPException(404, "User directory not found")
128
 
129
  meta = get_metadata(batch_id)
130
  if meta and meta.get("password") and meta.get("password") != password:
131
  return HTMLResponse(get_password_wall(f"Batch: {batch_id}", error=password is not None))
132
 
133
  files_data = []
134
+ # Search for files belonging to this batch
135
  for f in os.listdir(user_dir):
136
+ if f.startswith(f"{batch_id}_"):
137
+ # Skip the ZIP/PDF itself in the list
138
+ if f.endswith(".zip") or f.endswith(".pdf"): continue
139
+
140
  fpath = os.path.join(user_dir, f)
141
  files_data.append({
142
+ "name": "_".join(f.split("_")[2:]) if len(f.split("_")) > 2 else "_".join(f.split("_")[1:]),
143
  "url": f"/download/{user_id}/{f}?password={password or ''}",
144
  "stream": f"/player/{user_id}/{f}?password={password or ''}" if f.lower().endswith(('.mp4', '.mkv', '.webm')) else None,
145
  "size": round(os.path.getsize(fpath)/1024/1024, 2),
146
  "raw": f
147
  })
148
 
149
+ # Fallback: If no batch files found, maybe batch_id is a single filename
150
+ if not files_data:
151
+ # Check if batch_id is actually a filename in metadata
152
+ target_file = None
153
+ for f in os.listdir(user_dir):
154
+ if f.startswith(batch_id):
155
+ target_file = f
156
+ break
157
+
158
+ if target_file:
159
+ fpath = os.path.join(user_dir, target_file)
160
+ files_data.append({
161
+ "name": "_".join(target_file.split("_")[1:]),
162
+ "url": f"/download/{user_id}/{target_file}?password={password or ''}",
163
+ "stream": f"/player/{user_id}/{target_file}?password={password or ''}" if target_file.lower().endswith(('.mp4', '.mkv', '.webm')) else None,
164
+ "size": round(os.path.getsize(fpath)/1024/1024, 2),
165
+ "raw": target_file
166
+ })
167
+
168
+ if not files_data: raise HTTPException(404, "No files found for this batch")
169
  files_data.sort(key=lambda x: x["raw"])
170
 
171
  items_html = "".join([f"""
bot.py CHANGED
@@ -2,7 +2,6 @@ import os
2
  import time
3
  import uuid
4
  import asyncio
5
- import zipfile
6
  from PyPDF2 import PdfWriter
7
  from pyrogram import Client, filters
8
  from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery, BotCommand
@@ -47,6 +46,7 @@ else:
47
  "**Main Commands:**\n"
48
  "πŸ“¦ /zip - Create compressed ZIP\n"
49
  "πŸ“„ /pdf_merge - Combine PDF files\n"
 
50
  "πŸ” /search - Search your uploads\n"
51
  "πŸ“‚ /files - View storage\n"
52
  "βš™οΈ /settings - Bot preferences\n"
@@ -121,13 +121,30 @@ else:
121
  @bot.on_callback_query(filters.regex("^close_settings$"))
122
  async def close_settings(client, cb: CallbackQuery): await cb.message.delete()
123
 
124
- @bot.on_message(filters.command(["zip", "pdf_merge"]) & filters.private)
125
  async def tool_init(client, message: Message):
126
  uid = message.from_user.id
127
  mode = message.command[0]
128
  bid = str(uuid.uuid4())[:8]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  kb = InlineKeyboardMarkup([
130
- [InlineKeyboardButton("βš™οΈ Compression" if mode=="zip" else "πŸ“„ PDF Info", callback_data="zip_lvl_cycle" if mode=="zip" else "pdf_info")],
131
  [InlineKeyboardButton("✏️ Set Custom Name", callback_data="tool_rename")],
132
  [InlineKeyboardButton("βœ… Done / Process", callback_data="tool_done")]
133
  ])
@@ -135,7 +152,52 @@ else:
135
  f"πŸ“¦ **{mode.upper()} Mode Active**\n━━━━━━━━━━━━━━━━━━━━\nπŸ“‚ **Name:** `Auto-generated`\nπŸ”’ **Files:** 0\nπŸ“‰ **Status:** Waiting...",
136
  reply_markup=kb
137
  )
138
- user_sessions[uid] = {"mode":mode, "files":[], "level":zipfile.ZIP_DEFLATED, "batch_id":bid, "status_msg_id":msg.id, "name":None}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
 
140
  @bot.on_callback_query(filters.regex("^tool_rename$"))
141
  async def tool_rename_init(client, cb: CallbackQuery):
@@ -182,8 +244,18 @@ else:
182
  try:
183
  total_size = sum(os.path.getsize(f) for f in sess["files"] if os.path.exists(f))
184
  if sess["mode"] == "zip":
185
- with zipfile.ZipFile(opath, 'w', sess.get("level", zipfile.ZIP_DEFLATED)) as z:
186
- for f in sess["files"]: z.write(f, os.path.basename(f))
 
 
 
 
 
 
 
 
 
 
187
  else:
188
  merger = PdfWriter()
189
  for f in sess["files"]: merger.append(f)
@@ -196,7 +268,7 @@ else:
196
  set_metadata(sess["batch_id"], {"password": settings["password"]}) # For Web View
197
 
198
  durl = f"{BASE_URL}/download/{udir}/{oname}"
199
- vurl = f"{BASE_URL}/view/{udir}/{sess['batch_id']}"
200
  saved = 100 - (os.path.getsize(opath)*100/total_size) if total_size>0 else 0
201
 
202
  await cb.message.edit_text(
@@ -251,6 +323,55 @@ else:
251
  except: pass
252
 
253
  if is_tool:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
  user_sessions[uid]["files"].append(fpath)
255
  try:
256
  await client.edit_message_text(uid, user_sessions[uid]["status_msg_id"], f"πŸ“¦ **{user_sessions[uid]['mode'].upper()} Active**\n━━━━━━━━━━━━\nπŸ“‚ Last: `{fname}`\nπŸ”’ **Total:** {len(user_sessions[uid]['files'])}", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("✏️ Rename", callback_data="tool_rename")],[InlineKeyboardButton("βœ… Done", callback_data="tool_done")]]))
 
2
  import time
3
  import uuid
4
  import asyncio
 
5
  from PyPDF2 import PdfWriter
6
  from pyrogram import Client, filters
7
  from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery, BotCommand
 
46
  "**Main Commands:**\n"
47
  "πŸ“¦ /zip - Create compressed ZIP\n"
48
  "πŸ“„ /pdf_merge - Combine PDF files\n"
49
+ "🎬 /vcompress - Reduce video size\n"
50
  "πŸ” /search - Search your uploads\n"
51
  "πŸ“‚ /files - View storage\n"
52
  "βš™οΈ /settings - Bot preferences\n"
 
121
  @bot.on_callback_query(filters.regex("^close_settings$"))
122
  async def close_settings(client, cb: CallbackQuery): await cb.message.delete()
123
 
124
+ @bot.on_message(filters.command(["zip", "pdf_merge", "vcompress"]) & filters.private)
125
  async def tool_init(client, message: Message):
126
  uid = message.from_user.id
127
  mode = message.command[0]
128
  bid = str(uuid.uuid4())[:8]
129
+
130
+ if mode == "vcompress":
131
+ kb = InlineKeyboardMarkup([
132
+ [InlineKeyboardButton("πŸ“‰ Quality: Low (480p)", callback_data="vc_q_low")],
133
+ [InlineKeyboardButton("🎬 Quality: Medium (720p)", callback_data="vc_q_med")],
134
+ [InlineKeyboardButton("✨ Quality: High (1080p)", callback_data="vc_q_high")],
135
+ [InlineKeyboardButton("❌ Cancel", callback_data="close_settings")]
136
+ ])
137
+ msg = await message.reply_text(
138
+ "🎬 **Video Compression Mode**\n━━━━━━━━━━━━━━━━━━━━\n"
139
+ "Send me the video you want to compress.\n\n"
140
+ "**Selected Quality:** `Medium (720p)`",
141
+ reply_markup=kb
142
+ )
143
+ user_sessions[uid] = {"mode":mode, "files":[], "quality":"medium", "batch_id":bid, "status_msg_id":msg.id}
144
+ return
145
+
146
  kb = InlineKeyboardMarkup([
147
+ [InlineKeyboardButton("βš™οΈ Level: Normal" if mode=="zip" else "πŸ“„ PDF Info", callback_data="zip_lvl_cycle" if mode=="zip" else "pdf_info")],
148
  [InlineKeyboardButton("✏️ Set Custom Name", callback_data="tool_rename")],
149
  [InlineKeyboardButton("βœ… Done / Process", callback_data="tool_done")]
150
  ])
 
152
  f"πŸ“¦ **{mode.upper()} Mode Active**\n━━━━━━━━━━━━━━━━━━━━\nπŸ“‚ **Name:** `Auto-generated`\nπŸ”’ **Files:** 0\nπŸ“‰ **Status:** Waiting...",
153
  reply_markup=kb
154
  )
155
+ user_sessions[uid] = {"mode":mode, "files":[], "level":5, "batch_id":bid, "status_msg_id":msg.id, "name":None}
156
+
157
+ @bot.on_callback_query(filters.regex("^vc_q_"))
158
+ async def video_quality_callback(client, cb: CallbackQuery):
159
+ uid = cb.from_user.id
160
+ if uid not in user_sessions: return
161
+
162
+ q_map = {"low": "Low (480p)", "med": "Medium (720p)", "high": "High (1080p)"}
163
+ quality = cb.data.split("_")[-1]
164
+ user_sessions[uid]["quality"] = quality
165
+
166
+ await cb.answer(f"Quality set to: {q_map[quality]}")
167
+ kb = InlineKeyboardMarkup([
168
+ [InlineKeyboardButton(f"{'βœ… ' if quality=='low' else ''}πŸ“‰ Low (480p)", callback_data="vc_q_low")],
169
+ [InlineKeyboardButton(f"{'βœ… ' if quality=='med' else ''}🎬 Medium (720p)", callback_data="vc_q_med")],
170
+ [InlineKeyboardButton(f"{'βœ… ' if quality=='high' else ''}✨ High (1080p)", callback_data="vc_q_high")],
171
+ [InlineKeyboardButton("❌ Cancel", callback_data="close_settings")]
172
+ ])
173
+ try:
174
+ await cb.message.edit_text(
175
+ "🎬 **Video Compression Mode**\n━━━━━━━━━━━━━━━━━━━━\n"
176
+ "Send me the video you want to compress.\n\n"
177
+ f"**Selected Quality:** `{q_map[quality]}`",
178
+ reply_markup=kb
179
+ )
180
+ except: pass
181
+
182
+ @bot.on_callback_query(filters.regex("^zip_lvl_cycle$"))
183
+ async def zip_lvl_cycle(client, cb: CallbackQuery):
184
+ uid = cb.from_user.id
185
+ if uid not in user_sessions: return
186
+
187
+ levels = {0: "Store", 1: "Fast", 5: "Normal", 9: "Ultra"}
188
+ lvls_list = list(levels.keys())
189
+ curr = user_sessions[uid].get("level", 5)
190
+ new_lvl = lvls_list[(lvls_list.index(curr) + 1) % len(lvls_list)]
191
+ user_sessions[uid]["level"] = new_lvl
192
+
193
+ await cb.answer(f"Compression: {levels[new_lvl]}")
194
+ kb = InlineKeyboardMarkup([
195
+ [InlineKeyboardButton(f"βš™οΈ Level: {levels[new_lvl]}", callback_data="zip_lvl_cycle")],
196
+ [InlineKeyboardButton("✏️ Set Custom Name", callback_data="tool_rename")],
197
+ [InlineKeyboardButton("βœ… Done / Process", callback_data="tool_done")]
198
+ ])
199
+ try: await cb.message.edit_reply_markup(kb)
200
+ except: pass
201
 
202
  @bot.on_callback_query(filters.regex("^tool_rename$"))
203
  async def tool_rename_init(client, cb: CallbackQuery):
 
244
  try:
245
  total_size = sum(os.path.getsize(f) for f in sess["files"] if os.path.exists(f))
246
  if sess["mode"] == "zip":
247
+ lvl = sess.get("level", 5)
248
+ # Advance 7-Zip compression: Multi-threaded, optimized levels
249
+ cmd = ["7z", "a", f"-mx={lvl}", "-mmt=on", opath] + [os.path.basename(f) for f in sess["files"]]
250
+ process = await asyncio.create_subprocess_exec(
251
+ *cmd,
252
+ cwd=os.path.join(UPLOAD_DIR, udir),
253
+ stdout=asyncio.subprocess.PIPE,
254
+ stderr=asyncio.subprocess.PIPE
255
+ )
256
+ stdout, stderr = await process.communicate()
257
+ if process.returncode != 0:
258
+ raise Exception(f"7z Error: {stderr.decode()}")
259
  else:
260
  merger = PdfWriter()
261
  for f in sess["files"]: merger.append(f)
 
268
  set_metadata(sess["batch_id"], {"password": settings["password"]}) # For Web View
269
 
270
  durl = f"{BASE_URL}/download/{udir}/{oname}"
271
+ vurl = f"{BASE_URL}/view/{udir}/{oname.split('_')[0] if '_' in oname else sess['batch_id']}"
272
  saved = 100 - (os.path.getsize(opath)*100/total_size) if total_size>0 else 0
273
 
274
  await cb.message.edit_text(
 
323
  except: pass
324
 
325
  if is_tool:
326
+ if user_sessions[uid]["mode"] == "vcompress":
327
+ # Immediate processing for video compression
328
+ user_sessions[uid]["files"].append(fpath)
329
+ await status.edit_text("⏳ **Compressing Video...**\nThis may take a while depending on size.")
330
+
331
+ quality = user_sessions[uid].get("quality", "med")
332
+ # FFmpeg settings based on quality
333
+ q_settings = {
334
+ "low": ["-vf", "scale=-2:480", "-c:v", "libx264", "-crf", "28", "-preset", "faster"],
335
+ "med": ["-vf", "scale=-2:720", "-c:v", "libx264", "-crf", "24", "-preset", "faster"],
336
+ "high": ["-vf", "scale=-2:1080", "-c:v", "libx264", "-crf", "22", "-preset", "faster"]
337
+ }
338
+
339
+ opath = fpath.rsplit(".", 1)[0] + "_compressed.mp4"
340
+ cmd = ["ffmpeg", "-i", fpath] + q_settings.get(quality, q_settings["med"]) + ["-c:a", "aac", "-b:a", "128k", opath, "-y"]
341
+
342
+ process = await asyncio.create_subprocess_exec(
343
+ *cmd,
344
+ stdout=asyncio.subprocess.PIPE,
345
+ stderr=asyncio.subprocess.PIPE
346
+ )
347
+ await process.communicate()
348
+
349
+ orig_size = os.path.getsize(fpath)
350
+ if os.path.exists(opath):
351
+ # Clean up original
352
+ # (But wait, we need it for size calculation)
353
+ comp_size = os.path.getsize(opath)
354
+ try: os.remove(fpath)
355
+ except: pass
356
+ sname = os.path.basename(opath)
357
+ fpath = opath
358
+ fname = sname
359
+ saved = 100 - (comp_size * 100 / orig_size) if orig_size > 0 else 0
360
+ else:
361
+ saved = 0
362
+ await status.edit_text("❌ Compression failed. Sending original.")
363
+
364
+ # Reset tool state or finish
365
+ settings = user_settings.get(uid, {"auto_delete":24, "self_destruct":False, "password":None})
366
+ set_metadata(os.path.basename(fpath), {"password": settings["password"], "self_destruct": settings["self_destruct"]})
367
+ durl = f"{BASE_URL}/download/user_{uid}/{os.path.basename(fpath)}"
368
+ purl = f"{BASE_URL}/player/user_{uid}/{os.path.basename(fpath)}"
369
+
370
+ kb = InlineKeyboardMarkup([[InlineKeyboardButton("πŸ“₯ Download", url=durl), InlineKeyboardButton("🎬 Watch Online", url=purl)]])
371
+ await status.edit_text(f"βœ… **Compression Ready!**\n`{fname}`\n\nπŸ“Š **Saved:** {saved:.1f}%\nπŸ›‘οΈ Pass: {'Yes' if settings['password'] else 'No'}", reply_markup=kb)
372
+ del user_sessions[uid]
373
+ return
374
+
375
  user_sessions[uid]["files"].append(fpath)
376
  try:
377
  await client.edit_message_text(uid, user_sessions[uid]["status_msg_id"], f"πŸ“¦ **{user_sessions[uid]['mode'].upper()} Active**\n━━━━━━━━━━━━\nπŸ“‚ Last: `{fname}`\nπŸ”’ **Total:** {len(user_sessions[uid]['files'])}", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("✏️ Rename", callback_data="tool_rename")],[InlineKeyboardButton("βœ… Done", callback_data="tool_done")]]))
features.txt CHANGED
@@ -2,7 +2,8 @@
2
 
3
  ## Implemented
4
  - [x] High-Speed File Hosting (MTProto based)
5
- - [x] /zip - Multi-file to ZIP collection with Compression Settings
 
6
  - [x] /pdf_merge - Merge multiple PDFs into one
7
  - [x] /files - Professional file management with Delete buttons
8
  - [x] /settings - Configure auto-delete timer (1h to 48h)
 
2
 
3
  ## Implemented
4
  - [x] High-Speed File Hosting (MTProto based)
5
+ - [x] /zip - Multi-file to ZIP collection with Advanced 7-Zip Engine (Fast & Multi-threaded)
6
+ - [x] /vcompress - Advanced Video Compression (FFmpeg based) with Quality Presets (480p, 720p, 1080p)
7
  - [x] /pdf_merge - Merge multiple PDFs into one
8
  - [x] /files - Professional file management with Delete buttons
9
  - [x] /settings - Configure auto-delete timer (1h to 48h)