kines9661 commited on
Commit
1f92d8a
·
verified ·
1 Parent(s): 66617a8

Upload 4 files

Browse files
Files changed (4) hide show
  1. README.md +26 -13
  2. app.py +169 -0
  3. cli.py +562 -0
  4. requirements.txt +3 -0
README.md CHANGED
@@ -1,13 +1,26 @@
1
- ---
2
- title: Video
3
- emoji: 📉
4
- colorFrom: yellow
5
- colorTo: purple
6
- sdk: gradio
7
- sdk_version: 6.14.0
8
- python_version: '3.13'
9
- app_file: app.py
10
- pinned: false
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Veo Video Generator
3
+ emoji: 🎬
4
+ colorFrom: blue
5
+ colorTo: purple
6
+ sdk: gradio
7
+ app_file: app.py
8
+ pinned: false
9
+ license: mit
10
+ ---
11
+
12
+ # Veo Video Generator
13
+
14
+ A Gradio UI for generating videos from text prompts.
15
+
16
+ ## Features
17
+
18
+ - Text prompt input
19
+ - 16:9 and 9:16 aspect ratio options
20
+ - Audio mode option
21
+ - Require-audio validation
22
+ - MP4 preview and download
23
+
24
+ ## Notes
25
+
26
+ This Space runs on the free Hugging Face CPU Basic tier. It may sleep when inactive and generated files may be removed after restart.
app.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import os
3
+ import time
4
+ import uuid
5
+ from pathlib import Path
6
+
7
+ import gradio as gr
8
+
9
+ from cli import ProxyRotator, VeoEngine
10
+
11
+ OUTPUT_DIR = Path("outputs")
12
+ PROXY_FILE = Path("proxies-res-any-1777564385571.txt")
13
+
14
+
15
+ def cleanup_outputs(max_age_seconds=3600):
16
+ OUTPUT_DIR.mkdir(exist_ok=True)
17
+ now = time.time()
18
+ for path in glob.glob(str(OUTPUT_DIR / "*.mp4")):
19
+ try:
20
+ if os.path.getmtime(path) < now - max_age_seconds:
21
+ os.remove(path)
22
+ except OSError:
23
+ pass
24
+
25
+
26
+ def build_engine(model_key="veo"):
27
+ proxy_file = str(PROXY_FILE) if PROXY_FILE.exists() else str(PROXY_FILE)
28
+ rotator = ProxyRotator(proxy_file)
29
+ return VeoEngine(rotator, model_key=model_key)
30
+
31
+
32
+ def generate_video(prompt, model_key, aspect_ratio, audio_mode, require_audio, max_retries):
33
+ prompt = (prompt or "").strip()
34
+ if not prompt:
35
+ return None, "請先輸入 Prompt。"
36
+
37
+ cleanup_outputs()
38
+ max_retries = int(max_retries or 1)
39
+ last_error = None
40
+
41
+ for attempt in range(1, max_retries + 1):
42
+ try:
43
+ engine = build_engine(model_key)
44
+
45
+ yield None, f"Attempt {attempt}/{max_retries}\n正在取得 session nonce..."
46
+ engine.fetch_nonce()
47
+
48
+ yield None, f"Attempt {attempt}/{max_retries}\n正在增強 Prompt..."
49
+ enhanced = engine.enhance_prompt(prompt)
50
+
51
+ yield None, f"Attempt {attempt}/{max_retries}\n正在提交影片生成任務..."
52
+ scene_id = engine.generate_video(enhanced, aspect_ratio, audio_mode=audio_mode)
53
+
54
+ yield None, (
55
+ f"Attempt {attempt}/{max_retries}\n"
56
+ f"Scene ID: {scene_id}\n"
57
+ f"伺服器正在生成影片,通常需要 1-5 分鐘..."
58
+ )
59
+ video_url = engine.wait_for_video(scene_id)
60
+ if not video_url:
61
+ raise RuntimeError("生成完成檢查失敗,沒有取得影片 URL。")
62
+
63
+ filename = OUTPUT_DIR / f"veo_video_{scene_id}_{uuid.uuid4().hex[:8]}.mp4"
64
+ yield None, (
65
+ f"Attempt {attempt}/{max_retries}\n"
66
+ f"Scene ID: {scene_id}\n"
67
+ f"已取得影片 URL,正在下載...\n{video_url}"
68
+ )
69
+ saved_file = engine.download(video_url, str(filename))
70
+
71
+ has_audio = engine.has_audio_track(saved_file)
72
+ if require_audio and not has_audio:
73
+ raise RuntimeError("已下載影片,但沒有偵測到音軌。")
74
+
75
+ status = (
76
+ "生成完成!\n\n"
77
+ f"Model: {engine.MODEL_NAME}\n"
78
+ f"Referrer: {engine.PAGE_URL}\n"
79
+ f"Scene ID: {scene_id}\n"
80
+ f"Aspect Ratio: {aspect_ratio}\n"
81
+ f"Audio Mode: {audio_mode}\n"
82
+ f"Audio Detected: {'Yes' if has_audio else 'No'}\n"
83
+ f"Video URL: {video_url}\n\n"
84
+ f"Enhanced Prompt:\n{enhanced}"
85
+ )
86
+ yield saved_file, status
87
+ return
88
+
89
+ except Exception as exc:
90
+ last_error = exc
91
+ if attempt < max_retries:
92
+ yield None, f"Attempt {attempt}/{max_retries} 失敗:{exc}\n準備重試..."
93
+ time.sleep(2)
94
+ else:
95
+ yield None, f"全部重試失敗。\n最後錯誤:{last_error}"
96
+ return
97
+
98
+
99
+ def create_demo():
100
+ with gr.Blocks(title="Veo Video Generator") as demo:
101
+ gr.Markdown(
102
+ "# 🎬 AI Video Generator\n"
103
+ "**Models: Veo 3.1 / Grok 4.5**\n\n"
104
+ "Hugging Face Spaces 免費版 UI。選擇模型、輸入 Prompt 後會生成影片、下載 MP4,並檢查是否包含音軌。"
105
+ )
106
+
107
+ with gr.Row():
108
+ with gr.Column(scale=1):
109
+ prompt = gr.Textbox(
110
+ label="Prompt",
111
+ lines=5,
112
+ placeholder="A cinematic shot of a futuristic city at sunset",
113
+ )
114
+ model_key = gr.Radio(
115
+ choices=[("Veo 3.1", "veo"), ("Grok 4.5", "grok")],
116
+ value="veo",
117
+ label="Model",
118
+ info="Veo 3.1 使用 /veo-video-generator/;Grok 4.5 使用 /grok-ai-video-generator/。",
119
+ )
120
+ aspect_ratio = gr.Radio(
121
+ choices=["16:9", "9:16"],
122
+ value="16:9",
123
+ label="Aspect Ratio",
124
+ )
125
+ audio_mode = gr.Radio(
126
+ choices=["auto", "try", "none"],
127
+ value="auto",
128
+ label="Audio Mode",
129
+ info="auto 使用網站預設;try 會附加實驗音效參數;none 不附加音效偏好。",
130
+ )
131
+ require_audio = gr.Checkbox(
132
+ value=False,
133
+ label="Require Audio",
134
+ info="啟用後,如果下載影片沒有偵測到音軌,任務會標記為失敗。",
135
+ )
136
+ max_retries = gr.Slider(
137
+ minimum=1,
138
+ maximum=3,
139
+ step=1,
140
+ value=1,
141
+ label="Max Retries",
142
+ )
143
+ generate_btn = gr.Button("Generate Video", variant="primary")
144
+
145
+ with gr.Column(scale=1):
146
+ video = gr.Video(label="Generated Video")
147
+ status = gr.Textbox(label="Status", lines=14)
148
+
149
+ gr.Markdown(
150
+ "## 使用提示\n"
151
+ "- 免費 Space 可能會休眠,首次啟動較慢。\n"
152
+ "- 一次只建議生成一個任務。\n"
153
+ "- 影片會暫存在 Space 的 outputs 目錄,重啟後可能消失。\n"
154
+ "- 若設為 Public Space,任何人都可能使用你的介面。"
155
+ )
156
+
157
+ generate_btn.click(
158
+ fn=generate_video,
159
+ inputs=[prompt, model_key, aspect_ratio, audio_mode, require_audio, max_retries],
160
+ outputs=[video, status],
161
+ )
162
+
163
+ return demo
164
+
165
+
166
+ if __name__ == "__main__":
167
+ cleanup_outputs()
168
+ app = create_demo()
169
+ app.queue(default_concurrency_limit=1).launch(theme=gr.themes.Soft())
cli.py ADDED
@@ -0,0 +1,562 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import sys
4
+ import time
5
+ import json
6
+ import random
7
+ import argparse
8
+ import subprocess
9
+ import requests
10
+
11
+ try:
12
+ from rich.console import Console
13
+ from rich.prompt import Prompt
14
+ from rich.panel import Panel
15
+ from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TimeElapsedColumn
16
+ from rich.table import Table
17
+ from rich.text import Text
18
+ except ImportError:
19
+ import subprocess
20
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "rich", "-q"])
21
+ from rich.console import Console
22
+ from rich.prompt import Prompt
23
+ from rich.panel import Panel
24
+ from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TimeElapsedColumn
25
+ from rich.table import Table
26
+ from rich.text import Text
27
+
28
+ console = Console()
29
+
30
+ # ─────────────────────────────────────────────────────────
31
+ # Proxy Rotator
32
+ # ─────────────────────────────────────────────────────────
33
+ class ProxyRotator:
34
+ def __init__(self, proxy_file):
35
+ self.proxies = []
36
+ self.current_index = 0
37
+ self._load(proxy_file)
38
+
39
+ def _load(self, filename):
40
+ try:
41
+ with open(filename, 'r') as f:
42
+ for line in f:
43
+ line = line.strip()
44
+ if not line:
45
+ continue
46
+ parts = line.split(':')
47
+ if len(parts) == 4:
48
+ # IP:PORT:USER:PASS
49
+ proxy_url = f"http://{parts[2]}:{parts[3]}@{parts[0]}:{parts[1]}"
50
+ self.proxies.append(proxy_url)
51
+ elif len(parts) == 2:
52
+ self.proxies.append(f"http://{parts[0]}:{parts[1]}")
53
+ random.shuffle(self.proxies)
54
+ console.print(f"[bold green]✔ Loaded {len(self.proxies)} proxies![/bold green]")
55
+ except Exception as e:
56
+ console.print(f"[bold red]✖ Failed to load proxies: {e}[/bold red]")
57
+
58
+ def next(self):
59
+ if not self.proxies:
60
+ return None
61
+ proxy = self.proxies[self.current_index % len(self.proxies)]
62
+ self.current_index += 1
63
+ return proxy
64
+
65
+ def display_current(self, proxy):
66
+ if proxy:
67
+ safe = proxy.split('@')[-1] if '@' in proxy else proxy
68
+ console.print(f"[dim cyan]🔄 Proxy:[/dim cyan] [bold white]{safe}[/bold white]")
69
+
70
+
71
+ # ─────────────────────────────────────────────────────────
72
+ # VeoAI Engine
73
+ # ─────────────────────────────────────────────────────────
74
+ class VeoEngine:
75
+ AJAX_URL = "https://veoaifree.com/wp-admin/admin-ajax.php"
76
+ VIDEO_BASE = "https://veoaifree.com/video/uploads/"
77
+ MODEL_CONFIGS = {
78
+ "veo": {
79
+ "name": "Veo 3.1",
80
+ "page_url": "https://veoaifree.com/veo-video-generator/",
81
+ },
82
+ "grok": {
83
+ "name": "Grok 4.5",
84
+ "page_url": "https://veoaifree.com/grok-ai-video-generator/",
85
+ },
86
+ }
87
+ DEFAULT_MODEL = "veo"
88
+ PAGE_URL = MODEL_CONFIGS[DEFAULT_MODEL]["page_url"]
89
+ MODEL_NAME = MODEL_CONFIGS[DEFAULT_MODEL]["name"]
90
+
91
+ HEADERS = {
92
+ "accept": "*/*",
93
+ "accept-language": "en-US,en;q=0.7",
94
+ "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
95
+ "sec-ch-ua": '"Brave";v="147", "Not.A/Brand";v="8", "Chromium";v="147"',
96
+ "sec-ch-ua-mobile": "?0",
97
+ "sec-ch-ua-platform": '"Linux"',
98
+ "sec-fetch-dest": "empty",
99
+ "sec-fetch-mode": "cors",
100
+ "sec-fetch-site": "same-origin",
101
+ "sec-gpc": "1",
102
+ "x-requested-with": "XMLHttpRequest",
103
+ }
104
+
105
+ def __init__(self, proxy_rotator, model_key=DEFAULT_MODEL):
106
+ self.rotator = proxy_rotator
107
+ self.model_key = self.normalize_model_key(model_key)
108
+ self.model_config = self.MODEL_CONFIGS[self.model_key]
109
+ self.MODEL_NAME = self.model_config["name"]
110
+ self.PAGE_URL = self.model_config["page_url"]
111
+ self.session = None
112
+ self.nonce = None
113
+ self._build_session()
114
+
115
+ @classmethod
116
+ def normalize_model_key(cls, model_key):
117
+ model_key = (model_key or cls.DEFAULT_MODEL).strip().lower()
118
+ aliases = {
119
+ "veo": "veo",
120
+ "veo 3.1": "veo",
121
+ "grok": "grok",
122
+ "grok 4.5": "grok",
123
+ }
124
+ model_key = aliases.get(model_key, model_key)
125
+ if model_key not in cls.MODEL_CONFIGS:
126
+ raise ValueError(f"Unknown model '{model_key}'. Available models: {', '.join(cls.MODEL_CONFIGS)}")
127
+ return model_key
128
+
129
+ @classmethod
130
+ def model_choices(cls):
131
+ return list(cls.MODEL_CONFIGS.keys())
132
+
133
+ def _build_session(self):
134
+ self.session = requests.Session()
135
+ self.session.headers.update(self.HEADERS)
136
+ self.session.headers["referer"] = self.PAGE_URL
137
+ self.session.proxies = {} # direct connection, no proxy
138
+
139
+ def rotate(self):
140
+ console.print("[bold dark_orange]↻ Rotating to next proxy...[/bold dark_orange]")
141
+ self._build_session()
142
+
143
+ def _rotate_poll_proxy(self):
144
+ """No-op — running direct, no proxies to rotate."""
145
+ pass
146
+
147
+ # ── Step 1: Grab nonce from the page ──
148
+ def fetch_nonce(self):
149
+ with console.status("[bold green]⟳ Fetching session nonce...", spinner="bouncingBar"):
150
+ res = self.session.get(self.PAGE_URL, timeout=20)
151
+ res.raise_for_status()
152
+
153
+ # Primary pattern
154
+ matches = re.findall(r'nonce["\']?\s*[:=]\s*["\']([a-f0-9]{10})["\']', res.text)
155
+ if matches:
156
+ self.nonce = matches[0]
157
+ console.print(f"[bold green]✔ Nonce locked:[/bold green] [white]{self.nonce}[/white]")
158
+ return
159
+
160
+ # Fallback — grab any 10-char hex that looks like a WP nonce
161
+ fallback = re.findall(r'"([a-f0-9]{10})"', res.text)
162
+ if fallback:
163
+ self.nonce = fallback[0]
164
+ console.print(f"[bold yellow]⚠ Guessed nonce:[/bold yellow] [white]{self.nonce}[/white]")
165
+ return
166
+
167
+ raise Exception("Nonce not found in page HTML — proxy might be blocked.")
168
+
169
+ # ── Step 2: Enhance prompt via their AI ──
170
+ def enhance_prompt(self, raw_prompt):
171
+ with console.status("[bold magenta]✦ Enhancing prompt...", spinner="dots12"):
172
+ payload = {
173
+ "action": "veo_video_generator",
174
+ "nonce": self.nonce,
175
+ "prompt": raw_prompt,
176
+ "model": self.MODEL_NAME,
177
+ "modelName": self.MODEL_NAME,
178
+ "actionType": "main-prompt-generation",
179
+ }
180
+ res = self.session.post(self.AJAX_URL, data=payload, timeout=30)
181
+ res.raise_for_status()
182
+
183
+ console.print(f"[dim] Raw enhance response: {res.text[:200]}[/dim]")
184
+
185
+ try:
186
+ data = res.json()
187
+ if isinstance(data, dict):
188
+ enhanced = str(data.get("data", "")).strip()
189
+ else:
190
+ enhanced = res.text.strip()
191
+ except:
192
+ enhanced = res.text.strip()
193
+
194
+ if not enhanced or len(enhanced) < 5:
195
+ raise Exception(f"Enhancement failed. Response: {res.text[:150]}")
196
+
197
+ console.print(Panel(enhanced, title="[bold magenta]✦ Enhanced Prompt[/bold magenta]", border_style="magenta"))
198
+ return enhanced
199
+
200
+ # ── Step 3: Queue video generation ──
201
+ def generate_video(self, enhanced_prompt, aspect_ratio="16:9", audio_mode="auto"):
202
+ ratio_map = {
203
+ "16:9": "VIDEO_ASPECT_RATIO_LANDSCAPE",
204
+ "9:16": "VIDEO_ASPECT_RATIO_PORTRAIT",
205
+ }
206
+ api_ratio = ratio_map.get(aspect_ratio, "VIDEO_ASPECT_RATIO_LANDSCAPE")
207
+
208
+ with console.status(f"[bold blue]⚡ Queueing video generation ({aspect_ratio})...", spinner="earth"):
209
+ payload = {
210
+ "action": "veo_video_generator",
211
+ "nonce": self.nonce,
212
+ "prompt": enhanced_prompt,
213
+ "model": self.MODEL_NAME,
214
+ "modelName": self.MODEL_NAME,
215
+ "totalVariations": "1",
216
+ "aspectRatio": api_ratio,
217
+ "actionType": "full-video-generate",
218
+ }
219
+ if audio_mode == "try":
220
+ payload.update({
221
+ "generateAudio": "true",
222
+ "enableAudio": "true",
223
+ "withAudio": "true",
224
+ "audio": "true",
225
+ })
226
+ res = self.session.post(self.AJAX_URL, data=payload, timeout=30)
227
+ res.raise_for_status()
228
+
229
+ console.print(f"[dim] Raw generate response: {res.text[:300]}[/dim]")
230
+
231
+ scene_data = None
232
+ try:
233
+ data = res.json()
234
+ if isinstance(data, dict):
235
+ scene_data = data.get("data") or data.get("sceneData")
236
+ if isinstance(scene_data, dict):
237
+ scene_data = scene_data.get("sceneData") or scene_data.get("id")
238
+ except:
239
+ pass
240
+
241
+ if not scene_data:
242
+ # Brute-extract any 6-8 digit number
243
+ nums = re.findall(r'(\d{6,8})', res.text)
244
+ if nums:
245
+ scene_data = nums[0]
246
+
247
+ if not scene_data:
248
+ raise Exception(f"Could not extract scene ID. Response: {res.text[:200]}")
249
+
250
+ scene_data = str(scene_data)
251
+ console.print(f"[bold blue]✔ Queued! Scene ID:[/bold blue] [white]{scene_data}[/white]")
252
+ return scene_data
253
+
254
+ # ── Step 4: Wait for video ──
255
+ # Reverse-engineered from logic.js:
256
+ # - Browser waits 85s after generate before first poll
257
+ # - Empty response = still rendering, retry in 20s
258
+ # - Non-empty response = raw video URL (plain text, not JSON)
259
+ # - Site does: url.replace("videos/", "video/") on the result
260
+ def wait_for_video(self, scene_data):
261
+ payload = {
262
+ "action": "veo_video_generator",
263
+ "nonce": self.nonce,
264
+ "sceneData": scene_data,
265
+ "actionType": "final-video-results",
266
+ }
267
+
268
+ # ── Phase 1: Initial wait (85s, matching the browser's setTimeout) ──
269
+ console.print(f"\n[bold cyan]⏳ Server is rendering your video...[/bold cyan]")
270
+ console.print(f"[dim] (Waiting 85s before first check — this matches how the site works)[/dim]\n")
271
+
272
+ with Progress(
273
+ SpinnerColumn(),
274
+ TextColumn("[bold cyan]{task.description}"),
275
+ BarColumn(bar_width=40),
276
+ TextColumn("[bold]{task.percentage:>3.0f}%"),
277
+ TimeElapsedColumn(),
278
+ console=console,
279
+ ) as progress:
280
+ task = progress.add_task("Rendering", total=85)
281
+ for i in range(85):
282
+ time.sleep(1)
283
+ progress.update(task, advance=1)
284
+
285
+ # ── Phase 2: Poll every 20s until we get a non-empty response ──
286
+ max_attempts = 15 # 15 × 20s = 5 minutes max polling
287
+ for attempt in range(1, max_attempts + 1):
288
+ try:
289
+ console.print(f"[cyan] → Checking for video (attempt {attempt}/{max_attempts})...[/cyan]")
290
+ res = self.session.post(self.AJAX_URL, data=payload, timeout=120)
291
+
292
+ body = res.text.strip()
293
+ console.print(f"[dim] ← Status: {res.status_code} | Size: {len(body)} bytes[/dim]")
294
+
295
+ if body == "":
296
+ # Empty = still processing (confirmed from site JS)
297
+ console.print(f"[yellow] ⏸ Still rendering... checking again in 20s[/yellow]")
298
+ time.sleep(20)
299
+ continue
300
+
301
+ # Non-empty response — extract the video URL
302
+ console.print(f"[dim] ← Body: {body[:500]}[/dim]")
303
+ video_url = self._extract_video_url(body, scene_data)
304
+ if video_url:
305
+ return video_url
306
+
307
+ # Got a non-empty response but couldn't parse a URL — log it and retry
308
+ console.print(f"[yellow] ⚠ Got response but no video URL found. Retrying in 20s...[/yellow]")
309
+ time.sleep(20)
310
+
311
+ except requests.exceptions.Timeout:
312
+ console.print(f"[yellow] ⏸ Request timed out (>120s). Retrying...[/yellow]")
313
+ time.sleep(5)
314
+ except Exception as e:
315
+ console.print(f"[red] ✖ Poll error: {e}[/red]")
316
+ time.sleep(10)
317
+
318
+ raise Exception("Could not retrieve video after all poll attempts.")
319
+
320
+ def _extract_video_url(self, response_text, scene_data):
321
+ text = response_text.strip()
322
+
323
+ # The site's JS does: url.replace("videos/", "video/")
324
+ text = text.replace("videos/", "video/")
325
+
326
+ # Method 1: Response IS a direct URL (most common from this site)
327
+ if text.startswith("http") and (".mp4" in text or "video" in text):
328
+ console.print(f"[bold bright_green]✔ Got video URL![/bold bright_green]")
329
+ return text
330
+
331
+ # Method 2: URL embedded in a longer response
332
+ mp4_matches = re.findall(r'https?://[^\s<"\'\\\]]+\.mp4', text)
333
+ if mp4_matches:
334
+ url = mp4_matches[0].replace("videos/", "video/")
335
+ console.print(f"[bold bright_green]✔ Extracted video URL from response![/bold bright_green]")
336
+ return url
337
+
338
+ # Method 3: Filename pattern → construct full URL
339
+ filename_matches = re.findall(r'(video_\d+_\d+\.mp4)', text)
340
+ if filename_matches:
341
+ url = f"{self.VIDEO_BASE}{filename_matches[0]}"
342
+ console.print(f"[bold bright_green]✔ Constructed video URL from filename![/bold bright_green]")
343
+ return url
344
+
345
+ # Method 4: Try JSON parsing for nested data
346
+ try:
347
+ data = json.loads(text)
348
+ data_str = json.dumps(data)
349
+ mp4_matches = re.findall(r'https?://[^\s<"\'\\\]]+\.mp4', data_str)
350
+ if mp4_matches:
351
+ return mp4_matches[0].replace("videos/", "video/")
352
+
353
+ if isinstance(data, dict):
354
+ inner = data.get("data", "")
355
+ if isinstance(inner, str) and inner.strip():
356
+ inner = inner.strip().replace("videos/", "video/")
357
+ if inner.startswith("http"):
358
+ return inner
359
+ if "mp4" in inner:
360
+ return f"{self.VIDEO_BASE}{inner}"
361
+ except (json.JSONDecodeError, ValueError):
362
+ pass
363
+
364
+ return None
365
+
366
+ # ── Step 5: Download the mp4 ──
367
+ def download(self, url, filename):
368
+ with console.status(f"[bold yellow]⬇ Downloading video...", spinner="arrow3"):
369
+ headers = {
370
+ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36",
371
+ "Referer": self.PAGE_URL,
372
+ "Range": "bytes=0-",
373
+ }
374
+ res = requests.get(url, stream=True, headers=headers, timeout=60)
375
+
376
+ if res.status_code not in (200, 206):
377
+ raise Exception(f"Download failed: HTTP {res.status_code}")
378
+
379
+ total = int(res.headers.get("content-length", 0))
380
+ downloaded = 0
381
+
382
+ # Use progress bar for download
383
+ with Progress(
384
+ SpinnerColumn(),
385
+ TextColumn("[bold yellow]{task.description}"),
386
+ BarColumn(bar_width=40),
387
+ TextColumn("[bold]{task.percentage:>3.0f}%"),
388
+ TimeElapsedColumn(),
389
+ console=console,
390
+ ) as progress:
391
+ task = progress.add_task("Downloading", total=total or None)
392
+ with open(filename, "wb") as f:
393
+ for chunk in res.iter_content(chunk_size=65536):
394
+ if chunk:
395
+ f.write(chunk)
396
+ downloaded += len(chunk)
397
+ progress.update(task, advance=len(chunk))
398
+
399
+ size_mb = os.path.getsize(filename) / (1024 * 1024)
400
+ console.print(f"[bold yellow]✔ Saved:[/bold yellow] [green]{filename}[/green] ({size_mb:.1f} MB)")
401
+ return filename
402
+
403
+ def has_audio_track(self, filename):
404
+ ffprobe_result = self._has_audio_track_with_ffprobe(filename)
405
+ if ffprobe_result is not None:
406
+ return ffprobe_result
407
+
408
+ try:
409
+ with open(filename, "rb") as f:
410
+ data = f.read()
411
+ return b"soun" in data and any(codec in data for codec in (b"mp4a", b"aac", b"ac-3", b"ec-3", b"Opus", b"alac"))
412
+ except OSError:
413
+ return False
414
+
415
+ def _has_audio_track_with_ffprobe(self, filename):
416
+ try:
417
+ result = subprocess.run(
418
+ [
419
+ "ffprobe",
420
+ "-v",
421
+ "error",
422
+ "-select_streams",
423
+ "a",
424
+ "-show_entries",
425
+ "stream=codec_type",
426
+ "-of",
427
+ "csv=p=0",
428
+ filename,
429
+ ],
430
+ capture_output=True,
431
+ text=True,
432
+ timeout=20,
433
+ )
434
+ except (FileNotFoundError, subprocess.SubprocessError):
435
+ return None
436
+
437
+ if result.returncode != 0:
438
+ return None
439
+ return "audio" in result.stdout.lower()
440
+
441
+
442
+ # ─────────────────────────────────────────────────────────
443
+ # Main CLI Flow
444
+ # ─────────────────────────────────────────────────────────
445
+ def run_with_retry(engine, raw_prompt, aspect_ratio, max_retries=20, audio_mode="auto", require_audio=False):
446
+ for attempt in range(1, max_retries + 1):
447
+ try:
448
+ console.rule(f"[bold]Attempt {attempt}/{max_retries}", style="dim")
449
+
450
+ engine.fetch_nonce()
451
+ enhanced = engine.enhance_prompt(raw_prompt)
452
+ scene_id = engine.generate_video(enhanced, aspect_ratio, audio_mode=audio_mode)
453
+ video_url = engine.wait_for_video(scene_id)
454
+
455
+ if video_url:
456
+ console.print(f"\n[bold bright_green]🎬 Video URL: {video_url}[/bold bright_green]\n")
457
+ filename = f"veo_video_{scene_id}.mp4"
458
+ saved_file = engine.download(video_url, filename)
459
+ has_audio = engine.has_audio_track(saved_file)
460
+ audio_status = "Audio track detected" if has_audio else "No audio track detected"
461
+ audio_style = "bright_green" if has_audio else "yellow"
462
+ console.print(f"[bold {audio_style}]🔊 {audio_status}[/bold {audio_style}]")
463
+
464
+ if require_audio and not has_audio:
465
+ raise Exception("Audio track is required, but the downloaded video has no detectable audio stream.")
466
+
467
+ console.print(Panel(
468
+ f"[bold bright_green]ALL DONE![/bold bright_green]\n"
469
+ f"Video saved as: [white]{filename}[/white]\n"
470
+ f"Audio: [white]{audio_status}[/white]",
471
+ border_style="green"
472
+ ))
473
+ return True
474
+
475
+ except Exception as e:
476
+ console.print(f"\n[bold red]✖ Failed:[/bold red] {e}")
477
+ if attempt < max_retries:
478
+ console.print(f"[dark_orange] Rotating proxy and retrying...[/dark_orange]\n")
479
+ engine.rotate()
480
+ time.sleep(2)
481
+ else:
482
+ console.print("[bold red]All retries exhausted.[/bold red]")
483
+ return False
484
+
485
+
486
+ def parse_args():
487
+ parser = argparse.ArgumentParser(description="Generate a video from a text prompt using the VeoAI CLI flow.")
488
+ parser.add_argument("--prompt", help="Prompt to generate the video from. If omitted, interactive input is used.")
489
+ parser.add_argument(
490
+ "--aspect-ratio",
491
+ choices=["16:9", "9:16"],
492
+ default=None,
493
+ help="Video aspect ratio. If omitted, interactive input is used.",
494
+ )
495
+ parser.add_argument(
496
+ "--model",
497
+ choices=VeoEngine.model_choices(),
498
+ default=VeoEngine.DEFAULT_MODEL,
499
+ help="Model/page to use: 'veo' uses Veo 3.1; 'grok' uses Grok 4.5.",
500
+ )
501
+ parser.add_argument(
502
+ "--max-retries",
503
+ type=int,
504
+ default=20,
505
+ help="Maximum number of generation attempts before giving up.",
506
+ )
507
+ parser.add_argument(
508
+ "--audio-mode",
509
+ choices=["auto", "try", "none"],
510
+ default="auto",
511
+ help="Audio handling mode. 'try' sends experimental audio flags to the generator; 'auto' uses default API behavior.",
512
+ )
513
+ parser.add_argument(
514
+ "--require-audio",
515
+ action="store_true",
516
+ help="Fail the run if the downloaded MP4 has no detectable audio track.",
517
+ )
518
+ return parser.parse_args()
519
+
520
+
521
+ def main():
522
+ args = parse_args()
523
+ os.system("clear" if os.name == "posix" else "cls")
524
+
525
+ console.print(Panel.fit(
526
+ "[bold red]🔥 VEO AI VIDEO GENERATOR 🔥[/bold red]\n"
527
+ "[dim white]Proxy-Rotated · Auto-Retry · Fully Automated[/dim white]",
528
+ border_style="bright_red",
529
+ ))
530
+
531
+ proxy_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "proxies-res-any-1777564385571.txt")
532
+ rotator = ProxyRotator(proxy_file)
533
+ engine = VeoEngine(rotator, model_key=args.model)
534
+ console.print(f"[dim]Model: {engine.MODEL_NAME}[/dim]")
535
+ console.print(f"[dim]Referrer: {engine.PAGE_URL}[/dim]")
536
+
537
+ raw_prompt = args.prompt or Prompt.ask("\n[bold bright_white]Enter your prompt[/bold bright_white]")
538
+
539
+ if args.aspect_ratio:
540
+ aspect_ratio = args.aspect_ratio
541
+ else:
542
+ ratio_choice = Prompt.ask(
543
+ "[bold bright_white]Aspect Ratio[/bold bright_white]",
544
+ choices=["1", "2"],
545
+ default="1",
546
+ )
547
+ aspect_ratio = "9:16" if ratio_choice == "2" else "16:9"
548
+
549
+ console.print(f"[dim]Selected: {aspect_ratio}[/dim]\n")
550
+
551
+ run_with_retry(
552
+ engine,
553
+ raw_prompt,
554
+ aspect_ratio,
555
+ max_retries=args.max_retries,
556
+ audio_mode=args.audio_mode,
557
+ require_audio=args.require_audio,
558
+ )
559
+
560
+
561
+ if __name__ == "__main__":
562
+ main()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ requests
2
+ rich
3
+ gradio