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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
# ==========================================================
|
3 |
+
# FILE: ghostpack.py
|
4 |
+
# ==========================================================
|
5 |
+
import os, sys, time, json, argparse, importlib.util, subprocess, traceback
|
6 |
+
import torch, einops, numpy as np, gradio as gr
|
7 |
+
from PIL import Image
|
8 |
+
from diffusers import AutoencoderKLHunyuanVideo
|
9 |
+
from transformers import (
|
10 |
+
LlamaModel, CLIPTextModel, LlamaTokenizerFast, CLIPTokenizer,
|
11 |
+
SiglipImageProcessor, SiglipVisionModel
|
12 |
+
)
|
13 |
+
try:
|
14 |
+
from diffusers_helper.hf_login import login
|
15 |
+
from diffusers_helper.hunyuan import (
|
16 |
+
encode_prompt_conds, vae_decode, vae_encode, vae_decode_fake
|
17 |
+
)
|
18 |
+
from diffusers_helper.utils import (
|
19 |
+
save_bcthw_as_mp4, crop_or_pad_yield_mask, soft_append_bcthw,
|
20 |
+
resize_and_center_crop, generate_timestamp
|
21 |
+
)
|
22 |
+
from diffusers_helper.models.hunyuan_video_packed import HunyuanVideoTransformer3DModelPacked
|
23 |
+
from diffusers_helper.pipelines.k_diffusion_hunyuan import sample_hunyuan
|
24 |
+
from diffusers_helper.memory import (
|
25 |
+
gpu, get_cuda_free_memory_gb, move_model_to_device_with_memory_preservation,
|
26 |
+
offload_model_from_device_for_memory_preservation, fake_diffusers_current_device,
|
27 |
+
DynamicSwapInstaller, unload_complete_models, load_model_as_complete
|
28 |
+
)
|
29 |
+
from diffusers_helper.thread_utils import AsyncStream, async_run
|
30 |
+
from diffusers_helper.gradio.progress_bar import make_progress_bar_css, make_progress_bar_html
|
31 |
+
from diffusers_helper.clip_vision import hf_clip_vision_encode
|
32 |
+
from diffusers_helper.bucket_tools import find_nearest_bucket
|
33 |
+
except ImportError as e:
|
34 |
+
with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'outputs', 'install_logs.txt'), 'a') as f:
|
35 |
+
f.write(f"[Dependency Error] {str(e)}\n")
|
36 |
+
print(f"Dependency error: {str(e)}. Check outputs/install_logs.txt.")
|
37 |
+
sys.exit(1)
|
38 |
+
|
39 |
+
try:
|
40 |
+
from huggingface_hub import hf_hub_download
|
41 |
+
from safetensors.torch import load_file
|
42 |
+
except ImportError as e:
|
43 |
+
with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'outputs', 'install_logs.txt'), 'a') as f:
|
44 |
+
f.write(f"[Dependency Error] {str(e)}\n")
|
45 |
+
print(f"Dependency error: {str(e)}. Install huggingface_hub and safetensors: pip install huggingface_hub safetensors")
|
46 |
+
sys.exit(1)
|
47 |
+
|
48 |
+
# ------------------------- CLI ----------------------------
|
49 |
+
parser = argparse.ArgumentParser()
|
50 |
+
parser.add_argument('--share', action='store_true')
|
51 |
+
parser.add_argument('--server', type=str, default='0.0.0.0')
|
52 |
+
parser.add_argument('--port', type=int)
|
53 |
+
parser.add_argument('--inbrowser', action='store_true')
|
54 |
+
parser.add_argument('--cli', action='store_true')
|
55 |
+
args = parser.parse_args()
|
56 |
+
|
57 |
+
BASE = os.path.abspath(os.path.dirname(__file__))
|
58 |
+
os.environ['HF_HOME'] = os.path.join(BASE, 'hf_download')
|
59 |
+
LORA_CACHE = os.path.join(BASE, 'dlora')
|
60 |
+
os.makedirs(LORA_CACHE, exist_ok=True)
|
61 |
+
|
62 |
+
# Set HF token from environment variable
|
63 |
+
HF_TOKEN = os.getenv('HF_TOKEN', 'XXXXXXXXXXXXXXXXXXXXXXXX')
|
64 |
+
|
65 |
+
if args.cli:
|
66 |
+
print("👻 GhostPack F1 Pro CLI\n")
|
67 |
+
print("python ghostpack.py # launch UI")
|
68 |
+
print("python ghostpack.py --cli # show help\n")
|
69 |
+
sys.exit(0)
|
70 |
+
|
71 |
+
# ---------------------- Paths -----------------------------
|
72 |
+
OUT_BASE = os.path.join(BASE, 'outputs')
|
73 |
+
OUT_IMG = os.path.join(OUT_BASE, 'img')
|
74 |
+
OUT_TMP = os.path.join(OUT_BASE, 'tmp_vid')
|
75 |
+
OUT_VID = os.path.join(OUT_BASE, 'vid')
|
76 |
+
PROMPT_LOG = os.path.join(OUT_BASE, 'prompts.txt')
|
77 |
+
SAVED_PROMPTS = os.path.join(OUT_BASE, 'saved_prompts.json')
|
78 |
+
INSTALL_LOG = os.path.join(OUT_BASE, 'install_logs.txt')
|
79 |
+
for d in (OUT_BASE, OUT_IMG, OUT_TMP, OUT_VID):
|
80 |
+
os.makedirs(d, exist_ok=True)
|
81 |
+
if not os.path.exists(SAVED_PROMPTS):
|
82 |
+
json.dump([], open(SAVED_PROMPTS,'w'))
|
83 |
+
if not os.path.exists(INSTALL_LOG):
|
84 |
+
open(INSTALL_LOG,'w').close()
|
85 |
+
|
86 |
+
# ---------------- Auto-Downloader ------------------------
|
87 |
+
def auto_download_fastvideo_lora():
|
88 |
+
repo_id = "Kijai/HunyuanVideo_comfy"
|
89 |
+
filename = "hyvideo_FastVideo_LoRA-fp8.safetensors"
|
90 |
+
try:
|
91 |
+
msg, lora_path = download_lora(repo_id, filename, HF_TOKEN)
|
92 |
+
return msg
|
93 |
+
except Exception as e:
|
94 |
+
with open(INSTALL_LOG, 'a') as f:
|
95 |
+
f.write(f"[Auto-Download Error] {repo_id}/{filename}: {str(e)}\n")
|
96 |
+
return f"❌ Auto-download failed: {str(e)}"
|
97 |
+
|
98 |
+
# Run auto-downloader at startup
|
99 |
+
auto_download_status = auto_download_fastvideo_lora()
|
100 |
+
|
101 |
+
# ---------------- Prompt utils ---------------------------
|
102 |
+
def get_last_prompts():
|
103 |
+
return json.load(open(SAVED_PROMPTS))[-5:][::-1]
|
104 |
+
|
105 |
+
def save_prompt_fn(p, n):
|
106 |
+
if not p:
|
107 |
+
return "❌ No prompt"
|
108 |
+
data = json.load(open(SAVED_PROMPTS))
|
109 |
+
entry = {'prompt': p, 'negative': n}
|
110 |
+
if entry not in data:
|
111 |
+
data.append(entry)
|
112 |
+
json.dump(data, open(SAVED_PROMPTS,'w'))
|
113 |
+
return "✅ Saved"
|
114 |
+
|
115 |
+
def load_prompt_fn(idx):
|
116 |
+
lst = get_last_prompts()
|
117 |
+
return lst[idx]['prompt'] if idx < len(lst) else ""
|
118 |
+
|
119 |
+
# ---------------- Cleanup utils --------------------------
|
120 |
+
def clear_temp_videos():
|
121 |
+
try:
|
122 |
+
[os.remove(os.path.join(OUT_TMP,f)) for f in os.listdir(OUT_TMP)]
|
123 |
+
return "✅ Temp cleared"
|
124 |
+
except Exception as e:
|
125 |
+
return f"❌ Failed to clear temp: {str(e)}"
|
126 |
+
|
127 |
+
def clear_old_files():
|
128 |
+
try:
|
129 |
+
cutoff = time.time() - 7*24*3600
|
130 |
+
c = 0
|
131 |
+
for d in (OUT_TMP, OUT_IMG):
|
132 |
+
for f in os.listdir(d):
|
133 |
+
p = os.path.join(d, f)
|
134 |
+
if os.path.isfile(p) and os.path.getmtime(p) < cutoff:
|
135 |
+
os.remove(p)
|
136 |
+
c += 1
|
137 |
+
return f"✅ {c} old files removed"
|
138 |
+
except Exception as e:
|
139 |
+
return f"❌ Failed to clear old files: {str(e)}"
|
140 |
+
|
141 |
+
def clear_images():
|
142 |
+
try:
|
143 |
+
[os.remove(os.path.join(OUT_IMG,f)) for f in os.listdir(OUT_IMG)]
|
144 |
+
return "✅ Images cleared"
|
145 |
+
except Exception as e:
|
146 |
+
return f"❌ Failed to clear images: {str(e)}"
|
147 |
+
|
148 |
+
def clear_videos():
|
149 |
+
try:
|
150 |
+
[os.remove(os.path.join(OUT_VID,f)) for f in os.listdir(OUT_VID)]
|
151 |
+
return "✅ Videos cleared"
|
152 |
+
except Exception as e:
|
153 |
+
return f"❌ Failed to clear videos: {str(e)}"
|
154 |
+
|
155 |
+
# ---------------- Gallery helpers ------------------------
|
156 |
+
def list_images():
|
157 |
+
try:
|
158 |
+
return sorted(
|
159 |
+
[os.path.join(OUT_IMG,f) for f in os.listdir(OUT_IMG) if f.lower().endswith(('.png','.jpg'))],
|
160 |
+
key=os.path.getmtime
|
161 |
+
)
|
162 |
+
except Exception:
|
163 |
+
return []
|
164 |
+
|
165 |
+
def list_videos():
|
166 |
+
try:
|
167 |
+
return sorted(
|
168 |
+
[os.path.join(OUT_VID,f) for f in os.listdir(OUT_VID) if f.lower().endswith('.mp4')],
|
169 |
+
key=os.path.getmtime
|
170 |
+
)
|
171 |
+
except Exception:
|
172 |
+
return []
|
173 |
+
|
174 |
+
def list_loras():
|
175 |
+
try:
|
176 |
+
return sorted(
|
177 |
+
[os.path.join(LORA_CACHE,f) for f in os.listdir(LORA_CACHE) if f.lower().endswith('.safetensors')],
|
178 |
+
key=os.path.getmtime
|
179 |
+
)
|
180 |
+
except Exception:
|
181 |
+
return []
|
182 |
+
|
183 |
+
def load_image(sel):
|
184 |
+
try:
|
185 |
+
imgs = list_images()
|
186 |
+
if sel in [os.path.basename(p) for p in imgs]:
|
187 |
+
pth = imgs[[os.path.basename(p) for p in imgs].index(sel)]
|
188 |
+
return gr.update(value=pth), gr.update(value=os.path.basename(pth))
|
189 |
+
return gr.update(), gr.update()
|
190 |
+
except Exception as e:
|
191 |
+
return gr.update(), gr.update(value=f"❌ Error: {str(e)}")
|
192 |
+
|
193 |
+
def load_video(sel):
|
194 |
+
try:
|
195 |
+
vids = list_videos()
|
196 |
+
if sel in [os.path.basename(p) for p in vids]:
|
197 |
+
pth = vids[[os.path.basename(p) for p in vids].index(sel)]
|
198 |
+
return gr.update(value=pth), gr.update(value=os.path.basename(pth))
|
199 |
+
return gr.update(), gr.update()
|
200 |
+
except Exception as e:
|
201 |
+
return gr.update(), gr.update(value=f"❌ Error: {str(e)}")
|
202 |
+
|
203 |
+
def load_lora_select(sel):
|
204 |
+
try:
|
205 |
+
loras = list_loras()
|
206 |
+
if sel in [os.path.basename(p) for p in loras]:
|
207 |
+
pth = loras[[os.path.basename(p) for p in loras].index(sel)]
|
208 |
+
return gr.update(value=pth), gr.update(value=os.path.basename(pth))
|
209 |
+
return gr.update(), gr.update()
|
210 |
+
except Exception as e:
|
211 |
+
return gr.update(), gr.update(value=f"❌ Error: {str(e)}")
|
212 |
+
|
213 |
+
def next_image_and_load(sel):
|
214 |
+
try:
|
215 |
+
imgs = list_images()
|
216 |
+
if not imgs:
|
217 |
+
return gr.update(), gr.update()
|
218 |
+
names = [os.path.basename(i) for i in imgs]
|
219 |
+
idx = (names.index(sel)+1) % len(names) if sel in names else 0
|
220 |
+
pth = imgs[idx]
|
221 |
+
return gr.update(value=pth), gr.update(value=os.path.basename(pth))
|
222 |
+
except Exception:
|
223 |
+
return gr.update(), gr.update()
|
224 |
+
|
225 |
+
def next_video_and_load(sel):
|
226 |
+
try:
|
227 |
+
vids = list_videos()
|
228 |
+
if not vids:
|
229 |
+
return gr.update(), gr.update()
|
230 |
+
names = [os.path.basename(v) for v in vids]
|
231 |
+
idx = (names.index(sel)+1) % len(names) if sel in names else 0
|
232 |
+
pth = vids[idx]
|
233 |
+
return gr.update(value=pth), gr.update(value=os.path.basename(pth))
|
234 |
+
except Exception:
|
235 |
+
return gr.update(), gr.update()
|
236 |
+
|
237 |
+
def next_lora_and_load(sel):
|
238 |
+
try:
|
239 |
+
loras = list_loras()
|
240 |
+
if not loras:
|
241 |
+
return gr.update(), gr.update()
|
242 |
+
names = [os.path.basename(l) for l in loras]
|
243 |
+
idx = (names.index(sel)+1) % len(names) if sel in names else 0
|
244 |
+
pth = loras[idx]
|
245 |
+
return gr.update(value=pth), gr.update(value=os.path.basename(pth))
|
246 |
+
except Exception:
|
247 |
+
return gr.update(), gr.update()
|
248 |
+
|
249 |
+
def gallery_image_select(evt: gr.SelectData):
|
250 |
+
try:
|
251 |
+
imgs = list_images()
|
252 |
+
if evt.index is not None and evt.index < len(imgs):
|
253 |
+
pth = imgs[evt.index]
|
254 |
+
return gr.update(value=pth), gr.update(value=os.path.basename(pth))
|
255 |
+
return gr.update(), gr.update()
|
256 |
+
except Exception:
|
257 |
+
return gr.update(), gr.update()
|
258 |
+
|
259 |
+
def gallery_video_select(evt: gr.SelectData):
|
260 |
+
try:
|
261 |
+
vids = list_videos()
|
262 |
+
if evt.index is not None and evt.index < len(vids):
|
263 |
+
pth = vids[evt.index]
|
264 |
+
return gr.update(value=pth), gr.update(value=os.path.basename(pth))
|
265 |
+
return gr.update(), gr.update()
|
266 |
+
except Exception:
|
267 |
+
return gr.update(), gr.update()
|
268 |
+
|
269 |
+
def gallery_lora_select(evt: gr.SelectData):
|
270 |
+
try:
|
271 |
+
loras = list_loras()
|
272 |
+
if evt.index is not None and evt.index < len(loras):
|
273 |
+
pth = loras[evt.index]
|
274 |
+
return gr.update(value=pth), gr.update(value=os.path.basename(pth))
|
275 |
+
return gr.update(), gr.update()
|
276 |
+
except Exception:
|
277 |
+
return gr.update(), gr.update()
|
278 |
+
|
279 |
+
# ---------------- Install status -------------------------
|
280 |
+
def check_mod(n):
|
281 |
+
return importlib.util.find_spec(n) is not None
|
282 |
+
|
283 |
+
def status_xformers():
|
284 |
+
return "✅ xformers" if check_mod("xformers") else "❌ xformers"
|
285 |
+
|
286 |
+
def status_sage():
|
287 |
+
return "✅ sage-attn" if check_mod("sageattention") else "❌ sage-attn"
|
288 |
+
|
289 |
+
def status_flash():
|
290 |
+
return "✅ flash-attn" if check_mod("flash_attn") else "⚠️ flash-attn"
|
291 |
+
|
292 |
+
def install_pkg(pkg, warn=None):
|
293 |
+
try:
|
294 |
+
if warn:
|
295 |
+
print(warn)
|
296 |
+
time.sleep(1)
|
297 |
+
out = subprocess.check_output(
|
298 |
+
[sys.executable, "-m", "pip", "install", pkg],
|
299 |
+
stderr=subprocess.STDOUT, text=True
|
300 |
+
)
|
301 |
+
res = f"✅ {pkg}\n{out}\n"
|
302 |
+
except subprocess.CalledProcessError as e:
|
303 |
+
res = f"❌ {pkg}\n{e.output}\n"
|
304 |
+
with open(INSTALL_LOG, 'a') as f:
|
305 |
+
f.write(f"[{pkg}] {res}")
|
306 |
+
return res
|
307 |
+
|
308 |
+
install_xformers = lambda: install_pkg("xformers")
|
309 |
+
install_sage_attn = lambda: install_pkg("sage-attn")
|
310 |
+
install_flash_attn = lambda: install_pkg("flash-attn","⚠️ long compile")
|
311 |
+
refresh_logs = lambda: open(INSTALL_LOG).read()
|
312 |
+
clear_logs = lambda: (open(INSTALL_LOG,'w').close() or "✅ Logs cleared")
|
313 |
+
|
314 |
+
# ---------------- LoRA Download and Load ------------------
|
315 |
+
def download_lora(repo_id, filename, hf_token):
|
316 |
+
try:
|
317 |
+
lora_path = os.path.join(LORA_CACHE, filename)
|
318 |
+
if not os.path.exists(lora_path):
|
319 |
+
if get_cuda_free_memory_gb(gpu) < 2:
|
320 |
+
return "❌ Low VRAM (<2GB). Free up memory.", None
|
321 |
+
hf_hub_download(
|
322 |
+
repo_id=repo_id,
|
323 |
+
filename=filename,
|
324 |
+
local_dir=LORA_CACHE,
|
325 |
+
token=hf_token
|
326 |
+
)
|
327 |
+
with open(INSTALL_LOG, 'a') as f:
|
328 |
+
f.write(f"[LoRA Download] {repo_id}/{filename} downloaded to {lora_path}\n")
|
329 |
+
return "✅ LoRA downloaded", lora_path
|
330 |
+
except Exception as e:
|
331 |
+
with open(INSTALL_LOG, 'a') as f:
|
332 |
+
f.write(f"[LoRA Download Error] {repo_id}/{filename}: {str(e)}\n")
|
333 |
+
return f"❌ Download failed: {str(e)}", None
|
334 |
+
|
335 |
+
def load_lora(transformer, lora_path, lora_weight):
|
336 |
+
try:
|
337 |
+
if lora_path and os.path.exists(lora_path):
|
338 |
+
if hasattr(transformer, 'load_lora_weights'):
|
339 |
+
transformer.load_lora_weights(
|
340 |
+
lora_path,
|
341 |
+
adapter_name="fastvideo",
|
342 |
+
weight=lora_weight
|
343 |
+
)
|
344 |
+
with open(INSTALL_LOG, 'a') as f:
|
345 |
+
f.write(f"[LoRA Load] {lora_path} loaded with standard method, weight {lora_weight}\n")
|
346 |
+
return "✅ LoRA loaded"
|
347 |
+
else:
|
348 |
+
# Manual LoRA loading
|
349 |
+
lora_weights = load_file(lora_path)
|
350 |
+
state_dict = transformer.state_dict()
|
351 |
+
for key, value in lora_weights.items():
|
352 |
+
if key in state_dict:
|
353 |
+
state_dict[key] = state_dict[key] + lora_weight * value.to(state_dict[key].device)
|
354 |
+
else:
|
355 |
+
# Try partial key matching for common transformer layers
|
356 |
+
for model_key in state_dict:
|
357 |
+
if key.split('.')[-1] in model_key and ('self_attn' in model_key or 'ffn' in model_key):
|
358 |
+
state_dict[model_key] = state_dict[model_key] + lora_weight * value.to(state_dict[model_key].device)
|
359 |
+
break
|
360 |
+
else:
|
361 |
+
with open(INSTALL_LOG, 'a') as f:
|
362 |
+
f.write(f"[LoRA Load Warning] Key {key} not found in model state_dict\n")
|
363 |
+
transformer.load_state_dict(state_dict)
|
364 |
+
with open(INSTALL_LOG, 'a') as f:
|
365 |
+
f.write(f"[LoRA Load] {lora_path} loaded manually, weight {lora_weight}\n")
|
366 |
+
return "✅ LoRA loaded manually"
|
367 |
+
return "❌ No valid LoRA path"
|
368 |
+
except Exception as e:
|
369 |
+
with open(INSTALL_LOG, 'a') as f:
|
370 |
+
f.write(f"[LoRA Load Error] {lora_path}: {str(e)}\n")
|
371 |
+
return f"⚠️ LoRA not supported, using base model: {str(e)}"
|
372 |
+
|
373 |
+
def delete_lora(sel):
|
374 |
+
try:
|
375 |
+
loras = list_loras()
|
376 |
+
if sel in [os.path.basename(p) for p in loras]:
|
377 |
+
pth = loras[[os.path.basename(p) for p in loras].index(sel)]
|
378 |
+
os.remove(pth)
|
379 |
+
with open(INSTALL_LOG, 'a') as f:
|
380 |
+
f.write(f"[LoRA Delete] {pth} deleted\n")
|
381 |
+
return "✅ LoRA deleted", gr.update(choices=[os.path.basename(l) for l in list_loras()], value=None)
|
382 |
+
return "❌ No LoRA selected", gr.update()
|
383 |
+
except Exception as e:
|
384 |
+
return f"❌ Delete failed: {str(e)}", gr.update()
|
385 |
+
|
386 |
+
# ---------------- Model load -----------------------------
|
387 |
+
free_mem = get_cuda_free_memory_gb(gpu)
|
388 |
+
hv = free_mem > 60
|
389 |
+
|
390 |
+
try:
|
391 |
+
text_encoder = LlamaModel.from_pretrained(
|
392 |
+
"hunyuanvideo-community/HunyuanVideo",
|
393 |
+
subfolder='text_encoder', torch_dtype=torch.float16, token=HF_TOKEN
|
394 |
+
).cpu().eval()
|
395 |
+
except Exception as e:
|
396 |
+
with open(INSTALL_LOG, 'a') as f:
|
397 |
+
f.write(f"[Model Load Error] text_encoder: {str(e)}\n")
|
398 |
+
raise gr.Error(f"Failed to load text_encoder: {str(e)}")
|
399 |
+
|
400 |
+
try:
|
401 |
+
text_encoder_2 = CLIPTextModel.from_pretrained(
|
402 |
+
"hunyuanvideo-community/HunyuanVideo",
|
403 |
+
subfolder='text_encoder_2', torch_dtype=torch.float16, token=HF_TOKEN
|
404 |
+
).cpu().eval()
|
405 |
+
except Exception as e:
|
406 |
+
with open(INSTALL_LOG, 'a') as f:
|
407 |
+
f.write(f"[Model Load Error] text_encoder_2: {str(e)}\n")
|
408 |
+
raise gr.Error(f"Failed to load text_encoder_2: {str(e)}")
|
409 |
+
|
410 |
+
try:
|
411 |
+
tokenizer = LlamaTokenizerFast.from_pretrained(
|
412 |
+
"hunyuanvideo-community/HunyuanVideo",
|
413 |
+
subfolder='tokenizer', token=HF_TOKEN
|
414 |
+
)
|
415 |
+
except Exception as e:
|
416 |
+
with open(INSTALL_LOG, 'a') as f:
|
417 |
+
f.write(f"[Model Load Error] tokenizer: {str(e)}\n")
|
418 |
+
raise gr.Error(f"Failed to load tokenizer: {str(e)}")
|
419 |
+
|
420 |
+
try:
|
421 |
+
tokenizer_2 = CLIPTokenizer.from_pretrained(
|
422 |
+
"hunyuanvideo-community/HunyuanVideo",
|
423 |
+
subfolder='tokenizer_2', token=HF_TOKEN
|
424 |
+
)
|
425 |
+
except Exception as e:
|
426 |
+
with open(INSTALL_LOG, 'a') as f:
|
427 |
+
f.write(f"[Model Load Error] tokenizer_2: {str(e)}\n")
|
428 |
+
raise gr.Error(f"Failed to load tokenizer_2: {str(e)}")
|
429 |
+
|
430 |
+
try:
|
431 |
+
vae = AutoencoderKLHunyuanVideo.from_pretrained(
|
432 |
+
"hunyuanvideo-community/HunyuanVideo",
|
433 |
+
subfolder='vae', torch_dtype=torch.float16, token=HF_TOKEN
|
434 |
+
).cpu().eval()
|
435 |
+
except Exception as e:
|
436 |
+
with open(INSTALL_LOG, 'a') as f:
|
437 |
+
f.write(f"[Model Load Error] vae: {str(e)}\n")
|
438 |
+
raise gr.Error(f"Failed to load vae: {str(e)}")
|
439 |
+
|
440 |
+
try:
|
441 |
+
feature_extractor = SiglipImageProcessor.from_pretrained(
|
442 |
+
"lllyasviel/flux_redux_bfl", subfolder='feature_extractor', token=HF_TOKEN
|
443 |
+
)
|
444 |
+
except Exception as e:
|
445 |
+
with open(INSTALL_LOG, 'a') as f:
|
446 |
+
f.write(f"[Model Load Error] feature_extractor: {str(e)}\n")
|
447 |
+
raise gr.Error(f"Failed to load feature_extractor: {str(e)}")
|
448 |
+
|
449 |
+
try:
|
450 |
+
image_encoder = SiglipVisionModel.from_pretrained(
|
451 |
+
"lllyasviel/flux_redux_bfl",
|
452 |
+
subfolder='image_encoder', torch_dtype=torch.float16, token=HF_TOKEN
|
453 |
+
).cpu().eval()
|
454 |
+
except Exception as e:
|
455 |
+
with open(INSTALL_LOG, 'a') as f:
|
456 |
+
f.write(f"[Model Load Error] image_encoder: {str(e)}\n")
|
457 |
+
raise gr.Error(f"Failed to load image_encoder: {str(e)}")
|
458 |
+
|
459 |
+
try:
|
460 |
+
transformer = HunyuanVideoTransformer3DModelPacked.from_pretrained(
|
461 |
+
"lllyasviel/FramePack_F1_I2V_HY_20250503",
|
462 |
+
torch_dtype=torch.bfloat16, token=HF_TOKEN
|
463 |
+
).cpu().eval()
|
464 |
+
except Exception as e:
|
465 |
+
with open(INSTALL_LOG, 'a') as f:
|
466 |
+
f.write(f"[Model Load Error] transformer: {str(e)}\n")
|
467 |
+
raise gr.Error(f"Failed to load transformer: {str(e)}")
|
468 |
+
|
469 |
+
if not hv:
|
470 |
+
vae.enable_slicing()
|
471 |
+
vae.enable_tiling()
|
472 |
+
|
473 |
+
transformer.high_quality_fp32_output_for_inference = True
|
474 |
+
transformer.to(dtype=torch.bfloat16)
|
475 |
+
|
476 |
+
for m in (vae, image_encoder, text_encoder, text_encoder_2):
|
477 |
+
m.to(dtype=torch.float16)
|
478 |
+
for m in (vae, image_encoder, text_encoder, text_encoder_2, transformer):
|
479 |
+
m.requires_grad_(False)
|
480 |
+
|
481 |
+
if not hv:
|
482 |
+
DynamicSwapInstaller.install_model(transformer, device=gpu)
|
483 |
+
DynamicSwapInstaller.install_model(text_encoder, device=gpu)
|
484 |
+
else:
|
485 |
+
for m in (text_encoder, text_encoder_2, image_encoder, vae, transformer):
|
486 |
+
m.to(gpu)
|
487 |
+
|
488 |
+
stream = AsyncStream()
|
489 |
+
|
490 |
+
# ---------------- Worker -------------------------------
|
491 |
+
@torch.no_grad()
|
492 |
+
def worker(img, prompt, n_p, seed, secs, win, stp, cfg, gsc, rsc, keep, tea, crf, lora_path, lora_weight, disable_prompt_mods):
|
493 |
+
# Download and load LoRA if specified
|
494 |
+
lora_msg = "No LoRA specified"
|
495 |
+
if lora_path:
|
496 |
+
try:
|
497 |
+
if lora_path.startswith("http") or lora_path.startswith("Kijai/"):
|
498 |
+
repo_id = "Kijai/HunyuanVideo_comfy"
|
499 |
+
filename = "hyvideo_FastVideo_LoRA-fp8.safetensors"
|
500 |
+
lora_msg, lora_path = download_lora(repo_id, filename, HF_TOKEN)
|
501 |
+
if not lora_path:
|
502 |
+
raise gr.Error(lora_msg)
|
503 |
+
lora_msg = load_lora(transformer, lora_path, lora_weight)
|
504 |
+
if "⚠️" in lora_msg or "❌" in lora_msg:
|
505 |
+
print(lora_msg)
|
506 |
+
else:
|
507 |
+
stp = 8 # Override steps for FastVideo LoRA
|
508 |
+
except Exception as e:
|
509 |
+
with open(INSTALL_LOG, 'a') as f:
|
510 |
+
f.write(f"[LoRA Error] {lora_path}: {str(e)}\n")
|
511 |
+
lora_msg = f"⚠️ LoRA failed, using base model: {str(e)}"
|
512 |
+
|
513 |
+
# Validate prompt
|
514 |
+
try:
|
515 |
+
if not disable_prompt_mods:
|
516 |
+
if "stop" not in prompt.lower() and secs > 5:
|
517 |
+
prompt += " The subject stops moving after 5 seconds."
|
518 |
+
if "smooth" not in prompt.lower():
|
519 |
+
prompt = f"Smooth animation: {prompt}"
|
520 |
+
if "silent" not in prompt.lower():
|
521 |
+
prompt += ", silent"
|
522 |
+
if len(prompt.split()) > 50:
|
523 |
+
print("Warning: Complex prompt may slow rendering or cause instability.")
|
524 |
+
except Exception as e:
|
525 |
+
raise gr.Error(f"Prompt validation failed: {str(e)}")
|
526 |
+
|
527 |
+
# Check VRAM availability
|
528 |
+
if get_cuda_free_memory_gb(gpu) < 2:
|
529 |
+
raise gr.Error("Low VRAM (<2GB). Lower 'kee' or 'win'.")
|
530 |
+
|
531 |
+
sections = max(round((secs*30)/(win*4)), 1)
|
532 |
+
jid = generate_timestamp()
|
533 |
+
try:
|
534 |
+
with open(PROMPT_LOG, 'a') as f:
|
535 |
+
f.write(f"{jid}\t{prompt}\t{n_p}\n")
|
536 |
+
except Exception as e:
|
537 |
+
print(f"Failed to log prompt: {str(e)}")
|
538 |
+
|
539 |
+
stream.output_queue.push(('progress', (None, "", make_progress_bar_html(0, "Start"))))
|
540 |
+
try:
|
541 |
+
if not hv:
|
542 |
+
unload_complete_models(text_encoder, text_encoder_2, image_encoder, vae, transformer)
|
543 |
+
fake_diffusers_current_device(text_encoder, gpu)
|
544 |
+
load_model_as_complete(text_encoder_2, gpu)
|
545 |
+
lv, cp = encode_prompt_conds(prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
|
546 |
+
if cfg == 1:
|
547 |
+
lv_n = torch.zeros_like(lv)
|
548 |
+
cp_n = torch.zeros_like(cp)
|
549 |
+
else:
|
550 |
+
lv_n, cp_n = encode_prompt_conds(n_p, text_encoder, text_encoder_2, tokenizer, tokenizer_2)
|
551 |
+
lv, m = crop_or_pad_yield_mask(lv, 512)
|
552 |
+
lv_n, m_n = crop_or_pad_yield_mask(lv_n, 512)
|
553 |
+
lv, cp, lv_n, cp_n = [x.to(torch.bfloat16) for x in (lv, cp, lv_n, cp_n)]
|
554 |
+
H, W, _ = img.shape
|
555 |
+
h, w = find_nearest_bucket(H, W, 640)
|
556 |
+
img_np = resize_and_center_crop(img, w, h)
|
557 |
+
Image.fromarray(img_np).save(os.path.join(OUT_IMG, f"{jid}.png"))
|
558 |
+
img_pt = (torch.from_numpy(img_np).float()/127.5-1).permute(2,0,1)[None,:,None]
|
559 |
+
if not hv:
|
560 |
+
load_model_as_complete(vae, gpu)
|
561 |
+
start_lat = vae_encode(img_pt, vae)
|
562 |
+
if not hv:
|
563 |
+
load_model_as_complete(image_encoder, gpu)
|
564 |
+
img_emb = hf_clip_vision_encode(img_np, feature_extractor, image_encoder).last_hidden_state.to(torch.bfloat16)
|
565 |
+
gen = torch.Generator("cpu").manual_seed(seed)
|
566 |
+
hist_lat = torch.zeros((1,16,1+2+16,h//8,w//8), dtype=torch.float16).cpu()
|
567 |
+
hist_px = None
|
568 |
+
total = 0
|
569 |
+
pad_seq = [3] + [2]*(sections-3) + [1,0] if sections>4 else list(reversed(range(sections)))
|
570 |
+
for pad in pad_seq:
|
571 |
+
last = pad == 0
|
572 |
+
if stream.input_queue.top() == "end":
|
573 |
+
stream.output_queue.push(("end", None))
|
574 |
+
return
|
575 |
+
pad_sz = pad * win
|
576 |
+
idx = torch.arange(0, sum([1,pad_sz,win,1,2,16]))[None].to(device=gpu)
|
577 |
+
a,b,c,d,e,f = idx.split([1,pad_sz,win,1,2,16],1)
|
578 |
+
clean_idx = torch.cat([a,d],1)
|
579 |
+
pre = start_lat.to(hist_lat)
|
580 |
+
post, two, four = hist_lat[:,:,:1+2+16].split([1,2,16],2)
|
581 |
+
clean = torch.cat([pre, post],2)
|
582 |
+
if not hv:
|
583 |
+
unload_complete_models()
|
584 |
+
move_model_to_device_with_memory_preservation(transformer, gpu, keep)
|
585 |
+
transformer.initialize_teacache(tea, stp)
|
586 |
+
def cb(d):
|
587 |
+
pv = vae_decode_fake(d["denoised"])
|
588 |
+
pv = (pv*255).cpu().numpy().clip(0,255).astype(np.uint8)
|
589 |
+
pv = einops.rearrange(pv, "b c t h w -> (b h) (t w) c")
|
590 |
+
cur = d["i"]+1
|
591 |
+
stream.output_queue.push(('progress', (pv, f"{cur}/{stp}", make_progress_bar_html(int(100*cur/stp), f"{cur}/{stp}"))))
|
592 |
+
if stream.input_queue.top()=="end":
|
593 |
+
stream.output_queue.push(("end", None))
|
594 |
+
raise KeyboardInterrupt
|
595 |
+
new_lat = sample_hunyuan(
|
596 |
+
transformer=transformer, sampler="unipc", width=w, height=h, frames=win*4-3,
|
597 |
+
real_guidance_scale=cfg, distilled_guidance_scale=gsc, guidance_rescale=rsc,
|
598 |
+
num_inference_steps=stp, generator=gen,
|
599 |
+
prompt_embeds=lv, prompt_embeds_mask=m, prompt_poolers=cp,
|
600 |
+
negative_prompt_embeds=lv_n, negative_prompt_embeds_mask=m_n, negative_prompt_poolers=cp_n,
|
601 |
+
device=gpu, dtype=torch.bfloat16, image_embeddings=img_emb,
|
602 |
+
latent_indices=c, clean_latents=clean, clean_latent_indices=clean_idx,
|
603 |
+
clean_latents_2x=two, clean_latent_2x_indices=e,
|
604 |
+
clean_latents_4x=four, clean_latent_4x_indices=f, callback=cb
|
605 |
+
)
|
606 |
+
if last:
|
607 |
+
new_lat = torch.cat([start_lat.to(new_lat), new_lat],2)
|
608 |
+
total += new_lat.shape[2]
|
609 |
+
hist_lat = torch.cat([new_lat.to(hist_lat), hist_lat],2)
|
610 |
+
if not hv:
|
611 |
+
offload_model_from_device_for_memory_preservation(transformer, gpu, 8)
|
612 |
+
load_model_as_complete(vae, gpu)
|
613 |
+
real = hist_lat[:,:,:total]
|
614 |
+
if hist_px is None:
|
615 |
+
hist_px = vae_decode(real, vae).cpu()
|
616 |
+
else:
|
617 |
+
overlap = win*4-3
|
618 |
+
curr = vae_decode(real[:,:,:win*2], vae).cpu()
|
619 |
+
hist_px = soft_append_bcthw(curr, hist_px, overlap)
|
620 |
+
if not hv:
|
621 |
+
unload_complete_models()
|
622 |
+
tmp = os.path.join(OUT_TMP, f"{jid}_{total}.mp4")
|
623 |
+
save_bcthw_as_mp4(hist_px, tmp, fps=30, crf=crf)
|
624 |
+
stream.output_queue.push(('file', tmp))
|
625 |
+
if last:
|
626 |
+
fin = os.path.join(OUT_VID, f"{jid}_{total}.mp4")
|
627 |
+
os.replace(tmp, fin)
|
628 |
+
stream.output_queue.push(('complete', fin))
|
629 |
+
break
|
630 |
+
except Exception as e:
|
631 |
+
traceback.print_exc()
|
632 |
+
with open(INSTALL_LOG, 'a') as f:
|
633 |
+
f.write(f"[Worker Error] {str(e)}\n")
|
634 |
+
stream.output_queue.push(("end", None))
|
635 |
+
return lora_msg
|
636 |
+
|
637 |
+
# ---------------- Process Function -----------------------
|
638 |
+
@torch.no_grad()
|
639 |
+
def process(img, prm, npr, sd, sec, win, stp, cfg, gsc, rsc, kee, tea, crf, lora_path, lora_weight, disable_prompt_mods):
|
640 |
+
global stream
|
641 |
+
if img is None:
|
642 |
+
raise gr.Error("Upload an image")
|
643 |
+
yield None, None, "", "", gr.update(interactive=False), gr.update(interactive=True), gr.update()
|
644 |
+
stream = AsyncStream()
|
645 |
+
lora_msg = async_run(worker, img, prm, npr, sd, sec, win, stp, cfg, gsc, rsc, kee, tea, crf, lora_path, lora_weight, disable_prompt_mods)
|
646 |
+
out, log = None, ""
|
647 |
+
while True:
|
648 |
+
flag, data = stream.output_queue.next()
|
649 |
+
if flag == "file":
|
650 |
+
out = data
|
651 |
+
yield out, gr.update(), gr.update(), log, gr.update(interactive=False), gr.update(interactive=True), gr.update(value=lora_msg)
|
652 |
+
if flag == "progress":
|
653 |
+
pv, desc, html = data
|
654 |
+
log = desc
|
655 |
+
yield gr.update(), gr.update(visible=True, value=pv), desc, html, gr.update(interactive=False), gr.update(interactive=True), gr.update(value=lora_msg)
|
656 |
+
if flag in ("complete", "end"):
|
657 |
+
yield out, gr.update(visible=False), gr.update(), "", gr.update(interactive=True), gr.update(interactive=False), gr.update(value=lora_msg)
|
658 |
+
break
|
659 |
+
|
660 |
+
def end_process():
|
661 |
+
stream.input_queue.push("end")
|
662 |
+
|
663 |
+
# ------------------- UI ------------------------------
|
664 |
+
quick_prompts = [
|
665 |
+
["Smooth animation: A character waves for 3 seconds, then stands still for 2 seconds, static camera, silent."],
|
666 |
+
["Smooth animation: A character moves for 5 seconds, static camera, silent."]
|
667 |
+
]
|
668 |
+
css = make_progress_bar_css() + """
|
669 |
+
.orange-button{background:#ff6200;color:#fff;border-color:#ff6200;}
|
670 |
+
.load-button{background:#4CAF50;color:#fff;border-color:#4CAF50;margin-left:10px;}
|
671 |
+
.big-setting-button{background:#0066cc;color:#fff;border:none;padding:14px 24px;font-size:18px;width:100%;border-radius:6px;margin:8px 0;}
|
672 |
+
.styled-dropdown{width:250px;padding:5px;border-radius:4px;}
|
673 |
+
.viewer-column{width:100%;max-width:900px;margin:0 auto;}
|
674 |
+
.media-preview img,.media-preview video{max-width:100%;height:380px;object-fit:contain;border:1px solid #444;border-radius:6px;}
|
675 |
+
.media-container{display:flex;gap:20px;align-items:flex-start;}
|
676 |
+
.control-box{min-width:220px;}
|
677 |
+
.control-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px;}
|
678 |
+
.image-gallery{display:grid!important;grid-template-columns:repeat(auto-fit,minmax(300px,1fr))!important;gap:10px;padding:10px!important;overflow-y:auto!important;max-height:360px!important;}
|
679 |
+
.image-gallery .gallery-item{padding:10px;height:360px!important;width:300px!important;}
|
680 |
+
.image-gallery img{object-fit:contain;height:360px!important;width:300px!important;}
|
681 |
+
.video-gallery{display:grid!important;grid-template-columns:repeat(auto-fit,minmax(300px,1fr))!important;gap:10px;padding:10px!important;overflow-y:auto!important;max-height:360px!important;}
|
682 |
+
.video-gallery .gallery-item{padding:10px;height:360px!important;width:300px!important;}
|
683 |
+
.video-gallery video{object-fit:contain;height:360px!important;width:300px!important;}
|
684 |
+
.lora-gallery{display:grid!important;grid-template-columns:repeat(auto-fit,minmax(300px,1fr))!important;gap:10px;padding:10px!important;overflow-y:auto!important;max-height:360px!important;}
|
685 |
+
.lora-gallery .gallery-item{padding:10px;height:360px!important;width:300px!important;}
|
686 |
+
.lora-gallery .gallery-item div{text-align:center;font-size:16px;color:#fff;}
|
687 |
+
"""
|
688 |
+
|
689 |
+
blk = gr.Blocks(css=css).queue()
|
690 |
+
with blk:
|
691 |
+
gr.Markdown("# 👻 GhostPack F1 Pro")
|
692 |
+
with gr.Tabs():
|
693 |
+
|
694 |
+
with gr.TabItem("👻 Generate"):
|
695 |
+
with gr.Row():
|
696 |
+
with gr.Column():
|
697 |
+
img_in = gr.Image(sources="upload", type="numpy", label="Image", height=320)
|
698 |
+
prm = gr.Textbox(label="Prompt")
|
699 |
+
npr = gr.Textbox(label="Negative Prompt", value="low quality, blurry, speaking, talking, moaning, vocalizing, lip movement, mouth animation, sound, dialogue, speech, whispering, shouting, lip sync, facial animation, expressive face, verbal expression, animated mouth")
|
700 |
+
save_msg = gr.Markdown("")
|
701 |
+
lora_path = gr.Textbox(
|
702 |
+
label="FastVideo LoRA Path or HF Repo",
|
703 |
+
value="Kijai/HunyuanVideo_comfy",
|
704 |
+
placeholder="e.g., Kijai/HunyuanVideo_comfy/hyvideo_FastVideo_LoRA-fp8.safetensors or /path/to/hyvideo_FastVideo_LoRA-fp8.safetensors"
|
705 |
+
)
|
706 |
+
lora_weight = gr.Slider(label="LoRA Weight", minimum=0.5, maximum=1.5, value=1.0, step=0.1)
|
707 |
+
disable_prompt_mods = gr.Checkbox(label="Disable Prompt Modifications", value=False)
|
708 |
+
lora_status_gen = gr.Markdown(value=auto_download_status)
|
709 |
+
btn_save = gr.Button("Save Prompt")
|
710 |
+
btn1, btn2, btn3 = gr.Button("Load Most Recent"), gr.Button("Load 2nd Recent"), gr.Button("Load 3rd Recent")
|
711 |
+
ds = gr.Dataset(samples=quick_prompts, label="Quick List", components=[prm])
|
712 |
+
ds.click(lambda x: x[0], [ds], [prm])
|
713 |
+
btn_save.click(save_prompt_fn, [prm, npr], [save_msg])
|
714 |
+
btn1.click(lambda: load_prompt_fn(0), [], [prm])
|
715 |
+
btn2.click(lambda: load_prompt_fn(1), [], [prm])
|
716 |
+
btn3.click(lambda: load_prompt_fn(2), [], [prm])
|
717 |
+
with gr.Row():
|
718 |
+
b_go, b_end = gr.Button("Start"), gr.Button("End", interactive=False)
|
719 |
+
with gr.Group():
|
720 |
+
tea = gr.Checkbox(label="Use TeaCache", value=True)
|
721 |
+
se = gr.Number(label="Seed", value=31337, precision=0)
|
722 |
+
sec = gr.Slider(label="Video Length (s)", minimum=1, maximum=120, value=5, step=0.1)
|
723 |
+
win = gr.Slider(label="Latent Window", minimum=1, maximum=33, value=5, step=1)
|
724 |
+
stp = gr.Slider(label="Steps", minimum=1, maximum=100, value=8, step=1)
|
725 |
+
cfg = gr.Slider(label="CFG", minimum=1, maximum=32, value=1, step=0.01, visible=False)
|
726 |
+
gsc = gr.Slider(label="Distilled CFG", minimum=1, maximum=32, value=5, step=0.01)
|
727 |
+
rsc = gr.Slider(label="CFG Re-Scale", minimum=0, maximum=1, value=0.5, step=0.01)
|
728 |
+
kee = gr.Slider(label="GPU Keep (GB)", minimum=4, maximum=free_mem, value=6, step=0.1)
|
729 |
+
crf = gr.Slider(label="MP4 CRF", minimum=0, maximum=100, value=20, step=1)
|
730 |
+
with gr.Column():
|
731 |
+
pv = gr.Image(label="Next Latents", height=200, visible=False)
|
732 |
+
vid = gr.Video(label="Finished", autoplay=True, height=500, loop=True, show_share_button=False)
|
733 |
+
log_md = gr.Markdown("")
|
734 |
+
bar = gr.HTML("")
|
735 |
+
b_go.click(
|
736 |
+
process,
|
737 |
+
[img_in, prm, npr, se, sec, win, stp, cfg, gsc, rsc, kee, tea, crf, lora_path, lora_weight, disable_prompt_mods],
|
738 |
+
[vid, pv, log_md, bar, b_go, b_end, lora_status_gen]
|
739 |
+
)
|
740 |
+
b_end.click(end_process)
|
741 |
+
|
742 |
+
with gr.TabItem("🖼️ Image Gallery"):
|
743 |
+
with gr.Row(elem_classes="media-container"):
|
744 |
+
with gr.Column(scale=3):
|
745 |
+
image_preview = gr.Image(
|
746 |
+
label="Viewer",
|
747 |
+
value=(list_images()[0] if list_images() else None),
|
748 |
+
interactive=False, elem_classes="media-preview"
|
749 |
+
)
|
750 |
+
with gr.Column(elem_classes="control-box"):
|
751 |
+
image_dropdown = gr.Dropdown(
|
752 |
+
choices=[os.path.basename(i) for i in list_images()],
|
753 |
+
value=(os.path.basename(list_images()[0]) if list_images() else None),
|
754 |
+
label="Select", elem_classes="styled-dropdown"
|
755 |
+
)
|
756 |
+
with gr.Row(elem_classes="control-grid"):
|
757 |
+
load_btn = gr.Button("Load", elem_classes="load-button")
|
758 |
+
next_btn = gr.Button("Next", elem_classes="load-button")
|
759 |
+
with gr.Row(elem_classes="control-grid"):
|
760 |
+
refresh_btn = gr.Button("Refresh")
|
761 |
+
delete_btn = gr.Button("Delete", elem_classes="orange-button")
|
762 |
+
image_gallery = gr.Gallery(
|
763 |
+
value=list_images(), label="Thumbnails", columns=6, height=360,
|
764 |
+
allow_preview=False, type="filepath", elem_classes="image-gallery"
|
765 |
+
)
|
766 |
+
load_btn.click(load_image, [image_dropdown], [image_preview, image_dropdown])
|
767 |
+
next_btn.click(next_image_and_load, [image_dropdown], [image_preview, image_dropdown])
|
768 |
+
refresh_btn.click(lambda: (
|
769 |
+
gr.update(choices=[os.path.basename(i) for i in list_images()],
|
770 |
+
value=os.path.basename(list_images()[0]) if list_images() else None),
|
771 |
+
gr.update(value=list_images()[0] if list_images() else None),
|
772 |
+
gr.update(value=list_images())
|
773 |
+
), [], [image_dropdown, image_preview, image_gallery])
|
774 |
+
delete_btn.click(lambda sel: (os.remove(os.path.join(OUT_IMG, sel)) if sel else None) or load_image(""),
|
775 |
+
[image_dropdown], [image_preview, image_dropdown])
|
776 |
+
image_gallery.select(gallery_image_select, [], [image_preview, image_dropdown])
|
777 |
+
|
778 |
+
with gr.TabItem("🎬 Video Gallery"):
|
779 |
+
with gr.Row(elem_classes="media-container"):
|
780 |
+
with gr.Column(scale=3):
|
781 |
+
video_preview = gr.Video(
|
782 |
+
label="Viewer",
|
783 |
+
value=(list_videos()[0] if list_videos() else None),
|
784 |
+
autoplay=True, loop=True, interactive=False, elem_classes="media-preview"
|
785 |
+
)
|
786 |
+
with gr.Column(elem_classes="control-box"):
|
787 |
+
video_dropdown = gr.Dropdown(
|
788 |
+
choices=[os.path.basename(v) for v in list_videos()],
|
789 |
+
value=(os.path.basename(list_videos()[0]) if list_videos() else None),
|
790 |
+
label="Select", elem_classes="styled-dropdown"
|
791 |
+
)
|
792 |
+
with gr.Row(elem_classes="control-grid"):
|
793 |
+
load_vbtn = gr.Button("Load", elem_classes="load-button")
|
794 |
+
next_vbtn = gr.Button("Next", elem_classes="load-button")
|
795 |
+
with gr.Row(elem_classes="control-grid"):
|
796 |
+
refresh_v = gr.Button("Refresh")
|
797 |
+
delete_v = gr.Button("Delete", elem_classes="orange-button")
|
798 |
+
video_gallery = gr.Gallery(
|
799 |
+
value=list_videos(), label="Thumbnails", columns=6, height=360,
|
800 |
+
allow_preview=False, type="filepath", elem_classes="video-gallery"
|
801 |
+
)
|
802 |
+
load_vbtn.click(load_video, [video_dropdown], [video_preview, video_dropdown])
|
803 |
+
next_vbtn.click(next_video_and_load, [video_dropdown], [video_preview, video_dropdown])
|
804 |
+
refresh_v.click(lambda: (
|
805 |
+
gr.update(choices=[os.path.basename(v) for v in list_videos()],
|
806 |
+
value=os.path.basename(list_videos()[0]) if list_videos() else None),
|
807 |
+
gr.update(value=list_videos()[0] if list_videos() else None),
|
808 |
+
gr.update(value=list_videos())
|
809 |
+
), [], [video_dropdown, video_preview, video_gallery])
|
810 |
+
delete_v.click(lambda sel: (os.remove(os.path.join(OUT_VID, sel)) if sel else None) or load_video(""),
|
811 |
+
[video_dropdown], [video_preview, video_dropdown])
|
812 |
+
video_gallery.select(gallery_video_select, [], [video_preview, video_dropdown])
|
813 |
+
|
814 |
+
with gr.TabItem("📦 LoRA Management"):
|
815 |
+
with gr.Row(elem_classes="media-container"):
|
816 |
+
with gr.Column(scale=3):
|
817 |
+
lora_status = gr.Markdown("")
|
818 |
+
with gr.Column(elem_classes="control-box"):
|
819 |
+
lora_dropdown = gr.Dropdown(
|
820 |
+
choices=[os.path.basename(l) for l in list_loras()],
|
821 |
+
value=(os.path.basename(list_loras()[0]) if list_loras() else None),
|
822 |
+
label="Select LoRA", elem_classes="styled-dropdown"
|
823 |
+
)
|
824 |
+
with gr.Row(elem_classes="control-grid"):
|
825 |
+
load_lora_btn = gr.Button("Load", elem_classes="load-button")
|
826 |
+
next_lora_btn = gr.Button("Next", elem_classes="load-button")
|
827 |
+
with gr.Row(elem_classes="control-grid"):
|
828 |
+
refresh_lora_btn = gr.Button("Refresh")
|
829 |
+
delete_lora_btn = gr.Button("Delete", elem_classes="orange-button")
|
830 |
+
download_fastvideo_btn = gr.Button("Download FastVideo LoRA", elem_classes="big-setting-button")
|
831 |
+
lora_gallery = gr.Gallery(
|
832 |
+
value=[(l, os.path.basename(l)) for l in list_loras()], label="LoRA Files", columns=6, height=360,
|
833 |
+
allow_preview=False, elem_classes="lora-gallery"
|
834 |
+
)
|
835 |
+
load_lora_btn.click(load_lora_select, [lora_dropdown], [lora_path, lora_dropdown])
|
836 |
+
next_lora_btn.click(next_lora_and_load, [lora_dropdown], [lora_path, lora_dropdown])
|
837 |
+
refresh_lora_btn.click(lambda: (
|
838 |
+
gr.update(choices=[os.path.basename(l) for l in list_loras()],
|
839 |
+
value=os.path.basename(list_loras()[0]) if list_loras() else None),
|
840 |
+
gr.update(value=[(l, os.path.basename(l)) for l in list_loras()])
|
841 |
+
), [], [lora_dropdown, lora_gallery])
|
842 |
+
delete_lora_btn.click(delete_lora, [lora_dropdown], [lora_status, lora_dropdown])
|
843 |
+
download_fastvideo_btn.click(
|
844 |
+
lambda: auto_download_fastvideo_lora(),
|
845 |
+
[], [lora_status]
|
846 |
+
)
|
847 |
+
lora_gallery.select(gallery_lora_select, [], [lora_path, lora_dropdown])
|
848 |
+
|
849 |
+
with gr.TabItem("👻 About"):
|
850 |
+
gr.Markdown("## GhostPack F1 Pro")
|
851 |
+
with gr.Row():
|
852 |
+
with gr.Column():
|
853 |
+
gr.Markdown("**🛠️ Description**\nImage-to-Video toolkit powered by HunyuanVideo & FramePack-F1")
|
854 |
+
with gr.Column():
|
855 |
+
gr.Markdown("**📦 Version**\n2025-05-03")
|
856 |
+
with gr.Column():
|
857 |
+
gr.Markdown("**✍️ Author**\nGhostAI")
|
858 |
+
with gr.Column():
|
859 |
+
gr.Markdown("**🔗 Repo**\nhttps://huggingface.co/spaces/ghostai1/GhostPack")
|
860 |
+
|
861 |
+
with gr.TabItem("⚙️ Settings"):
|
862 |
+
ct = gr.Button("Clear Temp", elem_classes="big-setting-button")
|
863 |
+
ctmsg = gr.Markdown("")
|
864 |
+
co = gr.Button("Clear Old", elem_classes="big-setting-button")
|
865 |
+
comsg= gr.Markdown("")
|
866 |
+
ci = gr.Button("Clear Images", elem_classes="big-setting-button")
|
867 |
+
cimg= gr.Markdown("")
|
868 |
+
cv = gr.Button("Clear Videos", elem_classes="big-setting-button")
|
869 |
+
cvid= gr.Markdown("")
|
870 |
+
ct.click(clear_temp_videos, [], ctmsg)
|
871 |
+
co.click(clear_old_files, [], comsg)
|
872 |
+
ci.click(clear_images, [], cimg)
|
873 |
+
cv.click(clear_videos, [], cvid)
|
874 |
+
|
875 |
+
with gr.TabItem("🛠️ Install"):
|
876 |
+
xs = gr.Textbox(value=status_xformers(), interactive=False, label="xformers")
|
877 |
+
bx = gr.Button("Install xformers", elem_classes="big-setting-button")
|
878 |
+
ss = gr.Textbox(value=status_sage(), interactive=False, label="sage-attn")
|
879 |
+
bs = gr.Button("Install sage-attn", elem_classes="big-setting-button")
|
880 |
+
fs = gr.Textbox(value=status_flash(),interactive=False, label="flash-attn")
|
881 |
+
bf = gr.Button("Install flash-attn", elem_classes="big-setting-button")
|
882 |
+
bx.click(install_xformers, [], xs)
|
883 |
+
bs.click(install_sage_attn, [], ss)
|
884 |
+
bf.click(install_flash_attn, [], fs)
|
885 |
+
|
886 |
+
with gr.TabItem("📜 Logs"):
|
887 |
+
logs = gr.Textbox(lines=20, interactive=False, label="Install Logs")
|
888 |
+
rl = gr.Button("Refresh", elem_classes="big-setting-button")
|
889 |
+
cl = gr.Button("Clear", elem_classes="big-setting-button")
|
890 |
+
rl.click(refresh_logs, [], logs)
|
891 |
+
cl.click(clear_logs, [], logs)
|
892 |
+
|
893 |
+
# Force video previews to seek to 2s
|
894 |
+
gr.HTML("""<script>
|
895 |
+
document.querySelectorAll('.video-gallery video').forEach(v => {
|
896 |
+
v.addEventListener('loadedmetadata', () => {
|
897 |
+
if (v.duration > 2) v.currentTime = 2;
|
898 |
+
});
|
899 |
+
});
|
900 |
+
</script>""")
|
901 |
+
|
902 |
+
blk.launch(
|
903 |
+
server_name=args.server,
|
904 |
+
server_port=args.port,
|
905 |
+
share=args.share,
|
906 |
+
inbrowser=args.inbrowser
|
907 |
+
)
|