Spaces:
Running on Zero
Running on Zero
Upload 3 files
Browse files- app.py +31 -19
- prompt_assistant.py +113 -0
- requirements.txt +3 -0
app.py
CHANGED
|
@@ -21,6 +21,7 @@ from torch.nn import functional as F
|
|
| 21 |
from PIL import Image, ImageDraw, ImageFilter
|
| 22 |
|
| 23 |
import gradio as gr
|
|
|
|
| 24 |
|
| 25 |
# Bounded runtime diagnostics: no prompts, photo paths, credentials or LoRA URLs.
|
| 26 |
import atexit
|
|
@@ -2653,7 +2654,7 @@ SETTINGS_KEYS += [
|
|
| 2653 |
"sound_steps", "sound_guidance",
|
| 2654 |
]
|
| 2655 |
SETTINGS_KEYS += ["chain_count", "scene_prompts", "scene_idea", "scene_auto_count",
|
| 2656 |
-
"scene_seconds", "scene_auto_seconds"]
|
| 2657 |
|
| 2658 |
# The per-repo file dropdowns are populated only after a repo has been read, so a restored value
|
| 2659 |
# would not be among the choices. These keys get their choice list rebuilt around the stored value.
|
|
@@ -2739,6 +2740,8 @@ def export_settings(*values):
|
|
| 2739 |
# renamed label makes every saved profile refuse to load.
|
| 2740 |
def _settle_choice(key, value):
|
| 2741 |
"""Bend a stored value back onto the current list of choices, or drop it."""
|
|
|
|
|
|
|
| 2742 |
if key == "chain_count":
|
| 2743 |
try:
|
| 2744 |
return _scene_count(value)
|
|
@@ -2783,7 +2786,8 @@ def _settle_choice(key, value):
|
|
| 2783 |
def _restore_updates(payload):
|
| 2784 |
"""Turn a saved profile into component updates, skipping anything that no longer fits."""
|
| 2785 |
scene_defaults = {"chain_count": 3, "scene_prompts": "", "scene_idea": "",
|
| 2786 |
-
"scene_auto_count": True, "scene_seconds": "", "scene_auto_seconds": True
|
|
|
|
| 2787 |
updates = []
|
| 2788 |
for key in SETTINGS_KEYS:
|
| 2789 |
value = payload.get(key, scene_defaults.get(key))
|
|
@@ -4263,6 +4267,8 @@ def _remote_plan(client, payload, message, max_new_tokens=None):
|
|
| 4263 |
|
| 4264 |
def rank(name):
|
| 4265 |
low = name.lower()
|
|
|
|
|
|
|
| 4266 |
if "chat" in low:
|
| 4267 |
return 0
|
| 4268 |
if any(word in low for word in ("respond", "submit", "predict", "run", "generate")):
|
|
@@ -4298,6 +4304,8 @@ def _remote_ask(space_id, message, image=None, temperature=0.7, max_new_tokens=N
|
|
| 4298 |
"""One submitted AI job per call. Never replay a timed-out/failed paid request."""
|
| 4299 |
from gradio_client import handle_file
|
| 4300 |
from concurrent.futures import TimeoutError as FutureTimeout
|
|
|
|
|
|
|
| 4301 |
client = _REMOTE_CLIENTS.get(space_id)
|
| 4302 |
if client is None:
|
| 4303 |
client = _make_remote_client(space_id)
|
|
@@ -4316,13 +4324,20 @@ def _remote_ask(space_id, message, image=None, temperature=0.7, max_new_tokens=N
|
|
| 4316 |
picture.save(temporary_image, format="PNG")
|
| 4317 |
files.append(handle_file(temporary_image))
|
| 4318 |
payload = {"text": message, "files": files}
|
| 4319 |
-
|
| 4320 |
-
|
| 4321 |
-
|
| 4322 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4323 |
_runtime_event("remote_ai_submit", authenticated=bool(os.environ.get("EXPANDER_HF_TOKEN")))
|
| 4324 |
job = client.submit(*args, **kwargs)
|
| 4325 |
-
|
|
|
|
|
|
|
| 4326 |
_runtime_event("remote_ai_complete")
|
| 4327 |
return reply
|
| 4328 |
except FutureTimeout as error:
|
|
@@ -5362,7 +5377,7 @@ def plan_scene(idea, main_prompt, automatic, clip_count, seconds, space_id, imag
|
|
| 5362 |
raise gr.Error("Please shorten the scene idea to 16,000 characters.")
|
| 5363 |
space = str(space_id or "").strip()
|
| 5364 |
if not space:
|
| 5365 |
-
raise gr.Error("
|
| 5366 |
try:
|
| 5367 |
target = MAX_SCENE_CLIPS if automatic else _scene_count(clip_count)
|
| 5368 |
duration = _scene_duration(seconds)
|
|
@@ -7244,6 +7259,12 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
|
|
| 7244 |
placeholder="Describe the motion you want to see…",
|
| 7245 |
)
|
| 7246 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7247 |
with gr.Group(elem_classes="panel", visible=True) as basic_panel:
|
| 7248 |
gr.Markdown(
|
| 7249 |
"**Picture in, a few words above, one press.** The prompt is "
|
|
@@ -7295,15 +7316,6 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
|
|
| 7295 |
pb_use_model = gr.Checkbox(
|
| 7296 |
value=False, label="🧠 Write it with a model (first press downloads 8 GB, then ~20 s)",
|
| 7297 |
)
|
| 7298 |
-
pb_space = gr.Textbox(
|
| 7299 |
-
value=REMOTE_SPACE, label="🛰️ Big model Space (optional)",
|
| 7300 |
-
placeholder="owner/space-name",
|
| 7301 |
-
info="Already pointed at amisima/Qwen3.8-27B-Uncensored-Demo. That "
|
| 7302 |
-
"Space is shown your photo, writes the prompt from it and sets "
|
| 7303 |
-
"the effect strengths in the same message - one booking there, "
|
| 7304 |
-
"both answers. Put another owner/space-name in to borrow a "
|
| 7305 |
-
"different one, or empty it to use only the small model above.",
|
| 7306 |
-
)
|
| 7307 |
with gr.Row():
|
| 7308 |
pb_button = gr.Button("🖋️ Build / rewrite the prompt", variant="secondary",
|
| 7309 |
elem_id="enhance-btn")
|
|
@@ -7703,7 +7715,7 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
|
|
| 7703 |
placeholder="Describe how the scene should continue…")
|
| 7704 |
gr.Markdown("**Qwen3.8 prompt & LoRA assistant** · Uses this video's last frame and your next action. "
|
| 7705 |
"Selections and strengths are shared with the main prompt and Scene Builder. "
|
| 7706 |
-
"
|
| 7707 |
extension_context_image = gr.State(None)
|
| 7708 |
extension_prepare_btn = gr.Button("✨ Qwen3.8 · Prepare prompt, LoRAs & strengths", variant="secondary")
|
| 7709 |
extension_pick_status = gr.HTML("<div class='status-idle'>Prepare the continuation, or refresh to browse LoRAs.</div>")
|
|
@@ -8540,7 +8552,7 @@ with gr.Blocks(title="Wan 2.2 Studio | NEW AI Scene Planner · 64 Clips · 3 Aud
|
|
| 8540 |
aspect_mode, sound_auto, sound_engine, sound_prompt, sound_negative,
|
| 8541 |
sound_steps, sound_guidance,
|
| 8542 |
chain_count, scene_prompts, scene_idea, scene_auto_count,
|
| 8543 |
-
scene_seconds, scene_auto_seconds,
|
| 8544 |
]
|
| 8545 |
|
| 8546 |
profile_save_btn.click(
|
|
|
|
| 21 |
from PIL import Image, ImageDraw, ImageFilter
|
| 22 |
|
| 23 |
import gradio as gr
|
| 24 |
+
from prompt_assistant import assistant_choices, is_fable, prepare_request, writer_result
|
| 25 |
|
| 26 |
# Bounded runtime diagnostics: no prompts, photo paths, credentials or LoRA URLs.
|
| 27 |
import atexit
|
|
|
|
| 2654 |
"sound_steps", "sound_guidance",
|
| 2655 |
]
|
| 2656 |
SETTINGS_KEYS += ["chain_count", "scene_prompts", "scene_idea", "scene_auto_count",
|
| 2657 |
+
"scene_seconds", "scene_auto_seconds", "prompt_assistant_writer"]
|
| 2658 |
|
| 2659 |
# The per-repo file dropdowns are populated only after a repo has been read, so a restored value
|
| 2660 |
# would not be among the choices. These keys get their choice list rebuilt around the stored value.
|
|
|
|
| 2740 |
# renamed label makes every saved profile refuse to load.
|
| 2741 |
def _settle_choice(key, value):
|
| 2742 |
"""Bend a stored value back onto the current list of choices, or drop it."""
|
| 2743 |
+
if key == "prompt_assistant_writer":
|
| 2744 |
+
return str(value).strip() if isinstance(value, str) and value.strip() else REMOTE_SPACE
|
| 2745 |
if key == "chain_count":
|
| 2746 |
try:
|
| 2747 |
return _scene_count(value)
|
|
|
|
| 2786 |
def _restore_updates(payload):
|
| 2787 |
"""Turn a saved profile into component updates, skipping anything that no longer fits."""
|
| 2788 |
scene_defaults = {"chain_count": 3, "scene_prompts": "", "scene_idea": "",
|
| 2789 |
+
"scene_auto_count": True, "scene_seconds": "", "scene_auto_seconds": True,
|
| 2790 |
+
"prompt_assistant_writer": REMOTE_SPACE}
|
| 2791 |
updates = []
|
| 2792 |
for key in SETTINGS_KEYS:
|
| 2793 |
value = payload.get(key, scene_defaults.get(key))
|
|
|
|
| 4267 |
|
| 4268 |
def rank(name):
|
| 4269 |
low = name.lower()
|
| 4270 |
+
if "write_prompt" in low:
|
| 4271 |
+
return -1
|
| 4272 |
if "chat" in low:
|
| 4273 |
return 0
|
| 4274 |
if any(word in low for word in ("respond", "submit", "predict", "run", "generate")):
|
|
|
|
| 4304 |
"""One submitted AI job per call. Never replay a timed-out/failed paid request."""
|
| 4305 |
from gradio_client import handle_file
|
| 4306 |
from concurrent.futures import TimeoutError as FutureTimeout
|
| 4307 |
+
selected_writer = str(space_id or "").strip()
|
| 4308 |
+
space_id, message, image = prepare_request(selected_writer, message, image)
|
| 4309 |
client = _REMOTE_CLIENTS.get(space_id)
|
| 4310 |
if client is None:
|
| 4311 |
client = _make_remote_client(space_id)
|
|
|
|
| 4324 |
picture.save(temporary_image, format="PNG")
|
| 4325 |
files.append(handle_file(temporary_image))
|
| 4326 |
payload = {"text": message, "files": files}
|
| 4327 |
+
if is_fable(selected_writer):
|
| 4328 |
+
args = ()
|
| 4329 |
+
kwargs = {"message": payload, "max_new_tokens": int(max_new_tokens or 768),
|
| 4330 |
+
"temperature": float(temperature), "api_name": "/write_prompt"}
|
| 4331 |
+
else:
|
| 4332 |
+
plan, _ = _remote_plan(client, payload, message, max_new_tokens=int(max_new_tokens or 768))
|
| 4333 |
+
if not plan:
|
| 4334 |
+
raise RuntimeError("The writing Space did not expose a usable API. No AI job was submitted.")
|
| 4335 |
+
args, kwargs = plan[0]
|
| 4336 |
_runtime_event("remote_ai_submit", authenticated=bool(os.environ.get("EXPANDER_HF_TOKEN")))
|
| 4337 |
job = client.submit(*args, **kwargs)
|
| 4338 |
+
wait_seconds = max(300, 120 + int(max_new_tokens or 768) / 5) if is_fable(selected_writer) else 300
|
| 4339 |
+
response = job.result(timeout=wait_seconds)
|
| 4340 |
+
reply = writer_result(response)
|
| 4341 |
_runtime_event("remote_ai_complete")
|
| 4342 |
return reply
|
| 4343 |
except FutureTimeout as error:
|
|
|
|
| 5377 |
raise gr.Error("Please shorten the scene idea to 16,000 characters.")
|
| 5378 |
space = str(space_id or "").strip()
|
| 5379 |
if not space:
|
| 5380 |
+
raise gr.Error("Select a Prompt assistant model to use AI Scene Planner.")
|
| 5381 |
try:
|
| 5382 |
target = MAX_SCENE_CLIPS if automatic else _scene_count(clip_count)
|
| 5383 |
duration = _scene_duration(seconds)
|
|
|
|
| 7259 |
placeholder="Describe the motion you want to see…",
|
| 7260 |
)
|
| 7261 |
|
| 7262 |
+
pb_space = gr.Dropdown(
|
| 7263 |
+
choices=assistant_choices(REMOTE_SPACE), value=REMOTE_SPACE,
|
| 7264 |
+
allow_custom_value=True, label="Prompt assistant model",
|
| 7265 |
+
info="Both Qwen options can read your image. This choice is shared by prompt preparation, "
|
| 7266 |
+
"LoRA suggestions, scenes and Extend. You can also enter owner/space-name.",
|
| 7267 |
+
)
|
| 7268 |
with gr.Group(elem_classes="panel", visible=True) as basic_panel:
|
| 7269 |
gr.Markdown(
|
| 7270 |
"**Picture in, a few words above, one press.** The prompt is "
|
|
|
|
| 7316 |
pb_use_model = gr.Checkbox(
|
| 7317 |
value=False, label="🧠 Write it with a model (first press downloads 8 GB, then ~20 s)",
|
| 7318 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7319 |
with gr.Row():
|
| 7320 |
pb_button = gr.Button("🖋️ Build / rewrite the prompt", variant="secondary",
|
| 7321 |
elem_id="enhance-btn")
|
|
|
|
| 7715 |
placeholder="Describe how the scene should continue…")
|
| 7716 |
gr.Markdown("**Qwen3.8 prompt & LoRA assistant** · Uses this video's last frame and your next action. "
|
| 7717 |
"Selections and strengths are shared with the main prompt and Scene Builder. "
|
| 7718 |
+
"Uses the Prompt assistant model selected above (Original or Fable).")
|
| 7719 |
extension_context_image = gr.State(None)
|
| 7720 |
extension_prepare_btn = gr.Button("✨ Qwen3.8 · Prepare prompt, LoRAs & strengths", variant="secondary")
|
| 7721 |
extension_pick_status = gr.HTML("<div class='status-idle'>Prepare the continuation, or refresh to browse LoRAs.</div>")
|
|
|
|
| 8552 |
aspect_mode, sound_auto, sound_engine, sound_prompt, sound_negative,
|
| 8553 |
sound_steps, sound_guidance,
|
| 8554 |
chain_count, scene_prompts, scene_idea, scene_auto_count,
|
| 8555 |
+
scene_seconds, scene_auto_seconds, pb_space,
|
| 8556 |
]
|
| 8557 |
|
| 8558 |
profile_save_btn.click(
|
prompt_assistant.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared remote prompt-writer selection; no model weights or credentials here."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
FABLE = "qwen-fable"
|
| 7 |
+
# Filled with the duplicated Space when it is supplied; environment override is optional.
|
| 8 |
+
DEFAULT_FABLE_SPACE = "amisima/Qwen3.8-Fable"
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def assistant_choices(qwen_space):
|
| 12 |
+
return [("Qwen3.8 · Original", qwen_space),
|
| 13 |
+
("Qwen3.8 · Fable", FABLE)]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def is_fable(writer):
|
| 17 |
+
value = str(writer or "").strip().lower()
|
| 18 |
+
configured = os.environ.get("QWEN_FABLE_SPACE", DEFAULT_FABLE_SPACE).strip().lower()
|
| 19 |
+
for prefix in ("https://huggingface.co/spaces/", "http://huggingface.co/spaces/"):
|
| 20 |
+
if value.startswith(prefix):
|
| 21 |
+
value = value[len(prefix):].strip("/")
|
| 22 |
+
if configured.startswith(prefix):
|
| 23 |
+
configured = configured[len(prefix):].strip("/")
|
| 24 |
+
return value == FABLE or value.startswith(FABLE + ":") or "fable" in value or bool(configured and value == configured)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def supports_images(writer):
|
| 28 |
+
# Both offered Qwen models accept images; never silently strip attachments.
|
| 29 |
+
return True
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def resolve_writer(writer):
|
| 33 |
+
value = str(writer or "").strip()
|
| 34 |
+
if value.lower() == FABLE:
|
| 35 |
+
value = os.environ.get("QWEN_FABLE_SPACE", DEFAULT_FABLE_SPACE).strip()
|
| 36 |
+
if not value:
|
| 37 |
+
raise ValueError(
|
| 38 |
+
"Qwen Fable is not connected yet. Set QWEN_FABLE_SPACE to the "
|
| 39 |
+
"owner/name of your Fable vision Space. No AI request was sent."
|
| 40 |
+
)
|
| 41 |
+
elif value.lower().startswith(FABLE + ":"):
|
| 42 |
+
value = value.split(":", 1)[1].strip()
|
| 43 |
+
if not value:
|
| 44 |
+
raise ValueError("Choose a writing Space before preparing a prompt. No AI request was sent.")
|
| 45 |
+
if value.lower() == FABLE or value.lower().startswith(FABLE + ":"):
|
| 46 |
+
raise ValueError("QWEN_FABLE_SPACE must be a Space address such as owner/name.")
|
| 47 |
+
for prefix in ("https://huggingface.co/spaces/", "http://huggingface.co/spaces/"):
|
| 48 |
+
if value.startswith(prefix):
|
| 49 |
+
value = value[len(prefix):].strip("/")
|
| 50 |
+
break
|
| 51 |
+
return value
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def prepare_request(writer, message, image=None):
|
| 55 |
+
target = resolve_writer(writer)
|
| 56 |
+
return target, message, image
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _reply_text(result):
|
| 60 |
+
if result is None:
|
| 61 |
+
return ""
|
| 62 |
+
if isinstance(result, str):
|
| 63 |
+
return result.strip()
|
| 64 |
+
if isinstance(result, dict):
|
| 65 |
+
if result.get("role") in ("user", "system", "tool"):
|
| 66 |
+
return ""
|
| 67 |
+
if (result.get("metadata") or {}).get("title"):
|
| 68 |
+
return ""
|
| 69 |
+
return _reply_text(result.get("content", result.get("text", "")))
|
| 70 |
+
if isinstance(result, (tuple, list)):
|
| 71 |
+
if result and all(isinstance(item, dict) and "role" in item for item in result):
|
| 72 |
+
for item in reversed(result):
|
| 73 |
+
if item.get("role") == "assistant":
|
| 74 |
+
text = _reply_text(item)
|
| 75 |
+
if text:
|
| 76 |
+
return text
|
| 77 |
+
return ""
|
| 78 |
+
if result and all(isinstance(item, (tuple, list)) and len(item) == 2 for item in result):
|
| 79 |
+
return _reply_text(result[-1][1])
|
| 80 |
+
if result and all(isinstance(item, dict) and item.get("type") == "text" for item in result):
|
| 81 |
+
return "\n".join(_reply_text(item) for item in result).strip()
|
| 82 |
+
for item in reversed(result):
|
| 83 |
+
text = _reply_text(item)
|
| 84 |
+
if text:
|
| 85 |
+
return text
|
| 86 |
+
return ""
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def writer_result(result):
|
| 90 |
+
"""Reject incomplete JSON/prompt output, supporting existing Gradio chat APIs."""
|
| 91 |
+
if isinstance(result, (tuple, list)) and len(result) == 1:
|
| 92 |
+
return writer_result(result[0])
|
| 93 |
+
if isinstance(result, dict) and result.get("protocol") == "h3-writer-v1":
|
| 94 |
+
if result.get("finish_reason") != "stop":
|
| 95 |
+
raise ValueError(
|
| 96 |
+
"The writer returned an incomplete answer "
|
| 97 |
+
f"({result.get('finish_reason', 'unknown')}; "
|
| 98 |
+
f"{result.get('generated_tokens', '?')}/{result.get('max_new_tokens', '?')} tokens). "
|
| 99 |
+
"No automatic retry was submitted."
|
| 100 |
+
)
|
| 101 |
+
text = str(result.get("text") or "").strip()
|
| 102 |
+
else:
|
| 103 |
+
def cut_off(value):
|
| 104 |
+
if isinstance(value, dict):
|
| 105 |
+
title = str((value.get("metadata") or {}).get("title", "")).lower()
|
| 106 |
+
return "cut off" in title or "truncated" in title or cut_off(value.get("content"))
|
| 107 |
+
return isinstance(value, (tuple, list)) and any(cut_off(item) for item in value)
|
| 108 |
+
if cut_off(result):
|
| 109 |
+
raise ValueError("The writer reported a truncated answer. No automatic retry was submitted.")
|
| 110 |
+
text = _reply_text(result)
|
| 111 |
+
if not text:
|
| 112 |
+
raise ValueError("The writer returned no final answer. No automatic retry was submitted.")
|
| 113 |
+
return text
|
requirements.txt
CHANGED
|
@@ -32,3 +32,6 @@ torchdiffeq
|
|
| 32 |
nitrous-ema
|
| 33 |
librosa
|
| 34 |
soundfile
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
nitrous-ema
|
| 33 |
librosa
|
| 34 |
soundfile
|
| 35 |
+
|
| 36 |
+
# Remote Original / Fable prompt assistant.
|
| 37 |
+
gradio_client
|