-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
384 lines (307 loc) · 13.1 KB
/
Copy pathcli.py
File metadata and controls
384 lines (307 loc) · 13.1 KB
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
"""
Command-line interface for the video generation pipeline.
"""
import sys
from pathlib import Path
from typing import Optional, List
import click
import yaml
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
from src.pipeline import create_pipeline
from src.utils.logger import setup_logging, get_logger
from src.utils.tui_manager import TUIManager, ProgressCallback
@click.group()
@click.version_option(version="0.1.0")
def cli():
"""AI Video Generation Pipeline - Create engaging short-form videos with AI."""
pass
@cli.command()
@click.argument('topic')
@click.option('--input', '-i', multiple=True, type=click.Path(exists=True), help='Input video file(s)')
@click.option('--output', '-o', type=click.Path(), help='Output video path')
@click.option('--config', '-c', type=click.Path(exists=True), default='config/config.yaml', help='Configuration file')
@click.option('--content', type=str, help='Specific content/facts to include in the video script')
@click.option('--duration', '-d', type=int, help='Target duration in seconds')
@click.option('--style', type=click.Choice(['engaging', 'educational', 'funny', 'dramatic']), help='Video style')
@click.option('--tts', type=click.Choice(['coqui', 'chatterbox']), help='TTS engine')
@click.option('--tui/--no-tui', default=True, help='Show progress TUI')
@click.option('--verbose', '-v', is_flag=True, help='Verbose output')
def generate(
topic: str,
input: tuple,
output: Optional[str],
config: str,
content: Optional[str],
duration: Optional[int],
style: Optional[str],
tts: Optional[str],
tui: bool,
verbose: bool
):
"""
Generate a video from input clips and topic.
TOPIC: The subject/theme of the video
Example:
vidgen generate "Amazing Nature Facts" -i video1.mp4 -i video2.mp4
vidgen generate "Nature Facts" --content "Octopuses have 3 hearts. Honey never spoils." -i video.mp4
"""
try:
# Load configuration
config_data = load_config(config)
# Override config with CLI options
if duration:
config_data['video']['target_duration'] = duration
if style:
config_data['script']['style'] = style
if tts:
config_data['tts']['engine'] = tts
# Check for script provider override from environment (set by UI)
import os
script_provider = os.environ.get('VIDGEN_SCRIPT_PROVIDER')
if script_provider:
config_data['script']['llm']['provider'] = script_provider
if verbose:
config_data['logging']['level'] = 'DEBUG'
# Setup logging
logger = setup_logging(config_data)
logger.info(f"Starting video generation for topic: {topic}")
# Prepare input videos
input_videos = [Path(f) for f in input] if input else None
output_path = Path(output) if output else None
# Run pipeline with or without TUI
if tui:
run_with_tui(config_data, topic, input_videos, output_path, content or "")
else:
run_simple(config_data, topic, input_videos, output_path, content or "")
except Exception as e:
click.secho(f"Error: {e}", fg='red', err=True)
if verbose:
import traceback
traceback.print_exc()
sys.exit(1)
@cli.command()
@click.argument('video_path', type=click.Path(exists=True))
@click.option('--config', '-c', type=click.Path(exists=True), default='config/config.yaml')
def analyze(video_path: str, config: str):
"""
Analyze a video to detect scenes and events.
VIDEO_PATH: Path to video file
"""
try:
config_data = load_config(config)
logger = setup_logging(config_data)
from src.modules.video_analyzer import VideoAnalyzer
analyzer = VideoAnalyzer(config_data)
click.echo(f"Analyzing video: {video_path}")
results = analyzer.analyze([Path(video_path)])
click.echo(f"\nResults:")
click.echo(f" Total duration: {results['total_duration']:.2f}s")
click.echo(f" Scenes detected: {results['num_scenes']}")
click.echo(f" Top events found: {len(results['events'])}")
click.echo(f"\nTop 5 Events:")
for i, event in enumerate(results['events'][:5], 1):
click.echo(f" {i}. {event['start_time']:.2f}s - {event['end_time']:.2f}s "
f"(score: {event['score']:.3f})")
except Exception as e:
click.secho(f"Error: {e}", fg='red', err=True)
sys.exit(1)
@cli.command()
@click.argument('topic')
@click.option('--config', '-c', type=click.Path(exists=True), default='config/config.yaml')
@click.option('--style', type=click.Choice(['engaging', 'educational', 'funny', 'dramatic']))
@click.option('--output', '-o', type=click.Path(), help='Output script file')
def script(topic: str, config: str, style: Optional[str], output: Optional[str]):
"""
Generate a script for a given topic.
TOPIC: The subject/theme for the script
"""
try:
config_data = load_config(config)
if style:
config_data['script']['style'] = style
logger = setup_logging(config_data)
from src.modules.script_generator import ScriptGenerator
generator = ScriptGenerator(config_data)
click.echo(f"Generating script for: {topic}")
result = generator.generate(
topic=topic,
events=[],
target_duration=config_data['video']['target_duration']
)
click.echo(f"\nGenerated Script ({result['word_count']} words):")
click.echo("─" * 60)
click.echo(result['text'])
click.echo("─" * 60)
if output:
output_path = Path(output)
output_path.write_text(result['text'])
click.secho(f"\nScript saved to: {output_path}", fg='green')
except Exception as e:
click.secho(f"Error: {e}", fg='red', err=True)
sys.exit(1)
@cli.command()
@click.option('--config', '-c', type=click.Path(exists=True), default='config/config.yaml')
def info(config: str):
"""Display configuration and system information."""
try:
config_data = load_config(config)
click.echo("VidGen - AI Video Generation Pipeline")
click.echo("=" * 60)
click.echo("\nConfiguration:")
click.echo(f" Config file: {config}")
click.echo(f" Target duration: {config_data['video']['target_duration']}s")
click.echo(f" Resolution: {config_data['video']['resolution']['width']}x"
f"{config_data['video']['resolution']['height']}")
click.echo(f" FPS: {config_data['video']['fps']}")
click.echo(f" Script style: {config_data['script']['style']}")
click.echo(f" TTS engine: {config_data['tts']['engine']}")
click.echo(f" LLM provider: {config_data['script']['llm']['provider']}")
click.echo("\nPaths:")
click.echo(f" Input: {config_data['paths']['input_dir']}")
click.echo(f" Output: {config_data['paths']['output_dir']}")
click.echo(f" Temp: {config_data['paths']['temp_dir']}")
click.echo("\nSystem Check:")
# Check FFmpeg
import subprocess
try:
result = subprocess.run(['ffmpeg', '-version'], capture_output=True, text=True, stdin=subprocess.DEVNULL)
if result.returncode == 0:
version = result.stdout.split('\n')[0]
click.secho(f" ✓ FFmpeg: {version}", fg='green')
else:
click.secho(f" ✗ FFmpeg: Not found", fg='red')
except FileNotFoundError:
click.secho(f" ✗ FFmpeg: Not installed", fg='red')
# Check CUDA
try:
import torch
if torch.cuda.is_available():
click.secho(f" ✓ CUDA: Available ({torch.cuda.get_device_name(0)})", fg='green')
else:
click.secho(f" ⚠ CUDA: Not available (will use CPU)", fg='yellow')
except ImportError:
click.secho(f" ⚠ PyTorch: Not installed", fg='yellow')
except Exception as e:
click.secho(f"Error: {e}", fg='red', err=True)
sys.exit(1)
@cli.command()
def setup():
"""Run initial setup and checks."""
click.echo("VidGen Setup")
click.echo("=" * 60)
# Check Python version
import sys
if sys.version_info < (3, 9):
click.secho("✗ Python 3.9+ required", fg='red')
sys.exit(1)
else:
click.secho(f"✓ Python {sys.version_info.major}.{sys.version_info.minor}", fg='green')
# Create directories
click.echo("\nCreating directories...")
dirs = ['data/input', 'data/output', 'data/temp', 'models', 'logs', 'config']
for dir_path in dirs:
Path(dir_path).mkdir(parents=True, exist_ok=True)
click.echo(f" ✓ {dir_path}")
# Check dependencies
click.echo("\nChecking dependencies...")
required_packages = [
'torch', 'transformers', 'whisper', 'TTS',
'moviepy', 'opencv-python', 'scenedetect',
'textual', 'rich', 'click', 'yaml'
]
missing = []
for package in required_packages:
try:
__import__(package)
click.secho(f" ✓ {package}", fg='green')
except ImportError:
click.secho(f" ✗ {package}", fg='red')
missing.append(package)
if missing:
click.echo(f"\nMissing packages: {', '.join(missing)}")
click.echo("Install with: pip install -r requirements.txt")
sys.exit(1)
# Check FFmpeg
click.echo("\nChecking system tools...")
import subprocess
try:
subprocess.run(['ffmpeg', '-version'], capture_output=True, check=True, stdin=subprocess.DEVNULL)
click.secho(" ✓ FFmpeg installed", fg='green')
except (FileNotFoundError, subprocess.CalledProcessError):
click.secho(" ✗ FFmpeg not found", fg='red')
click.echo(" Install FFmpeg: https://ffmpeg.org/download.html")
click.echo("\n" + "=" * 60)
click.secho("✓ Setup complete!", fg='green')
click.echo("\nNext steps:")
click.echo(" 1. Place input videos in data/input/")
click.echo(" 2. Run: python app.py (for interactive UI)")
click.echo(" 3. Or: python cli.py generate \"Your Topic\" (for CLI)")
def load_config(config_path: str) -> dict:
"""Load configuration from YAML file."""
path = Path(config_path)
if not path.exists():
raise FileNotFoundError(f"Configuration file not found: {config_path}")
with open(path, 'r') as f:
return yaml.safe_load(f)
def run_simple(
config: dict,
topic: str,
input_videos: Optional[List[Path]],
output_path: Optional[Path],
content: str = ""
):
"""Run pipeline with simple progress output."""
logger = get_logger("cli")
def progress_callback(stage: str, progress: float, message: str):
"""Simple progress output."""
stage_name = stage.replace('_', ' ').title()
click.echo(f"[{stage_name}] {progress:.0f}% - {message}")
pipeline = create_pipeline(config, progress_callback)
click.echo(f"Starting video generation: {topic}")
click.echo("─" * 60)
result = pipeline.run(topic, input_videos, output_path, content)
click.echo("─" * 60)
if result['success']:
click.secho("✓ Video generation complete!", fg='green')
click.echo(f"Output: {result['output_file']}")
click.echo(f"Duration: {result['duration']:.1f}s")
click.echo(f"Events used: {result['events_detected']}")
else:
click.secho(f"✗ Generation failed: {result['error']}", fg='red')
sys.exit(1)
def run_with_tui(
config: dict,
topic: str,
input_videos: Optional[List[Path]],
output_path: Optional[Path],
content: str = ""
):
"""Run pipeline with TUI progress display."""
tui = TUIManager()
def progress_callback(stage: str, progress: float, message: str):
"""TUI progress callback."""
tui.update_stage(stage, progress, message)
pipeline = create_pipeline(config, progress_callback)
tui.start(topic)
tui.set_metadata("input_videos", len(input_videos) if input_videos else 0)
try:
result = pipeline.run(topic, input_videos, output_path, content)
if result['success']:
tui.set_metadata("output_file", str(result['output_file']))
tui.set_metadata("video_duration", config['video']['target_duration'])
tui.stop(success=True, message="Video generation complete!")
click.echo(f"\nOutput file: {result['output_file']}")
else:
tui.stop(success=False, message=f"Generation failed: {result['error']}")
sys.exit(1)
except KeyboardInterrupt:
tui.stop(success=False, message="Cancelled by user")
pipeline.cleanup()
sys.exit(1)
except Exception as e:
tui.stop(success=False, message=f"Error: {e}")
raise
if __name__ == '__main__':
cli()