Opera10 commited on
Commit
a3ce64d
·
verified ·
1 Parent(s): 910c0dc

Delete ltxvideo.py

Browse files
Files changed (1) hide show
  1. ltxvideo.py +0 -309
ltxvideo.py DELETED
@@ -1,309 +0,0 @@
1
- import os
2
- import sys
3
- import json
4
- import base64
5
- import requests
6
- import random
7
- import time
8
- import io
9
-
10
- # ثبت زمان دقیق شروع اجرای اسکریپت
11
- start_time = time.time()
12
-
13
- # =========================================================
14
- # تنظیم زمان انتظار ارتباطی کلاینت به ۲۵۰ ثانیه جهت هماهنگی با تایمر ۱۰ دقیقه‌ای رانر
15
- import httpx
16
- original_client_init = httpx.Client.__init__
17
- def patched_client_init(self, *args, **kwargs):
18
- kwargs['timeout'] = httpx.Timeout(250.0)
19
- original_client_init(self, *args, **kwargs)
20
- httpx.Client.__init__ = patched_client_init
21
-
22
- original_async_init = httpx.AsyncClient.__init__
23
- def patched_async_init(self, *args, **kwargs):
24
- kwargs['timeout'] = httpx.Timeout(250.0)
25
- original_async_init(self, *args, **kwargs)
26
- httpx.AsyncClient.__init__ = patched_async_init
27
- # =========================================================
28
-
29
- from gradio_client import Client, handle_file
30
- from PIL import Image
31
-
32
- raw_prompt = os.environ.get('PROMPT', '')
33
- run_id = os.environ.get('RUN_ID', '')
34
- space_url = os.environ.get('SPACE_URL', '')
35
- github_run_id = os.environ.get('GITHUB_RUN_ID', '')
36
-
37
- def report_failure(error_msg):
38
- try:
39
- requests.post(
40
- f"{space_url}/api/webhook/fail",
41
- json={
42
- "run_id": run_id,
43
- "error": error_msg,
44
- "event_type": "ltxvideo",
45
- "client_payload": {
46
- "prompt": raw_prompt,
47
- "run_id": run_id,
48
- "space_url": space_url
49
- },
50
- "github_run_id": github_run_id
51
- },
52
- timeout=15
53
- )
54
- except Exception:
55
- pass
56
-
57
- # بررسی و رمزگشایی متغیرهای ارسال شده
58
- if not raw_prompt.startswith("VOICECONFIG_LTX_"):
59
- err_str = "Error: Invalid LTX configuration payload."
60
- print(err_str)
61
- report_failure(err_str)
62
- sys.exit(1)
63
-
64
- try:
65
- encoded_data = raw_prompt[len("VOICECONFIG_LTX_"):]
66
- config = json.loads(base64.b64decode(encoded_data).decode('utf-8'))
67
- except Exception as e:
68
- err_str = f"Decode Error: {e}"
69
- print(err_str)
70
- report_failure(err_str)
71
- sys.exit(1)
72
-
73
- print(f"🚀 Starting LTX Video runner. Run ID: {run_id}")
74
-
75
- try:
76
- client = Client("Fighterdan/LTX-2.3-10Eros_I2V")
77
- except Exception as e:
78
- err_str = f"Failed to connect to Gradio Space: {e}"
79
- print(err_str)
80
- report_failure(err_str)
81
- sys.exit(1)
82
-
83
- # مدیریت دانلود تصویر با دو بار تلاش (جلوگیری از خطای تاخیر CDN یا ۴۰۴)
84
- image_url = config.get("image_path")
85
- local_img = "gen_input.png"
86
- download_success = False
87
- max_download_attempts = 5
88
-
89
- print("1. Downloading input image...")
90
- for dl_attempt in range(max_download_attempts):
91
- try:
92
- r = requests.get(image_url, timeout=45)
93
- if r.status_code == 200:
94
- # تایید سلامت فرمت تصویر و تبدیل به RGB خالص برای سازگاری با Gradio
95
- img_data = io.BytesIO(r.content)
96
- img = Image.open(img_data)
97
- img.verify()
98
-
99
- img_data.seek(0)
100
- clean_img = Image.open(img_data).convert('RGB')
101
- clean_img.save(local_img, format='PNG')
102
- download_success = True
103
- print(" -> Image successfully downloaded and verified.")
104
- break
105
- else:
106
- print(f" -> Download attempt {dl_attempt + 1} failed with status: {r.status_code}")
107
- except Exception as e:
108
- print(f" -> Download attempt {dl_attempt + 1} connection failed: {e}")
109
-
110
- if dl_attempt < max_download_attempts - 1:
111
- print(" -> Waiting 8 seconds before retrying image download...")
112
- time.sleep(8.0)
113
-
114
- if not download_success:
115
- err_str = "Failed to download or verify input image after multiple attempts."
116
- print(err_str)
117
- report_failure(err_str)
118
- sys.exit(1)
119
-
120
- # پیکربندی پارامترهای اصلی ساخت ویدیو
121
- base_seed = int(config.get("seed", -1))
122
- seconds = float(config.get("seconds", 5.0))
123
- prompt = config.get("prompt", "")
124
-
125
- print(f"🎬 Generation configurations - Duration: {seconds}s")
126
-
127
- video_path = None
128
- max_attempts = 4
129
-
130
- # حلقه تلاش مجدد داخلی برای ساخت ویدیو
131
- for attempt in range(max_attempts):
132
- # پایش هوشمند زمان سپری شده: اگر بیش از ۵۱۰ ثانیه (۸.۵ دقیقه) گذشته باشد، کار متوقف شده تا درخواست جدیدی صادر شود
133
- elapsed_time = time.time() - start_time
134
- if elapsed_time > 510.0:
135
- print(f"⏳ WARNING: Elapsed time is {elapsed_time:.1f}s. Approaching 10-minute limit.")
136
- print("Aborting current runner execution to request a fresh, brand-new GitHub Action run.")
137
- report_failure("Runner execution time exceeded safe 10-minute limits. Initiating auto-retry on a fresh runner.")
138
- sys.exit(1)
139
-
140
- # تنظیم سید پردازش
141
- seed = base_seed
142
- if seed == -1:
143
- seed = random.randint(1, 2147483647)
144
-
145
- print(f" -> Generation Attempt {attempt + 1} of {max_attempts} with Seed: {seed}...")
146
-
147
- try:
148
- result = client.predict(
149
- image_path=handle_file(local_img),
150
- prompt=prompt,
151
- negative_prompt="captions, music, transition, bad quality, subtitles, text, watermark, cartoon, ugly, blur, static, noise, mutant, horror",
152
- seconds=seconds,
153
- preset="tuned",
154
- seed=seed,
155
- randomize_seed=False,
156
- max_width=1120,
157
- max_height=1344,
158
- target_mp=1.15,
159
- snap_multiple=64,
160
- custom_res_enabled=False,
161
- mode="anchor only",
162
- face_bbox="",
163
- likeness_strength=0.9,
164
- likeness_anchor_strength=0.15,
165
- latent_anchor_strength=0.08,
166
- first_frame_strength=0.82,
167
- sulphur_lora_strength=0.15,
168
- sulphur_v1_lora_strength=0.15,
169
- vbvr_lora_strength=0.5,
170
- dreamly_lora_strength=0.6,
171
- synth_lora_strength=0.0,
172
- plora_lora_strength=0.0,
173
- singularity_lora_strength=0.3,
174
- omninft_lora_strength=0.8,
175
- omninft_bf16_lora_strength=0.0,
176
- better_motion_lora_strength=0.0,
177
- physics_v2_lora_strength=0.0,
178
- hardcut_lora_strength=0.0,
179
- transition_lora_strength=0.15,
180
- sulphur_audio_strength=0.15,
181
- sulphur_v1_audio_strength=0.15,
182
- vbvr_audio_strength=0.5,
183
- dreamly_audio_strength=0.6,
184
- synth_audio_strength=0.0,
185
- plora_audio_strength=0.0,
186
- singularity_audio_strength=0.3,
187
- omninft_audio_strength=0.8,
188
- omninft_bf16_audio_strength=0.0,
189
- better_motion_audio_strength=0.0,
190
- physics_v2_audio_strength=0.0,
191
- hardcut_audio_strength=0.0,
192
- transition_audio_strength=0.0,
193
- cache_at_step=0,
194
- cache_warmup=400,
195
- energy_threshold=0.3,
196
- anchor_similarity_threshold=0.3,
197
- sigma_string="0.4824, 0.2412, 0.0",
198
- skip_refine=False,
199
- gen_budget=0,
200
- profile_name="",
201
- input_mode="single image (i2v)",
202
- msr_ref2=None,
203
- msr_ref3=None,
204
- msr_ref4=None,
205
- msr_background=None,
206
- msr_frame_count=41,
207
- msr_guide_strength=1.0,
208
- msr_lora_strength=0.7,
209
- prompt_relay_enabled=False,
210
- prompt_segments="",
211
- scene_chain_enabled=False,
212
- scene_chain_prompt="",
213
- scene_chain_max_scenes=2,
214
- scene_chain_frame_overlap=8,
215
- scene_chain_mid_guide=True,
216
- scene_chain_mid_guide_strength=0.25,
217
- kv_enabled=False,
218
- kv_strength=1.0,
219
- audio_ref_enabled=False,
220
- audio_ref_file=None,
221
- audio_ref_guidance_scale=3.0,
222
- audio_ref_stem_sep=False,
223
- audio_ref_normalize=True,
224
- kf_strength=0.82,
225
- kf_last_image=None,
226
- kf_mid_enabled=False,
227
- kf_mid_1_image=None,
228
- kf_mid_1_pos=50,
229
- kf_mid_2_image=None,
230
- kf_mid_2_pos=50,
231
- kf_mid_3_image=None,
232
- kf_mid_3_pos=50,
233
- kf_mid_4_image=None,
234
- kf_mid_4_pos=50,
235
- kf_mid_5_image=None,
236
- kf_mid_5_pos=50,
237
- api_name="/generate"
238
- )
239
-
240
- # استخراج مسیر فایل ویدیو خروجی
241
- if isinstance(result, (tuple, list)):
242
- video_data = result[0]
243
- else:
244
- video_data = result
245
-
246
- if isinstance(video_data, dict):
247
- video_path = video_data.get('video') or video_data.get('path')
248
- else:
249
- video_path = str(video_data)
250
-
251
- if video_path and os.path.exists(video_path):
252
- print(" -> Success! Video file created successfully.")
253
- break
254
-
255
- except Exception as e:
256
- err_msg = str(e)
257
- print(f" -> Failed on attempt {attempt + 1}: {err_msg}")
258
-
259
- # شناسایی فوری محدودیت سهمیه هوش مصنوعی و خروج جهت سوئیچ اکانت گیت‌هاب توسط سرور اصلی
260
- if 'ZeroGPU quota' in err_msg or 'quota' in err_msg.lower():
261
- print(" -> ZeroGPU quota hit. Aborting internal attempts to switch GitHub accounts.")
262
- report_failure(err_msg)
263
- sys.exit(1)
264
-
265
- if attempt < max_attempts - 1:
266
- print(" -> Waiting 5 seconds before next internal attempt...")
267
- time.sleep(5.0)
268
-
269
- if not video_path or not os.path.exists(video_path):
270
- err_str = "Failed to generate video after all internal retry attempts."
271
- print(f"CRITICAL ERROR: {err_str}")
272
- report_failure(err_str)
273
- sys.exit(1)
274
-
275
- # فرآیند آپلود فایل و ثبت فراداده‌ها به سرور فلاسک
276
- print("Uploading video back to space...")
277
- ext = 'mp4'
278
- if video_path.endswith('.webm'):
279
- ext = 'webm'
280
-
281
- try:
282
- with open(video_path, 'rb') as f:
283
- requests.post(
284
- f"{space_url}/api/webhook/upload",
285
- data={'run_id': run_id, 'github_run_id': github_run_id, 'ext': ext},
286
- files={'file': f},
287
- timeout=60
288
- )
289
-
290
- print("Uploading Seed Metadata...")
291
- meta_data = {"seed": seed}
292
- with open("meta.json", "w", encoding="utf-8") as mf:
293
- json.dump(meta_data, mf)
294
-
295
- with open("meta.json", "rb") as mf:
296
- requests.post(
297
- f"{space_url}/api/webhook/upload",
298
- data={'run_id': f"{run_id}_meta", 'github_run_id': github_run_id, 'ext': 'json'},
299
- files={'file': mf},
300
- timeout=30
301
- )
302
-
303
- print("✅ SUCCESS!")
304
-
305
- except Exception as up_err:
306
- err_str = f"Upload to main server failed: {up_err}"
307
- print(err_str)
308
- report_failure(err_str)
309
- sys.exit(1)