YouTubeLoader / bot /core /progress.py
understanding's picture
Create progress.py
28c0b4f verified
raw
history blame
1.1 kB
# PATH: bot/core/progress.py
import time
class SpeedETA:
def __init__(self):
self.t0 = time.time()
self.last_t = self.t0
self.last_bytes = 0
self.total = 0
def update(self, done_bytes: int, total_bytes: int) -> dict:
now = time.time()
self.total = total_bytes
dt = max(1e-6, now - self.last_t)
db = done_bytes - self.last_bytes
speed = db / dt # bytes/sec
remaining = max(0, total_bytes - done_bytes)
eta = remaining / max(1e-6, speed)
self.last_t = now
self.last_bytes = done_bytes
return {"done": done_bytes, "total": total_bytes, "speed_bps": speed, "eta_sec": eta}
def human_bytes(n: float) -> str:
units = ["B", "KB", "MB", "GB"]
x = float(n)
for u in units:
if x < 1024 or u == units[-1]:
return f"{x:.2f}{u}"
x /= 1024
return f"{x:.2f}GB"
def human_eta(sec: float) -> str:
s = int(max(0, sec))
m, s = divmod(s, 60)
h, m = divmod(m, 60)
if h: return f"{h}h {m}m"
if m: return f"{m}m {s}s"
return f"{s}s"