VaTeX / vatex_monitor_downloads.py
qingy2024's picture
Upload folder using huggingface_hub
77f5a3f verified
import curses
import json
import time
import sys
import os
import glob
import argparse
from datetime import datetime
# --- Configuration ---
BAR_CHAR = "#" # Simpler character that works in all terminals
EMPTY_BAR_CHAR = "-"
REFRESH_INTERVAL_SECONDS = 1
def format_time(seconds):
"""Format seconds into a human-readable time string."""
if seconds < 60:
return f"{seconds:.1f}s"
elif seconds < 3600:
minutes = seconds / 60
return f"{minutes:.1f}m"
else:
hours = seconds / 3600
return f"{hours:.1f}h"
def analyze_progress(json_file_path, output_dir, last_stats=None):
"""
Analyzes the JSON file and output directory to calculate progress.
"""
start_time = time.time()
# 1. Get the set of all expected video IDs from the JSON file
try:
with open(json_file_path, 'r', encoding='utf-8') as f:
video_data = json.load(f)
expected_video_ids = {item['videoID']: item.get('title', 'Unknown')
for item in video_data if 'videoID' in item}
total_videos = len(expected_video_ids)
except (FileNotFoundError, json.JSONDecodeError):
return 0, 0, 0, [], 0, 0, {}
# 2. Get the set of all completed video IDs from the output directory
completed_video_ids = set()
completed_files_with_info = []
file_sizes = {}
try:
for filepath in glob.glob(os.path.join(output_dir, '*.*')):
basename = os.path.basename(filepath)
video_id = os.path.splitext(basename)[0]
if video_id in expected_video_ids:
completed_video_ids.add(video_id)
try:
mtime = os.path.getmtime(filepath)
size = os.path.getsize(filepath)
title = expected_video_ids.get(video_id, 'Unknown')
completed_files_with_info.append((basename, mtime, size, title, video_id))
file_sizes[video_id] = size
except FileNotFoundError:
continue
except FileNotFoundError:
pass
# 3. Sort recent files by modification time (newest first)
completed_files_with_info.sort(key=lambda x: x[1], reverse=True)
recent_files = completed_files_with_info[:10] # Show up to 10 recent files
# 4. Calculate stats
completed_videos = len(completed_video_ids)
pending_videos = total_videos - completed_videos
# 5. Calculate download rate and ETA
download_rate = 0
eta = 0
if last_stats and 'completed' in last_stats and last_stats['completed'] < completed_videos:
time_diff = time.time() - last_stats.get('timestamp', start_time)
if time_diff > 0:
download_rate = (completed_videos - last_stats['completed']) / time_diff * 60 # per minute
if download_rate > 0 and pending_videos > 0:
eta = pending_videos / download_rate * 60 # seconds
return total_videos, completed_videos, pending_videos, recent_files, download_rate, eta, file_sizes
def draw_progress_bar(stdscr, y, x, width, label, percentage, color_pair):
"""Draws a label and a progress bar with improved visuals."""
if width <= 0 or y >= stdscr.getmaxyx()[0]:
return
# Reserve space for label, percentage, and brackets
label_width = len(label)
percent_str = f" [{percentage:5.1f}%]"
bar_area_width = width - label_width - len(percent_str)
if bar_area_width <= 0:
return
filled_len = int(bar_area_width * percentage / 100)
bar = BAR_CHAR * filled_len + EMPTY_BAR_CHAR * (bar_area_width - filled_len)
try:
stdscr.addstr(y, x, label, curses.color_pair(3))
stdscr.addstr(y, x + label_width, bar, color_pair)
stdscr.addstr(y, x + label_width + bar_area_width, percent_str)
except curses.error:
# Safely handle drawing errors
pass
def format_size(size_bytes):
"""Format bytes into human-readable format."""
if size_bytes < 1024:
return f"{size_bytes} B"
elif size_bytes < 1024 * 1024:
return f"{size_bytes/1024:.1f} KB"
elif size_bytes < 1024 * 1024 * 1024:
return f"{size_bytes/(1024*1024):.1f} MB"
else:
return f"{size_bytes/(1024*1024*1024):.2f} GB"
def safe_addstr(stdscr, y, x, text, attr=0):
"""Safely add a string to the screen, handling boundary errors."""
height, width = stdscr.getmaxyx()
if y < 0 or y >= height or x < 0 or x >= width:
return
# Truncate the string if it would go off-screen
max_len = width - x
if max_len <= 0:
return
display_text = text[:max_len]
try:
stdscr.addstr(y, x, display_text, attr)
except curses.error:
# Safely handle any curses errors
pass
def main(stdscr, json_path, output_dir):
# --- Curses Setup ---
curses.curs_set(0) # Hide cursor
curses.use_default_colors()
curses.init_pair(1, curses.COLOR_GREEN, -1) # Success / Bar
curses.init_pair(2, curses.COLOR_WHITE, -1) # Normal text
curses.init_pair(3, curses.COLOR_CYAN, -1) # Labels
curses.init_pair(4, curses.COLOR_RED, -1) # Error / Warning
curses.init_pair(5, curses.COLOR_YELLOW, -1) # Info
# For tracking download rate
last_stats = None
start_time = time.time()
while True:
stdscr.erase()
height, width = stdscr.getmaxyx()
# --- Data Loading ---
total, completed, pending, recent_files, download_rate, eta, file_sizes = analyze_progress(
json_path, output_dir, last_stats
)
# Update stats for next iteration
last_stats = {
'completed': completed,
'timestamp': time.time()
}
# Calculate total downloaded size
total_size = sum(file_sizes.values())
# --- Drawing UI ---
# Header
header = f"Download Monitor - {os.path.basename(json_path)}"
safe_addstr(stdscr, 0, 2, header, curses.A_BOLD)
safe_addstr(stdscr, 1, 2, f"Output: {os.path.basename(output_dir)}", curses.A_DIM)
safe_addstr(stdscr, 2, 2, "Press 'q' to quit, 'r' to refresh", curses.A_DIM)
try:
stdscr.hline(3, 0, "-", width)
except curses.error:
pass
y_pos = 5
# Stats Section
if total == 0:
safe_addstr(stdscr, y_pos, 4, "Waiting for data or JSON not found...", curses.color_pair(4) | curses.A_BOLD)
y_pos += 2
else:
# Stats header
safe_addstr(stdscr, y_pos, 4, "Download Statistics", curses.color_pair(3) | curses.A_BOLD)
y_pos += 2
# Left column stats
safe_addstr(stdscr, y_pos, 4, f"Total Videos: {total}", curses.color_pair(2))
safe_addstr(stdscr, y_pos + 1, 4, f"Completed: {completed}", curses.color_pair(1))
safe_addstr(stdscr, y_pos + 2, 4, f"Pending: {pending}", curses.color_pair(5))
# Right column stats if there's enough space
if width > 50:
right_col = width // 2
safe_addstr(stdscr, y_pos, right_col, f"Total Size: {format_size(total_size)}", curses.color_pair(2))
safe_addstr(stdscr, y_pos + 1, right_col, f"Rate: {download_rate:.1f} videos/min", curses.color_pair(1))
if eta > 0:
eta_str = format_time(eta)
safe_addstr(stdscr, y_pos + 2, right_col, f"ETA: {eta_str}", curses.color_pair(5))
else:
safe_addstr(stdscr, y_pos + 2, right_col, "ETA: calculating...", curses.color_pair(5))
y_pos += 4
# Progress Bar
percentage = (completed / total) * 100 if total > 0 else 0
draw_progress_bar(stdscr, y_pos, 4, width - 8, "Progress: ", percentage, curses.color_pair(1))
y_pos += 2
# Runtime
runtime = time.time() - start_time
runtime_str = format_time(runtime)
safe_addstr(stdscr, y_pos, 4, f"Runtime: {runtime_str}", curses.color_pair(2))
y_pos += 2
# Separator
try:
stdscr.hline(y_pos, 0, "-", width)
except curses.error:
pass
y_pos += 1
# Recent Files Section
safe_addstr(stdscr, y_pos, 2, "Recently Completed Files:", curses.color_pair(3) | curses.A_BOLD)
y_pos += 2
if recent_files:
for i, (filename, mtime, size, title, video_id) in enumerate(recent_files):
if y_pos >= height - 1:
break
# Format the time
time_str = datetime.fromtimestamp(mtime).strftime("%H:%M:%S")
size_str = format_size(size)
# Display title if available, otherwise filename
display_name = title if title != 'Unknown' else filename
# Truncate long names
max_name_len = width - 25 if width > 25 else 10
if len(display_name) > max_name_len:
display_name = display_name[:max_name_len-3] + "..."
file_info = f"{display_name} ({size_str}, {time_str})"
safe_addstr(stdscr, y_pos, 4, file_info, curses.color_pair(2))
y_pos += 1
else:
safe_addstr(stdscr, y_pos, 4, "(No completed files found yet)", curses.color_pair(4))
stdscr.refresh()
# Non-blocking input with a timeout
stdscr.timeout(REFRESH_INTERVAL_SECONDS * 1000)
key = stdscr.getch()
if key == ord('q'):
break
elif key == ord('r'):
# Force refresh
continue
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="A curses-based monitor for the video downloader script.",
formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument(
"json_file",
type=str,
help="Path to the JSON file containing video information (the same one used by the downloader)."
)
parser.add_argument(
"output_dir",
type=str,
help="Path to the output directory where videos are being saved."
)
args = parser.parse_args()
print(f"Starting download monitor...")
print(f" - Watching JSON: {args.json_file}")
print(f" - Watching Dir: {args.output_dir}")
print("\nPress 'q' in the monitor window to exit.")
time.sleep(1)
try:
curses.wrapper(main, args.json_file, args.output_dir)
except curses.error as e:
print(f"\nCurses error: {e}")
print("Your terminal window might be too small to run the monitor.")
except KeyboardInterrupt:
print("\nMonitor stopped.")