File size: 11,043 Bytes
77f5a3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
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.")