linoyts HF Staff commited on
Commit
ea746e5
·
1 Parent(s): cd7fe6c

Add prompt assist: auto-describe reference sheet + suggest shot (Qwen2.5-VL via Inference Providers) (#6)

Browse files

- Add prompt assist: auto-describe reference sheet + suggest shot (Qwen2.5-VL via Inference Providers) (86919aa4981b55932a18070fc75eea130e9c1591)

Files changed (1) hide show
  1. app.py +100 -2
app.py CHANGED
@@ -21,6 +21,8 @@ subprocess.run([sys.executable, "-m", "pip", "install", "--force-reinstall", "--
21
  sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-pipelines", "src"))
22
  sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-core", "src"))
23
 
 
 
24
  import logging
25
  import random
26
  import tempfile
@@ -35,7 +37,7 @@ torch._dynamo.config.disable = True
35
 
36
  import spaces
37
  import gradio as gr
38
- from huggingface_hub import hf_hub_download, snapshot_download
39
 
40
  # Import LTX modules in the proven order — importing ltx_core.quantization/loader FIRST hits a
41
  # circular import (fp8_cast <-> loader.fuse_loras). Importing the model modules first forces the
@@ -325,6 +327,94 @@ def generate(sheet_image, sheet, action, seed, randomize, progress=gr.Progress(t
325
  return out_path, seed
326
 
327
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
328
  with gr.Blocks(title="LTX-2.3 Ingredients (Fast)") as demo:
329
  gr.Markdown(
330
  "# ⚡ LTX-2.3 Ingredients — Fast (Distilled)\n"
@@ -345,8 +435,10 @@ with gr.Blocks(title="LTX-2.3 Ingredients (Fast)") as demo:
345
  gr.Markdown("*Tiles your images into one sheet and loads it into the **Reference sheet** tab.*")
346
  sheet = gr.Textbox(label="Reference sheet description", lines=3,
347
  placeholder="a young woman with red hair in a green jacket (face close-up + turnaround); a brass pocket watch; a cobblestone alley at night")
 
348
  action = gr.Textbox(label="Generated video — action / shot, plus any speech & sounds", lines=3,
349
  placeholder="the woman walks down the alley, checks the pocket watch and whispers 'almost time'; footsteps on cobblestone, distant city hum")
 
350
  with gr.Accordion("Settings", open=False):
351
  randomize = gr.Checkbox(True, label="Randomize seed")
352
  seed = gr.Slider(0, MAX_SEED, value=42, step=1, label="Seed")
@@ -354,7 +446,13 @@ with gr.Blocks(title="LTX-2.3 Ingredients (Fast)") as demo:
354
  with gr.Column():
355
  video_out = gr.Video(label="Generated video")
356
 
357
- build_btn.click(compose_sheet, inputs=gallery, outputs=sheet_image)
 
 
 
 
 
 
358
  run.click(generate, inputs=[sheet_image, sheet, action, seed, randomize], outputs=[video_out, seed])
359
 
360
  gr.Examples(
 
21
  sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-pipelines", "src"))
22
  sys.path.insert(0, os.path.join(LTX_REPO_DIR, "packages", "ltx-core", "src"))
23
 
24
+ import base64
25
+ import io
26
  import logging
27
  import random
28
  import tempfile
 
37
 
38
  import spaces
39
  import gradio as gr
40
+ from huggingface_hub import hf_hub_download, snapshot_download, InferenceClient
41
 
42
  # Import LTX modules in the proven order — importing ltx_core.quantization/loader FIRST hits a
43
  # circular import (fp8_cast <-> loader.fuse_loras). Importing the model modules first forces the
 
327
  return out_path, seed
328
 
329
 
330
+ # ============================ PROMPT ASSIST (Inference Providers) ============================
331
+ # Vision-LLM helpers that auto-write the two prompt fields. These are plain network calls
332
+ # (no GPU), so they live OUTSIDE @spaces.GPU and never touch the LTX pipeline / VRAM.
333
+ PROMPT_VLM = os.environ.get("PROMPT_VLM", "Qwen/Qwen2.5-VL-72B-Instruct")
334
+ _vlm = InferenceClient(model=PROMPT_VLM, token=HF_TOKEN)
335
+
336
+ _DESCRIBE_PROMPT = (
337
+ "You are writing the 'reference sheet description' for the LTX-2.3 Ingredients video model. "
338
+ "List every distinct subject in the image in this dense style.\n"
339
+ "FORMAT:\n"
340
+ "- One running description, subjects separated by '; '.\n"
341
+ "- Each CHARACTER: rich visual detail — build, skin/fur, hair, eyes, distinctive features, full clothing — then how "
342
+ "they are shown, e.g. 'shown in a face close-up and a full-body turnaround'.\n"
343
+ "- Each PROP: a detailed visual description.\n"
344
+ "- The LOCATION last, ONLY if a real environment is shown, described with its lighting.\n"
345
+ "- Describe each DISTINCT subject EXACTLY ONCE; merge multiple views of the same subject, never repeat a character. "
346
+ "IGNORE plain, neutral or studio backgrounds behind cut-outs (those are not a location).\n"
347
+ "- No preamble; never mention 'reference sheet', grid, panels, photo, or image.\n"
348
+ "EXAMPLE STYLE (a different image): \"a young Asian woman with a warm skin tone, dark hair parted down the middle in "
349
+ "two long braids, an olive-green t-shirt and khaki cargo pants, shown in a face close-up and a full-body turnaround; "
350
+ "a large heavy-duty blue hiking backpack with an external silver frame; a sweeping mountain landscape where a dirt "
351
+ "path winds toward snow-capped peaks under a bright blue sky\".\n"
352
+ "Now write the description for THIS image."
353
+ )
354
+
355
+ _ACTION_PROMPT = (
356
+ "You write the 'action / shot' prompt for the LTX-2.3 Ingredients video model, which animates the subjects from the "
357
+ "reference sheet into a ~5 second talking clip WITH audio. Match this STYLE and RULES.\n"
358
+ "STYLE: \"cinematic [genre] scene, a [shot type] of [subjects re-described briefly]. [staged action]; X says in a "
359
+ "[voice]: '...'. [reaction / second beat]; Y replies in a [voice]: '...'. [camera move]; [film look / lighting]. "
360
+ "clear immersive audio: [voices + ambient sounds], no background music\".\n"
361
+ "RULES:\n"
362
+ "- ONE continuous shot, no cuts. If there are 2+ characters, a SINGLE held two-shot with ALL of them visible together "
363
+ "in one shared location and consistent lighting; never a split screen or side-by-side panels.\n"
364
+ "- Briefly RE-DESCRIBE each subject's key appearance so identity holds (as in the style line).\n"
365
+ "- Each character gets at least one line of dialogue as a COMPLETE self-contained sentence, attributed with a described voice.\n"
366
+ "- Natural conversational distance for non-romantic pairings; no leaning in / intimacy.\n"
367
+ "- End with 'clear immersive audio:' listing the voices and ambient sounds; 'no background music' unless music truly fits.\n"
368
+ "- Output ONLY the action paragraph, present tense, lowercase cinematic style, ~90-140 words."
369
+ )
370
+
371
+
372
+ def _img_data_uri(img, max_side=1024):
373
+ im = img.convert("RGB")
374
+ im.thumbnail((max_side, max_side))
375
+ buf = io.BytesIO()
376
+ im.save(buf, format="JPEG", quality=90)
377
+ return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode()
378
+
379
+
380
+ def describe_sheet(sheet_image):
381
+ """Auto-fill the reference-sheet description from the composed sheet image."""
382
+ if sheet_image is None:
383
+ raise gr.Error("Add or build a reference sheet first.")
384
+ try:
385
+ out = _vlm.chat_completion(
386
+ messages=[{"role": "user", "content": [
387
+ {"type": "text", "text": _DESCRIBE_PROMPT},
388
+ {"type": "image_url", "image_url": {"url": _img_data_uri(sheet_image)}}]}],
389
+ max_tokens=320, temperature=0.3,
390
+ )
391
+ return out.choices[0].message.content.strip()
392
+ except Exception as e:
393
+ raise gr.Error(f"Auto-describe failed ({type(e).__name__}). Check the HF_TOKEN secret / model access.")
394
+
395
+
396
+ def suggest_action(sheet_image, sheet_desc, action_idea):
397
+ """Write the action/shot prompt. Expands the idea in the action box; invents one if empty."""
398
+ if sheet_image is None:
399
+ raise gr.Error("Add or build a reference sheet first.")
400
+ idea = (action_idea or "").strip()
401
+ subjects = (sheet_desc or "").strip() or "(infer the subjects from the image)"
402
+ user = f"Subjects: {subjects}\n\nIdea: {idea if idea else '(none — invent a fitting short scene)'}"
403
+ try:
404
+ out = _vlm.chat_completion(
405
+ messages=[
406
+ {"role": "system", "content": _ACTION_PROMPT},
407
+ {"role": "user", "content": [
408
+ {"type": "text", "text": user},
409
+ {"type": "image_url", "image_url": {"url": _img_data_uri(sheet_image)}}]}],
410
+ max_tokens=420, temperature=0.7,
411
+ )
412
+ return out.choices[0].message.content.strip()
413
+ except Exception as e:
414
+ raise gr.Error(f"Suggest shot failed ({type(e).__name__}). Check the HF_TOKEN secret / model access.")
415
+ # =============================================================================================
416
+
417
+
418
  with gr.Blocks(title="LTX-2.3 Ingredients (Fast)") as demo:
419
  gr.Markdown(
420
  "# ⚡ LTX-2.3 Ingredients — Fast (Distilled)\n"
 
435
  gr.Markdown("*Tiles your images into one sheet and loads it into the **Reference sheet** tab.*")
436
  sheet = gr.Textbox(label="Reference sheet description", lines=3,
437
  placeholder="a young woman with red hair in a green jacket (face close-up + turnaround); a brass pocket watch; a cobblestone alley at night")
438
+ describe_btn = gr.Button("✨ Auto-describe sheet", size="sm")
439
  action = gr.Textbox(label="Generated video — action / shot, plus any speech & sounds", lines=3,
440
  placeholder="the woman walks down the alley, checks the pocket watch and whispers 'almost time'; footsteps on cobblestone, distant city hum")
441
+ suggest_btn = gr.Button("✨ Suggest shot — type a one-line idea above, or leave empty to invent", size="sm")
442
  with gr.Accordion("Settings", open=False):
443
  randomize = gr.Checkbox(True, label="Randomize seed")
444
  seed = gr.Slider(0, MAX_SEED, value=42, step=1, label="Seed")
 
446
  with gr.Column():
447
  video_out = gr.Video(label="Generated video")
448
 
449
+ # Build the sheet, then auto-describe it into the description box.
450
+ build_btn.click(compose_sheet, inputs=gallery, outputs=sheet_image).then(
451
+ describe_sheet, inputs=sheet_image, outputs=sheet)
452
+ # Auto-describe when a sheet image is uploaded directly, or via the button.
453
+ sheet_image.upload(describe_sheet, inputs=sheet_image, outputs=sheet)
454
+ describe_btn.click(describe_sheet, inputs=sheet_image, outputs=sheet)
455
+ suggest_btn.click(suggest_action, inputs=[sheet_image, sheet, action], outputs=action)
456
  run.click(generate, inputs=[sheet_image, sheet, action, seed, randomize], outputs=[video_out, seed])
457
 
458
  gr.Examples(