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