Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,38 +1,28 @@
|
|
| 1 |
# app.py
|
| 2 |
-
# VisPrompt Studio — Image/Text → Detailed Prompts (CPU
|
| 3 |
-
#
|
| 4 |
-
#
|
| 5 |
-
# - Salesforce/blip-image-captioning-base (fallback; faster on CPU)
|
| 6 |
|
| 7 |
import os, random, math
|
| 8 |
-
from typing import Optional
|
| 9 |
|
| 10 |
import gradio as gr
|
| 11 |
from PIL import Image, ExifTags
|
| 12 |
import torch
|
| 13 |
-
|
| 14 |
from transformers import (
|
| 15 |
-
AutoProcessor,
|
| 16 |
-
|
| 17 |
-
BlipProcessor,
|
| 18 |
-
BlipForConditionalGeneration,
|
| 19 |
)
|
| 20 |
|
| 21 |
-
# ===== Model IDs =====
|
| 22 |
MODEL_QWEN2_VL = "Qwen/Qwen2-VL-2B-Instruct"
|
| 23 |
-
MODEL_BLIP
|
| 24 |
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
_q_model = None
|
| 28 |
-
_b_processor = None
|
| 29 |
-
_b_model = None
|
| 30 |
|
| 31 |
def device():
|
| 32 |
-
|
| 33 |
-
return "cpu"
|
| 34 |
|
| 35 |
-
# ---------- Utilities ----------
|
| 36 |
def safe_open_image(inp):
|
| 37 |
if inp is None: return None
|
| 38 |
if isinstance(inp, Image.Image): return inp.convert("RGB")
|
|
@@ -42,38 +32,37 @@ def exif_info(img: Image.Image) -> dict:
|
|
| 42 |
out = {}
|
| 43 |
try:
|
| 44 |
raw = img.getexif()
|
| 45 |
-
if
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
except Exception:
|
| 55 |
pass
|
| 56 |
return out
|
| 57 |
|
| 58 |
CAMERA_ANGLES = ["eye-level","low-angle","high-angle","aerial/top-down","worm's-eye","Dutch tilt"]
|
| 59 |
-
SHOT_SIZES
|
| 60 |
-
LENSES
|
| 61 |
-
LIGHTING
|
| 62 |
-
COMPOSITION
|
| 63 |
-
POST
|
| 64 |
-
STYLES
|
| 65 |
-
VIDEO_MOTION
|
| 66 |
-
VIDEO_META
|
| 67 |
-
|
| 68 |
-
NEGATIVE
|
| 69 |
|
| 70 |
def smart_choices(caption: str, w: int, h: int, exif: dict, seed: int):
|
| 71 |
-
rnd
|
| 72 |
aspect = (w / h) if h > 0 else 1.0
|
| 73 |
-
shot
|
| 74 |
-
text
|
| 75 |
-
if any(k in text for k in ["portrait","selfie","face","headshot"]):
|
| 76 |
-
shot = "close-up"
|
| 77 |
if any(k in text for k in ["aerial","drone","top-down","overhead","bird's-eye","bird’s-eye"]):
|
| 78 |
angle = "aerial/top-down"
|
| 79 |
elif any(k in text for k in ["towering","imposing","hero","statue"]):
|
|
@@ -81,133 +70,212 @@ def smart_choices(caption: str, w: int, h: int, exif: dict, seed: int):
|
|
| 81 |
else:
|
| 82 |
angle = rnd.choice(CAMERA_ANGLES[:3])
|
| 83 |
lens = f'{exif["focal_length_mm"]}mm' if "focal_length_mm" in exif else rnd.choice(LENSES)
|
| 84 |
-
light
|
| 85 |
-
comp = ", ".join(rnd.sample(COMPOSITION, k=
|
| 86 |
-
style
|
| 87 |
-
post = ", ".join(rnd.sample(POST, k=
|
| 88 |
-
neg
|
| 89 |
return angle, shot, lens, light, comp, style, post, neg, aspect
|
| 90 |
|
| 91 |
def build_image_prompt(desc, angle, shot, lens, light, comp, style, post, aspect):
|
| 92 |
ar = "16:9" if aspect >= 1.6 else ("4:3" if aspect >= 1.3 else "1:1")
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
def build_video_prompt(img_prompt: str, motion: str, meta: list, transition: str, seconds: int):
|
| 98 |
meta_str = ", ".join(meta)
|
| 99 |
-
return (
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
-
# ----------
|
| 103 |
@torch.inference_mode()
|
| 104 |
-
def
|
| 105 |
-
global
|
| 106 |
-
if
|
| 107 |
-
|
| 108 |
_q_model = AutoModelForVision2Seq.from_pretrained(MODEL_QWEN2_VL, torch_dtype=torch.float32, trust_remote_code=True)
|
| 109 |
_q_model.to(device()).eval()
|
| 110 |
-
# Simple instruction to push detailed descriptions (uncensored)
|
| 111 |
-
prompt = "Describe this image in exhaustive detail: people, clothing, actions, camera angle, lighting, background."
|
| 112 |
-
inputs = _q_processor(text=prompt, images=img, return_tensors="pt")
|
| 113 |
-
out = _q_model.generate(**inputs, max_new_tokens=max_new_tokens)
|
| 114 |
-
text = _q_processor.batch_decode(out, skip_special_tokens=True)[0].strip()
|
| 115 |
-
return text
|
| 116 |
|
| 117 |
@torch.inference_mode()
|
| 118 |
-
def
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
_b_model = BlipForConditionalGeneration.from_pretrained(MODEL_BLIP)
|
| 123 |
_b_model.to(device()).eval()
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
out = _b_model.generate(**inputs, **kwargs)
|
| 128 |
-
return
|
| 129 |
|
| 130 |
-
def caption_image(model_choice: str, img: Image.Image,
|
| 131 |
if model_choice == "Qwen2-VL-2B-Instruct":
|
| 132 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
else:
|
| 134 |
-
|
|
|
|
|
|
|
| 135 |
|
| 136 |
-
# ---------- Main generate ----------
|
| 137 |
-
def generate(
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
-
if
|
| 144 |
-
|
|
|
|
| 145 |
w, h = img.size
|
| 146 |
exif = exif_info(img)
|
| 147 |
-
angle, shot, lens, light, comp, style, post, neg, aspect = smart_choices(caption, w, h, exif, seed)
|
| 148 |
-
base_desc = caption
|
| 149 |
else:
|
| 150 |
if not text_scene or not text_scene.strip():
|
| 151 |
return "", "", ""
|
| 152 |
-
|
| 153 |
-
w, h =
|
| 154 |
-
|
| 155 |
-
|
|
|
|
|
|
|
| 156 |
|
| 157 |
-
image_prompt = build_image_prompt(base_desc, angle, shot, lens, light, comp, style, post, aspect)
|
| 158 |
-
neg_line = f"\nNegative prompt hints: {neg}"
|
| 159 |
video_prompt = build_video_prompt(
|
| 160 |
image_prompt,
|
| 161 |
-
motion=
|
| 162 |
-
meta=
|
| 163 |
-
transition=
|
| 164 |
seconds=int(max(2, min(20, seconds)))
|
| 165 |
)
|
| 166 |
|
| 167 |
if mode == "Image prompt":
|
| 168 |
-
return caption, image_prompt +
|
| 169 |
elif mode == "Video prompt":
|
| 170 |
return caption, "", video_prompt
|
| 171 |
else:
|
| 172 |
-
return caption, image_prompt +
|
| 173 |
|
| 174 |
-
# ---------- UI ----------
|
| 175 |
-
TITLE = "VisPrompt Studio —
|
| 176 |
DESC = """
|
| 177 |
Upload an image **or** describe a scene.
|
| 178 |
-
|
| 179 |
|
| 180 |
-
|
| 181 |
-
- **Qwen2-VL-2B-Instruct (default)** —
|
| 182 |
-
- **BLIP base** — faster
|
| 183 |
"""
|
| 184 |
|
| 185 |
with gr.Blocks(title=TITLE) as demo:
|
| 186 |
gr.Markdown(f"# {TITLE}\n{DESC}")
|
| 187 |
with gr.Row():
|
| 188 |
with gr.Column(scale=1):
|
| 189 |
-
model_choice = gr.Dropdown(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
with gr.Tab("Image input"):
|
| 191 |
image = gr.Image(type="pil", label="Upload an image", height=360)
|
| 192 |
with gr.Tab("Text input"):
|
| 193 |
-
text_scene = gr.Textbox(lines=6, placeholder="Describe the scene
|
| 194 |
|
| 195 |
-
mode = gr.Radio(choices=["Image prompt","Video prompt","Both"], value="Both", label="Output type")
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
run = gr.Button("Generate prompts", variant="primary")
|
| 202 |
|
| 203 |
with gr.Column(scale=1):
|
| 204 |
-
caption_box = gr.Textbox(label="
|
| 205 |
-
img_prompt_box = gr.Textbox(label="Image Prompt", interactive=False, lines=
|
| 206 |
-
vid_prompt_box = gr.Textbox(label="Video Prompt", interactive=False, lines=14, show_copy_button=True)
|
| 207 |
|
| 208 |
run.click(
|
| 209 |
fn=generate,
|
| 210 |
-
inputs=[image, text_scene, mode,
|
| 211 |
outputs=[caption_box, img_prompt_box, vid_prompt_box]
|
| 212 |
)
|
| 213 |
|
|
|
|
| 1 |
# app.py
|
| 2 |
+
# VisPrompt Studio — Image/Text → Detailed Prompts (CPU)
|
| 3 |
+
# Focus: ensure LONG, DETAILED scene descriptions (esp. people/adult photos)
|
| 4 |
+
# Models: Qwen2-VL-2B-Instruct (default, richer captions) and BLIP base (faster)
|
|
|
|
| 5 |
|
| 6 |
import os, random, math
|
| 7 |
+
from typing import Optional
|
| 8 |
|
| 9 |
import gradio as gr
|
| 10 |
from PIL import Image, ExifTags
|
| 11 |
import torch
|
|
|
|
| 12 |
from transformers import (
|
| 13 |
+
AutoProcessor, AutoModelForVision2Seq,
|
| 14 |
+
BlipProcessor, BlipForConditionalGeneration,
|
|
|
|
|
|
|
| 15 |
)
|
| 16 |
|
|
|
|
| 17 |
MODEL_QWEN2_VL = "Qwen/Qwen2-VL-2B-Instruct"
|
| 18 |
+
MODEL_BLIP = "Salesforce/blip-image-captioning-base"
|
| 19 |
|
| 20 |
+
_q_proc = _q_model = None
|
| 21 |
+
_b_proc = _b_model = None
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
def device():
|
| 24 |
+
return "cpu" # (If you upgrade to ZeroGPU, switch to "cuda" when available)
|
|
|
|
| 25 |
|
|
|
|
| 26 |
def safe_open_image(inp):
|
| 27 |
if inp is None: return None
|
| 28 |
if isinstance(inp, Image.Image): return inp.convert("RGB")
|
|
|
|
| 32 |
out = {}
|
| 33 |
try:
|
| 34 |
raw = img.getexif()
|
| 35 |
+
if raw:
|
| 36 |
+
tag_map = {ExifTags.TAGS.get(k, k): v for k, v in raw.items()}
|
| 37 |
+
fl = tag_map.get("FocalLength")
|
| 38 |
+
if isinstance(fl, tuple) and len(fl)==2 and fl[1]!=0:
|
| 39 |
+
out["focal_length_mm"] = round(fl[0]/fl[1], 1)
|
| 40 |
+
elif isinstance(fl, (int,float)):
|
| 41 |
+
out["focal_length_mm"] = float(fl)
|
| 42 |
+
if "Model" in tag_map: out["camera_model"] = str(tag_map["Model"]).strip()
|
| 43 |
+
if "Make" in tag_map: out["camera_make"] = str(tag_map["Make"]).strip()
|
| 44 |
except Exception:
|
| 45 |
pass
|
| 46 |
return out
|
| 47 |
|
| 48 |
CAMERA_ANGLES = ["eye-level","low-angle","high-angle","aerial/top-down","worm's-eye","Dutch tilt"]
|
| 49 |
+
SHOT_SIZES = ["extreme close-up","close-up","medium shot","wide shot","extreme wide shot"]
|
| 50 |
+
LENSES = ["14mm ultra-wide","24mm wide-angle","35mm street","50mm standard","85mm portrait","135mm telephoto","200mm telephoto"]
|
| 51 |
+
LIGHTING = ["soft diffused light","golden hour rim light","overcast softbox feel","hard noon sun with crisp shadows","blue hour ambient","tungsten practicals","neon key with colored rim","studio softbox left + kicker right","volumetric god rays","moody chiaroscuro"]
|
| 52 |
+
COMPOSITION = ["rule of thirds","leading lines","central composition","frame within a frame","negative space","foreground bokeh","shallow depth of field","symmetry","diagonal dynamics","layered depth"]
|
| 53 |
+
POST = ["high micro-contrast","subtle film grain","cinematic color grade","Kodak Portra palette","teal–orange split tone","matte shadows","HDR tonality restrained","8k detail","photorealistic finish"]
|
| 54 |
+
STYLES = ["documentary realism","editorial fashion","street photography","nature landscape","architectural minimalism","cyberpunk neon","sci-fi cinematic","fantasy epic","moody noir","retro 35mm film"]
|
| 55 |
+
VIDEO_MOTION = ["slow dolly-in","gentle push-in","handheld micro-jitters","locked-off tripod","gimbal glide","orbit right-to-left","crane rise","parallax truck shot","rack focus mid-shot"]
|
| 56 |
+
VIDEO_META = ["24 fps","30 fps","48 fps","cinematic motion blur","shutter 1/48","global illumination feel"]
|
| 57 |
+
VIDEO_TRANS = ["straight cut","cinematic fade-in/out","cross dissolve","match cut"]
|
| 58 |
+
NEGATIVE = ["no distortion","no chromatic aberration","no blown highlights","no excessive sharpening","no artifacts","no watermark","no text overlay"]
|
| 59 |
|
| 60 |
def smart_choices(caption: str, w: int, h: int, exif: dict, seed: int):
|
| 61 |
+
rnd = random.Random(seed)
|
| 62 |
aspect = (w / h) if h > 0 else 1.0
|
| 63 |
+
shot = "wide shot" if aspect >= 1.5 else "medium shot"
|
| 64 |
+
text = caption.lower()
|
| 65 |
+
if any(k in text for k in ["portrait","selfie","face","headshot"]): shot = "close-up"
|
|
|
|
| 66 |
if any(k in text for k in ["aerial","drone","top-down","overhead","bird's-eye","bird’s-eye"]):
|
| 67 |
angle = "aerial/top-down"
|
| 68 |
elif any(k in text for k in ["towering","imposing","hero","statue"]):
|
|
|
|
| 70 |
else:
|
| 71 |
angle = rnd.choice(CAMERA_ANGLES[:3])
|
| 72 |
lens = f'{exif["focal_length_mm"]}mm' if "focal_length_mm" in exif else rnd.choice(LENSES)
|
| 73 |
+
light= rnd.choice(LIGHTING)
|
| 74 |
+
comp = ", ".join(rnd.sample(COMPOSITION, k=3))
|
| 75 |
+
style= rnd.choice(STYLES)
|
| 76 |
+
post = ", ".join(rnd.sample(POST, k=3))
|
| 77 |
+
neg = ", ".join(NEGATIVE[:3] + rnd.sample(NEGATIVE[3:], k=2))
|
| 78 |
return angle, shot, lens, light, comp, style, post, neg, aspect
|
| 79 |
|
| 80 |
def build_image_prompt(desc, angle, shot, lens, light, comp, style, post, aspect):
|
| 81 |
ar = "16:9" if aspect >= 1.6 else ("4:3" if aspect >= 1.3 else "1:1")
|
| 82 |
+
# Expanded, sectioned prompt for richer output
|
| 83 |
+
return (
|
| 84 |
+
f"{desc}\n"
|
| 85 |
+
f"Camera: {angle}; {shot}; lens {lens}.\n"
|
| 86 |
+
f"Lighting: {light}; natural falloff; realistic reflections and shadows.\n"
|
| 87 |
+
f"Composition: {comp}; controlled perspective; clean subject separation; coherent scale.\n"
|
| 88 |
+
f"Style: {style}; grounded materials and textures.\n"
|
| 89 |
+
f"Post: {post}; minimal artifacts; print-ready clarity.\n"
|
| 90 |
+
f"Aspect ratio hint: {ar}."
|
| 91 |
+
)
|
| 92 |
|
| 93 |
def build_video_prompt(img_prompt: str, motion: str, meta: list, transition: str, seconds: int):
|
| 94 |
meta_str = ", ".join(meta)
|
| 95 |
+
return (
|
| 96 |
+
f"{img_prompt}\n"
|
| 97 |
+
f"Video rendering: {seconds}s; camera motion: {motion}; {meta_str}; transitions: {transition}.\n"
|
| 98 |
+
f"Maintain temporal consistency, realistic parallax, and stable lighting throughout."
|
| 99 |
+
)
|
| 100 |
|
| 101 |
+
# ---------------- Caption backends ----------------
|
| 102 |
@torch.inference_mode()
|
| 103 |
+
def _ensure_qwen():
|
| 104 |
+
global _q_proc, _q_model
|
| 105 |
+
if _q_proc is None or _q_model is None:
|
| 106 |
+
_q_proc = AutoProcessor.from_pretrained(MODEL_QWEN2_VL, trust_remote_code=True)
|
| 107 |
_q_model = AutoModelForVision2Seq.from_pretrained(MODEL_QWEN2_VL, torch_dtype=torch.float32, trust_remote_code=True)
|
| 108 |
_q_model.to(device()).eval()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
|
| 110 |
@torch.inference_mode()
|
| 111 |
+
def caption_qwen(img: Image.Image, max_new_tokens: int = 220, temperature: float = 0.2, top_p: float = 0.9) -> str:
|
| 112 |
+
_ensure_qwen()
|
| 113 |
+
# Strong, explicit instruction for LONG descriptions
|
| 114 |
+
system_inst = (
|
| 115 |
+
"Describe this image in exhaustive detail. Include: subject(s), appearance, clothing, pose, "
|
| 116 |
+
"body details, interactions, accessories, objects, environment, background, textures, colors, "
|
| 117 |
+
"time of day, mood, and context. Be explicit, precise, and visual. Minimum ~80 words."
|
| 118 |
+
)
|
| 119 |
+
inputs = _q_proc(text=system_inst, images=img, return_tensors="pt")
|
| 120 |
+
out = _q_model.generate(
|
| 121 |
+
**inputs,
|
| 122 |
+
max_new_tokens=int(max_new_tokens),
|
| 123 |
+
do_sample=True,
|
| 124 |
+
temperature=float(temperature),
|
| 125 |
+
top_p=float(top_p),
|
| 126 |
+
repetition_penalty=1.05,
|
| 127 |
+
)
|
| 128 |
+
return _q_proc.batch_decode(out, skip_special_tokens=True)[0].strip()
|
| 129 |
+
|
| 130 |
+
@torch.inference_mode()
|
| 131 |
+
def caption_qwen_retry_if_short(img: Image.Image, min_words: int, **gen_kwargs) -> str:
|
| 132 |
+
"""Retry once with an even stronger instruction if the result is under min_words."""
|
| 133 |
+
text = caption_qwen(img, **gen_kwargs)
|
| 134 |
+
if len(text.split()) >= min_words:
|
| 135 |
+
return text
|
| 136 |
+
# Second pass: force structure and length
|
| 137 |
+
_ensure_qwen()
|
| 138 |
+
retry_inst = (
|
| 139 |
+
"Describe the image again with strict structure and more detail. Sections: "
|
| 140 |
+
"1) Subjects & actions, 2) Appearance & clothing, 3) Scene & background, "
|
| 141 |
+
"4) Lighting & colors, 5) Camera & framing, 6) Context & mood. "
|
| 142 |
+
"Write 120–180 words. Be concrete and visual."
|
| 143 |
+
)
|
| 144 |
+
inputs = _q_proc(text=retry_inst, images=img, return_tensors="pt")
|
| 145 |
+
out = _q_model.generate(
|
| 146 |
+
**inputs,
|
| 147 |
+
max_new_tokens=max(220, gen_kwargs.get("max_new_tokens", 220)),
|
| 148 |
+
do_sample=True,
|
| 149 |
+
temperature=gen_kwargs.get("temperature", 0.2),
|
| 150 |
+
top_p=gen_kwargs.get("top_p", 0.9),
|
| 151 |
+
repetition_penalty=1.07,
|
| 152 |
+
)
|
| 153 |
+
text2 = _q_proc.batch_decode(out, skip_special_tokens=True)[0].strip()
|
| 154 |
+
if len(text2.split()) > len(text.split()):
|
| 155 |
+
return text2
|
| 156 |
+
return text # fallback to first if somehow shorter
|
| 157 |
+
|
| 158 |
+
@torch.inference_mode()
|
| 159 |
+
def _ensure_blip():
|
| 160 |
+
global _b_proc, _b_model
|
| 161 |
+
if _b_proc is None or _b_model is None:
|
| 162 |
+
_b_proc = BlipProcessor.from_pretrained(MODEL_BLIP)
|
| 163 |
_b_model = BlipForConditionalGeneration.from_pretrained(MODEL_BLIP)
|
| 164 |
_b_model.to(device()).eval()
|
| 165 |
+
|
| 166 |
+
@torch.inference_mode()
|
| 167 |
+
def caption_blip(img: Image.Image, beam_search: bool = True, max_len: int = 96) -> str:
|
| 168 |
+
_ensure_blip()
|
| 169 |
+
inputs = _b_proc(images=img, return_tensors="pt")
|
| 170 |
+
max_len = int(max(32, min(160, max_len)))
|
| 171 |
+
kwargs = dict(max_length=max_len, num_beams=4) if beam_search else dict(max_length=max_len)
|
| 172 |
out = _b_model.generate(**inputs, **kwargs)
|
| 173 |
+
return _b_proc.decode(out[0], skip_special_tokens=True).strip()
|
| 174 |
|
| 175 |
+
def caption_image(model_choice: str, img: Image.Image, min_words: int, max_new_tokens: int):
|
| 176 |
if model_choice == "Qwen2-VL-2B-Instruct":
|
| 177 |
+
return caption_qwen_retry_if_short(
|
| 178 |
+
img,
|
| 179 |
+
min_words=min_words,
|
| 180 |
+
max_new_tokens=max_new_tokens,
|
| 181 |
+
temperature=0.35,
|
| 182 |
+
top_p=0.92,
|
| 183 |
+
)
|
| 184 |
else:
|
| 185 |
+
# BLIP won't reliably hit min_words; we just raise max_len and num_beams
|
| 186 |
+
base = caption_blip(img, beam_search=True, max_len=min(160, max_new_tokens))
|
| 187 |
+
return base
|
| 188 |
|
| 189 |
+
# ---------------- Main generate ----------------
|
| 190 |
+
def generate(
|
| 191 |
+
image: Optional[Image.Image],
|
| 192 |
+
text_scene: str,
|
| 193 |
+
mode: str,
|
| 194 |
+
min_words: int,
|
| 195 |
+
max_new_tokens: int,
|
| 196 |
+
seconds: int,
|
| 197 |
+
seed: int,
|
| 198 |
+
model_choice: str
|
| 199 |
+
):
|
| 200 |
+
rng_seed = int(seed)
|
| 201 |
+
rnd = random.Random(rng_seed)
|
| 202 |
|
| 203 |
+
if image is not None:
|
| 204 |
+
img = safe_open_image(image)
|
| 205 |
+
caption = caption_image(model_choice, img, min_words=min_words, max_new_tokens=max_new_tokens)
|
| 206 |
w, h = img.size
|
| 207 |
exif = exif_info(img)
|
|
|
|
|
|
|
| 208 |
else:
|
| 209 |
if not text_scene or not text_scene.strip():
|
| 210 |
return "", "", ""
|
| 211 |
+
caption = text_scene.strip()
|
| 212 |
+
w, h, exif = 1920, 1080, {}
|
| 213 |
+
|
| 214 |
+
angle, shot, lens, light, comp, style, post, neg, aspect = smart_choices(caption, w, h, exif, rng_seed)
|
| 215 |
+
image_prompt = build_image_prompt(caption, angle, shot, lens, light, comp, style, post, aspect)
|
| 216 |
+
negative_line = f"\nNegative prompt hints: {neg}"
|
| 217 |
|
|
|
|
|
|
|
| 218 |
video_prompt = build_video_prompt(
|
| 219 |
image_prompt,
|
| 220 |
+
motion=rnd.choice(VIDEO_MOTION),
|
| 221 |
+
meta=rnd.sample(VIDEO_META, k=2),
|
| 222 |
+
transition=rnd.choice(VIDEO_TRANS),
|
| 223 |
seconds=int(max(2, min(20, seconds)))
|
| 224 |
)
|
| 225 |
|
| 226 |
if mode == "Image prompt":
|
| 227 |
+
return caption, image_prompt + negative_line, ""
|
| 228 |
elif mode == "Video prompt":
|
| 229 |
return caption, "", video_prompt
|
| 230 |
else:
|
| 231 |
+
return caption, image_prompt + negative_line, video_prompt
|
| 232 |
|
| 233 |
+
# ---------------- UI ----------------
|
| 234 |
+
TITLE = "VisPrompt Studio — Long-Form Scene Descriptions"
|
| 235 |
DESC = """
|
| 236 |
Upload an image **or** describe a scene.
|
| 237 |
+
This version enforces **long, detailed scene descriptions** before building the camera/lighting prompts.
|
| 238 |
|
| 239 |
+
Models:
|
| 240 |
+
- **Qwen2-VL-2B-Instruct (default)** — richer people/adult descriptions on CPU (slower).
|
| 241 |
+
- **BLIP base** — faster but briefer.
|
| 242 |
"""
|
| 243 |
|
| 244 |
with gr.Blocks(title=TITLE) as demo:
|
| 245 |
gr.Markdown(f"# {TITLE}\n{DESC}")
|
| 246 |
with gr.Row():
|
| 247 |
with gr.Column(scale=1):
|
| 248 |
+
model_choice = gr.Dropdown(
|
| 249 |
+
choices=["Qwen2-VL-2B-Instruct", "BLIP base"],
|
| 250 |
+
value="Qwen2-VL-2B-Instruct",
|
| 251 |
+
label="Captioning model (drives the base scene description)",
|
| 252 |
+
allow_custom_value=False
|
| 253 |
+
)
|
| 254 |
with gr.Tab("Image input"):
|
| 255 |
image = gr.Image(type="pil", label="Upload an image", height=360)
|
| 256 |
with gr.Tab("Text input"):
|
| 257 |
+
text_scene = gr.Textbox(lines=6, placeholder="Describe the scene...", label="Scene description")
|
| 258 |
|
| 259 |
+
mode = gr.Radio(choices=["Image prompt", "Video prompt", "Both"], value="Both", label="Output type")
|
| 260 |
+
|
| 261 |
+
with gr.Accordion("Description depth", open=True):
|
| 262 |
+
min_words = gr.Slider(40, 180, value=90, step=10, label="Min words for scene description (Qwen)")
|
| 263 |
+
max_new_tokens = gr.Slider(96, 300, value=220, step=4, label="Max tokens for caption generation")
|
| 264 |
|
| 265 |
+
with gr.Accordion("Video settings", open=False):
|
| 266 |
+
seconds = gr.Slider(3, 12, value=6, step=1, label="Video duration (seconds)")
|
| 267 |
+
|
| 268 |
+
seed = gr.Slider(0, 9999, value=1234, step=1, label="Style seed")
|
| 269 |
run = gr.Button("Generate prompts", variant="primary")
|
| 270 |
|
| 271 |
with gr.Column(scale=1):
|
| 272 |
+
caption_box = gr.Textbox(label="Long scene description (from image or your text)", interactive=False, lines=10, show_copy_button=True)
|
| 273 |
+
img_prompt_box = gr.Textbox(label="Image Prompt (copy to image generators)", interactive=False, lines=14, show_copy_button=True)
|
| 274 |
+
vid_prompt_box = gr.Textbox(label="Video Prompt (copy to video generators)", interactive=False, lines=14, show_copy_button=True)
|
| 275 |
|
| 276 |
run.click(
|
| 277 |
fn=generate,
|
| 278 |
+
inputs=[image, text_scene, mode, min_words, max_new_tokens, seconds, seed, model_choice],
|
| 279 |
outputs=[caption_box, img_prompt_box, vid_prompt_box]
|
| 280 |
)
|
| 281 |
|