MogensR commited on
Commit
cd21456
Β·
1 Parent(s): 3b2383a

Create cli/utils.py

Browse files
Files changed (1) hide show
  1. cli/utils.py +222 -0
cli/utils.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utility functions for the CLI.
3
+ """
4
+
5
+ import sys
6
+ import os
7
+ import subprocess
8
+ from pathlib import Path
9
+ from typing import Optional, List, Dict, Any
10
+ import json
11
+ import psutil
12
+ import torch
13
+ from rich.console import Console
14
+ from rich.table import Table
15
+
16
+ console = Console()
17
+
18
+
19
+ def check_system_requirements() -> Dict[str, Any]:
20
+ """Check if system meets requirements."""
21
+ requirements = {
22
+ 'python_version': sys.version,
23
+ 'python_ok': sys.version_info >= (3, 8),
24
+ 'memory_gb': psutil.virtual_memory().total / (1024**3),
25
+ 'memory_ok': psutil.virtual_memory().total >= 8 * (1024**3),
26
+ 'cuda_available': torch.cuda.is_available(),
27
+ 'gpu_name': None,
28
+ 'gpu_memory_gb': 0,
29
+ 'ffmpeg_available': check_ffmpeg(),
30
+ 'disk_space_gb': get_free_disk_space(),
31
+ 'disk_ok': get_free_disk_space() >= 10
32
+ }
33
+
34
+ if torch.cuda.is_available():
35
+ requirements['gpu_name'] = torch.cuda.get_device_name(0)
36
+ requirements['gpu_memory_gb'] = torch.cuda.get_device_properties(0).total_memory / (1024**3)
37
+
38
+ return requirements
39
+
40
+
41
+ def check_ffmpeg() -> bool:
42
+ """Check if FFmpeg is available."""
43
+ try:
44
+ subprocess.run(['ffmpeg', '-version'], capture_output=True, check=True)
45
+ return True
46
+ except (subprocess.CalledProcessError, FileNotFoundError):
47
+ return False
48
+
49
+
50
+ def get_free_disk_space() -> float:
51
+ """Get free disk space in GB."""
52
+ stat = psutil.disk_usage('/')
53
+ return stat.free / (1024**3)
54
+
55
+
56
+ def install_ffmpeg_instructions() -> str:
57
+ """Get FFmpeg installation instructions for current platform."""
58
+ system = sys.platform
59
+
60
+ if system == "darwin": # macOS
61
+ return "Install FFmpeg using: brew install ffmpeg"
62
+ elif system == "win32": # Windows
63
+ return "Download FFmpeg from https://ffmpeg.org/download.html and add to PATH"
64
+ else: # Linux
65
+ return "Install FFmpeg using: sudo apt-get install ffmpeg (Ubuntu/Debian) or equivalent"
66
+
67
+
68
+ def print_system_info():
69
+ """Print system information table."""
70
+ reqs = check_system_requirements()
71
+
72
+ table = Table(title="System Information")
73
+ table.add_column("Component", style="cyan")
74
+ table.add_column("Status", style="green")
75
+ table.add_column("Value", style="white")
76
+
77
+ # Python
78
+ python_status = "βœ“" if reqs['python_ok'] else "βœ—"
79
+ table.add_row("Python", python_status, reqs['python_version'].split()[0])
80
+
81
+ # Memory
82
+ memory_status = "βœ“" if reqs['memory_ok'] else "βœ—"
83
+ table.add_row("Memory", memory_status, f"{reqs['memory_gb']:.1f} GB")
84
+
85
+ # GPU
86
+ if reqs['cuda_available']:
87
+ table.add_row("GPU", "βœ“", f"{reqs['gpu_name']} ({reqs['gpu_memory_gb']:.1f} GB)")
88
+ else:
89
+ table.add_row("GPU", "βœ—", "Not available")
90
+
91
+ # FFmpeg
92
+ ffmpeg_status = "βœ“" if reqs['ffmpeg_available'] else "βœ—"
93
+ table.add_row("FFmpeg", ffmpeg_status, "Installed" if reqs['ffmpeg_available'] else "Not found")
94
+
95
+ # Disk space
96
+ disk_status = "βœ“" if reqs['disk_ok'] else "βœ—"
97
+ table.add_row("Disk Space", disk_status, f"{reqs['disk_space_gb']:.1f} GB free")
98
+
99
+ console.print(table)
100
+
101
+ # Print warnings
102
+ if not reqs['memory_ok']:
103
+ console.print("[yellow]Warning: Less than 8GB RAM available. Processing may be slow.[/yellow]")
104
+
105
+ if not reqs['ffmpeg_available']:
106
+ console.print(f"[yellow]Warning: FFmpeg not found. {install_ffmpeg_instructions()}[/yellow]")
107
+
108
+ if not reqs['disk_ok']:
109
+ console.print("[yellow]Warning: Less than 10GB disk space available.[/yellow]")
110
+
111
+
112
+ def format_time(seconds: float) -> str:
113
+ """Format seconds to human-readable time."""
114
+ if seconds < 60:
115
+ return f"{seconds:.1f}s"
116
+ elif seconds < 3600:
117
+ minutes = seconds / 60
118
+ return f"{minutes:.1f}m"
119
+ else:
120
+ hours = seconds / 3600
121
+ return f"{hours:.1f}h"
122
+
123
+
124
+ def estimate_processing_time(video_path: str, use_two_stage: bool = False) -> float:
125
+ """Estimate processing time for a video."""
126
+ import cv2
127
+
128
+ try:
129
+ cap = cv2.VideoCapture(video_path)
130
+ frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
131
+ fps = cap.get(cv2.CAP_PROP_FPS)
132
+ cap.release()
133
+
134
+ # Rough estimates based on hardware
135
+ if torch.cuda.is_available():
136
+ seconds_per_frame = 0.1 if not use_two_stage else 0.2
137
+ else:
138
+ seconds_per_frame = 0.5 if not use_two_stage else 1.0
139
+
140
+ return frame_count * seconds_per_frame
141
+
142
+ except:
143
+ return 0
144
+
145
+
146
+ def validate_paths(input_path: str, output_path: str) -> bool:
147
+ """Validate input and output paths."""
148
+ input_file = Path(input_path)
149
+ output_file = Path(output_path)
150
+
151
+ if not input_file.exists():
152
+ console.print(f"[red]Error: Input file does not exist: {input_path}[/red]")
153
+ return False
154
+
155
+ if not input_file.is_file():
156
+ console.print(f"[red]Error: Input path is not a file: {input_path}[/red]")
157
+ return False
158
+
159
+ # Check if input is a video file
160
+ valid_extensions = {'.mp4', '.avi', '.mov', '.mkv', '.webm', '.flv', '.wmv'}
161
+ if input_file.suffix.lower() not in valid_extensions:
162
+ console.print(f"[red]Error: Input file is not a supported video format: {input_file.suffix}[/red]")
163
+ console.print(f"Supported formats: {', '.join(valid_extensions)}")
164
+ return False
165
+
166
+ # Check output directory exists or can be created
167
+ output_dir = output_file.parent
168
+ if not output_dir.exists():
169
+ try:
170
+ output_dir.mkdir(parents=True, exist_ok=True)
171
+ except Exception as e:
172
+ console.print(f"[red]Error: Cannot create output directory: {e}[/red]")
173
+ return False
174
+
175
+ # Warn if output file exists
176
+ if output_file.exists():
177
+ response = console.input(f"[yellow]Output file exists. Overwrite? (y/n):[/yellow] ")
178
+ if response.lower() != 'y':
179
+ return False
180
+
181
+ return True
182
+
183
+
184
+ def create_config_file(config_path: Optional[str] = None) -> str:
185
+ """Create a default configuration file."""
186
+ if config_path is None:
187
+ config_path = Path.home() / ".backgroundfx" / "config.json"
188
+ else:
189
+ config_path = Path(config_path)
190
+
191
+ config_path.parent.mkdir(parents=True, exist_ok=True)
192
+
193
+ default_config = {
194
+ "default_background": "blur",
195
+ "quality_preset": "high",
196
+ "use_two_stage": False,
197
+ "chroma_preset": "standard",
198
+ "output_format": "mp4",
199
+ "models_dir": str(Path.home() / ".backgroundfx" / "models"),
200
+ "temp_dir": "/tmp",
201
+ "max_memory_gb": 8,
202
+ "batch_size": 1,
203
+ "device": "auto"
204
+ }
205
+
206
+ with open(config_path, 'w') as f:
207
+ json.dump(default_config, f, indent=2)
208
+
209
+ return str(config_path)
210
+
211
+
212
+ def load_config(config_path: str) -> Dict[str, Any]:
213
+ """Load configuration from file."""
214
+ try:
215
+ with open(config_path, 'r') as f:
216
+ return json.load(f)
217
+ except FileNotFoundError:
218
+ console.print(f"[yellow]Config file not found: {config_path}[/yellow]")
219
+ return {}
220
+ except json.JSONDecodeError as e:
221
+ console.print(f"[red]Error parsing config file: {e}[/red]")
222
+ return {}