Skip to content

Commit

Permalink
rev
Browse files Browse the repository at this point in the history
  • Loading branch information
5hojib committed Dec 8, 2024
1 parent e2b75cd commit 03ffbed
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 48 deletions.
86 changes: 40 additions & 46 deletions bot/helper/aeon_utils/ffmpeg_s.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,20 +68,16 @@ def eta(self):

@property
def speed(self):
elapsed = time() - self._start_time
return self._processed_bytes / elapsed if elapsed > 0 else 0
return self._processed_bytes / (time() - self._start_time)

async def readlines(self, stream):
"""Efficiently read lines from a stream."""
buffer = bytearray()
data = bytearray()
while not stream.at_eof():
chunk = await stream.read(1024)
if not chunk:
break
buffer.extend(chunk)
*lines, buffer = buffer.split(b"\n")
lines = re.split(rb"[\r\n]+", data)
data[:] = lines.pop(-1)
for line in lines:
yield line.strip()
yield line
data.extend(await stream.read(1024))

async def progress(self, status: str = ""):
start_time = time()
Expand All @@ -96,31 +92,27 @@ async def progress(self, status: str = ""):
self._processed_bytes = await get_path_size(self.outfile)
await sleep(0.5)
continue
try:
progress = dict(
re.findall(
r"(frame|fps|size|time|bitrate|speed)\s*=\s*(\S+)",
line.decode("utf-8"),
),
if progress := dict(
re.findall(
r"(frame|fps|size|time|bitrate|speed)\s*\=\s*(\S+)",
line.decode("utf-8"),
),
):
if not self._duration:
self._duration = (await get_media_info(self.path))[0]
try:
hh, mm, sms = progress["time"].split(":")
except ValueError:
hh, mm, sms = 0, 0, 0
time_to_second = (int(hh) * 3600) + (int(mm) * 60) + float(sms)
self._processed_bytes = int(progress["size"].rstrip("kB")) * 1024
self._percentage = (
f"{round((time_to_second / self._duration) * 100, 2)}%"
)
except Exception:
continue

if not self._duration:
self._duration = (await get_media_info(self.path))[0]

time_data = progress.get("time", "0:0:0").split(":")
hh, mm, ss = map(float, time_data) if len(time_data) == 3 else (0, 0, 0)

time_to_second = hh * 3600 + mm * 60 + ss
self._processed_bytes = (
int(progress.get("size", "0kB").strip("kB")) * 1024
)
self._percentage = f"{(time_to_second / self._duration) * 100:.2f}%"
with contextlib.suppress(Exception):
self._eta = (
self._duration / float(progress.get("speed", "1x").strip("x"))
) - (time() - start_time)
with contextlib.suppress(Exception):
self._eta = (
self._duration / float(progress["speed"].strip("x"))
) - (time() - start_time)


class SampleVideo(FFProgress):
Expand All @@ -141,15 +133,12 @@ async def create(self, video_file: str, on_file: bool = False):
self.path = video_file
dir, name = video_file.rsplit("/", 1)
self.outfile = ospath.join(dir, f"SAMPLE.{name}")
duration = (await get_media_info(video_file))[0]

# Create segment timings dynamically
segments = [(0, self._part_duration)]
duration = (await get_media_info(video_file))[0]
remaining_duration = duration - (self._part_duration * 2)
parts = max((remaining_duration // self._part_duration), 1)
parts = (self._duration - (self._part_duration * 2)) // self._part_duration
time_interval = remaining_duration // parts
next_segment = time_interval

for _ in range(parts):
segments.append((next_segment, next_segment + self._part_duration))
next_segment += time_interval
Expand All @@ -158,9 +147,14 @@ async def create(self, video_file: str, on_file: bool = False):
for i, (start, end) in enumerate(segments):
filter_complex += (
f"[0:v]trim=start={start}:end={end},setpts=PTS-STARTPTS[v{i}]; "
)
filter_complex += (
f"[0:a]atrim=start={start}:end={end},asetpts=PTS-STARTPTS[a{i}]; "
)
filter_complex += "".join(f"[v{i}][a{i}]" for i in range(len(segments)))

for i in range(len(segments)):
filter_complex += f"[v{i}][a{i}]"

filter_complex += f"concat=n={len(segments)}:v=1:a=1[vout][aout]"

cmd = [
Expand All @@ -179,7 +173,7 @@ async def create(self, video_file: str, on_file: bool = False):
"-c:a",
"aac",
"-threads",
f"{cpu_count() // 2}",
f"{cpu_count()//2}",
self.outfile,
]

Expand All @@ -197,13 +191,13 @@ async def create(self, video_file: str, on_file: bool = False):
return False
if code == 0:
if on_file:
new_dir, _ = ospath.splitext(video_file)
await makedirs(new_dir, exist_ok=True)
newDir, _ = ospath.splitext(video_file)
await makedirs(newDir, exist_ok=True)
await gather(
move(video_file, ospath.join(new_dir, name)),
move(self.outfile, ospath.join(new_dir, f"SAMPLE.{name}")),
move(video_file, ospath.join(newDir, name)),
move(self.outfile, ospath.join(newDir, f"SAMPLE.{name}")),
)
return new_dir
return newDir
return True

LOGGER.error(
Expand Down
1 change: 0 additions & 1 deletion bot/helper/ext_utils/status_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,6 @@ async def get_readable_message(sid, is_user, page_no=1, status="All", page_step=
MirrorStatus.STATUS_CONVERT,
MirrorStatus.STATUS_FFMPEG,
MirrorStatus.STATUS_QUEUEUP,
MirrorStatus.STATUS_SAMVID,
]:
progress = (
await task.progress()
Expand Down
2 changes: 1 addition & 1 deletion bot/helper/listeners/task_listener.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ async def on_download_complete(self):
self.size = await get_path_size(up_dir)

if self.sample_video:
up_path = await self.generate_sample_video(
up_path = await self.generate_sample_video_x(
up_path,
gid,
unwanted_files,
Expand Down

0 comments on commit 03ffbed

Please sign in to comment.