azils3/bash
0
1# Ultroid - UserBot2# Copyright (C) 2021-2025 TeamUltroid3#4# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >5# PLease read the GNU Affero General Public License in6# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.7 8from . import get_help9 10__doc__ = get_help("help_compressor")11 12 13import asyncio14import os15import re16import time17from datetime import datetime as dt18 19from telethon.errors.rpcerrorlist import MessageNotModifiedError20from telethon.tl.types import DocumentAttributeVideo21 22from pyUltroid.fns.tools import metadata23 24from . import (25 ULTConfig,26 bash,27 downloader,28 get_string,29 humanbytes,30 math,31 mediainfo,32 time_formatter,33 ultroid_cmd,34 uploader,35)36 37 38@ultroid_cmd(pattern="compress( (.*)|$)")39async def _(e):40 cr = e.pattern_match.group(1).strip()41 crf = 2742 to_stream = False43 if cr:44 k = e.text.split()45 if len(k) == 2:46 crf = int(k[1]) if k[1].isdigit() else 2747 elif len(k) > 2:48 crf = int(k[1]) if k[1].isdigit() else 2749 to_stream = "stream" in k[2]50 vido = await e.get_reply_message()51 if vido and vido.media and "video" in mediainfo(vido.media):52 if hasattr(vido.media, "document"):53 vfile = vido.media.document54 name = vido.file.name55 else:56 vfile = vido.media57 name = ""58 if not name:59 name = "video_" + dt.now().isoformat("_", "seconds") + ".mp4"60 xxx = await e.eor(get_string("audiotools_5"))61 c_time = time.time()62 file = await downloader(63 f"resources/downloads/{name}",64 vfile,65 xxx,66 c_time,67 f"Downloading {name}...",68 )69 70 o_size = os.path.getsize(file.name)71 d_time = time.time()72 diff = time_formatter((d_time - c_time) * 1000)73 file_name = (file.name).split("/")[-1]74 out = file_name.replace(file_name.split(".")[-1], "compressed.mkv")75 await xxx.edit(76 f"`Downloaded {file.name} of {humanbytes(o_size)} in {diff}.\nNow Compressing...`"77 )78 x, y = await bash(79 f'mediainfo --fullscan """{file.name}""" | grep "Frame count"'80 )81 if y and y.endswith("NOT_FOUND"):82 return await xxx.edit(f"ERROR: `{y}`")83 total_frames = x.split(":")[1].split("\n")[0]84 progress = f"progress-{c_time}.txt"85 with open(progress, "w"):86 pass87 proce = await asyncio.create_subprocess_shell(88 f'ffmpeg -hide_banner -loglevel quiet -progress {progress} -i """{file.name}""" -preset ultrafast -vcodec libx265 -crf {crf} -c:a copy """{out}""" -y',89 stdout=asyncio.subprocess.PIPE,90 stderr=asyncio.subprocess.PIPE,91 )92 while proce.returncode != 0:93 await asyncio.sleep(3)94 with open(progress, "r+") as fil:95 text = fil.read()96 frames = re.findall("frame=(\\d+)", text)97 size = re.findall("total_size=(\\d+)", text)98 speed = 099 if len(frames):100 elapse = int(frames[-1])101 if len(size):102 size = int(size[-1])103 per = elapse * 100 / int(total_frames)104 time_diff = time.time() - int(d_time)105 speed = round(elapse / time_diff, 2)106 if int(speed) != 0:107 some_eta = ((int(total_frames) - elapse) / speed) * 1000108 text = f"`Compressing {file_name} at {crf} CRF.\n`"109 progress_str = "`[{0}{1}] {2}%\n\n`".format(110 "".join("●" for _ in range(math.floor(per / 5))),111 "".join("" for _ in range(20 - math.floor(per / 5))),112 round(per, 2),113 )114 115 e_size = f"{humanbytes(size)} of ~{humanbytes((size / per) * 100)}"116 eta = f"~{time_formatter(some_eta)}"117 try:118 await xxx.edit(119 text120 + progress_str121 + "`"122 + e_size123 + "`"124 + "\n\n`"125 + eta126 + "`"127 )128 except MessageNotModifiedError:129 pass130 os.remove(file.name)131 c_size = os.path.getsize(out)132 f_time = time.time()133 difff = time_formatter((f_time - d_time) * 1000)134 await xxx.edit(135 f"`Compressed {humanbytes(o_size)} to {humanbytes(c_size)} in {difff}\nTrying to Upload...`"136 )137 differ = 100 - ((c_size / o_size) * 100)138 caption = f"**Original Size: **`{humanbytes(o_size)}`\n"139 caption += f"**Compressed Size: **`{humanbytes(c_size)}`\n"140 caption += f"**Compression Ratio: **`{differ:.2f}%`\n"141 caption += f"\n**Time Taken To Compress: **`{difff}`"142 n_file, _ = await e.client.fast_uploader(143 out, show_progress=True, event=e, message="Uploading...", to_delete=True144 )145 if to_stream:146 data = await metadata(out)147 width = data["width"]148 height = data["height"]149 duration = data["duration"]150 attributes = [151 DocumentAttributeVideo(152 duration=duration, w=width, h=height, supports_streaming=True153 )154 ]155 await e.client.send_file(156 e.chat_id,157 n_file,158 thumb=ULTConfig.thumb,159 caption=caption,160 attributes=attributes,161 force_document=False,162 reply_to=e.reply_to_msg_id,163 )164 else:165 await e.client.send_file(166 e.chat_id,167 n_file,168 thumb=ULTConfig.thumb,169 caption=caption,170 force_document=True,171 reply_to=e.reply_to_msg_id,172 )173 await xxx.delete()174 os.remove(out)175 os.remove(progress)176 else:177 await e.eor(get_string("audiotools_8"), time=5)178 