Spaces:
Running on Zero
Running on Zero
File size: 14,286 Bytes
e7c2c4f b96b7b7 e7c2c4f b779350 e7c2c4f b779350 e7c2c4f 77785eb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 | import spaces
import gradio as gr
from transformers import LlavaForConditionalGeneration, TextIteratorStreamer, AutoProcessor
import torch
from PIL import Image
from threading import Thread
from typing import Generator
# liger-kernel is an optional perf optimization; skipped here for compatibility
# from liger_kernel.transformers import apply_liger_kernel_to_llama
MODEL_PATH = "fancyfeast/llama-joycaption-beta-one-hf-llava"
TITLE = """<h1 style="text-align:center;">JoyCaption Beta One</h1>
<p style="text-align:center;">Image captioning VLM — running on ZeroGPU</p>
<hr>"""
CAPTION_TYPE_MAP = {
"Descriptive": [
"Write a detailed description for this image.",
"Write a detailed description for this image in {word_count} words or less.",
"Write a {length} detailed description for this image.",
],
"Descriptive (Casual)": [
"Write a descriptive caption for this image in a casual tone.",
"Write a descriptive caption for this image in a casual tone within {word_count} words.",
"Write a {length} descriptive caption for this image in a casual tone.",
],
"Straightforward": [
"Write a straightforward caption for this image. Begin with the main subject and medium. Mention pivotal elements—people, objects, scenery—using confident, definite language. Focus on concrete details like color, shape, texture, and spatial relationships. Show how elements interact. Omit mood and speculative wording. If text is present, quote it exactly. Note any watermarks, signatures, or compression artifacts. Never mention what's absent, resolution, or unobservable details. Vary your sentence structure and keep the description concise, without starting with \"This image is…\" or similar phrasing.",
"Write a straightforward caption for this image within {word_count} words. Begin with the main subject and medium. Mention pivotal elements—people, objects, scenery—using confident, definite language. Focus on concrete details like color, shape, texture, and spatial relationships. Show how elements interact. Omit mood and speculative wording. If text is present, quote it exactly. Note any watermarks, signatures, or compression artifacts. Never mention what's absent, resolution, or unobservable details. Vary your sentence structure and keep the description concise, without starting with \"This image is…\" or similar phrasing.",
"Write a {length} straightforward caption for this image. Begin with the main subject and medium. Mention pivotal elements—people, objects, scenery—using confident, definite language. Focus on concrete details like color, shape, texture, and spatial relationships. Show how elements interact. Omit mood and speculative wording. If text is present, quote it exactly. Note any watermarks, signatures, or compression artifacts. Never mention what's absent, resolution, or unobservable details. Vary your sentence structure and keep the description concise, without starting with \"This image is…\" or similar phrasing.",
],
"Stable Diffusion Prompt": [
"Output a stable diffusion prompt that is indistinguishable from a real stable diffusion prompt.",
"Output a stable diffusion prompt that is indistinguishable from a real stable diffusion prompt. {word_count} words or less.",
"Output a {length} stable diffusion prompt that is indistinguishable from a real stable diffusion prompt.",
],
"MidJourney": [
"Write a MidJourney prompt for this image.",
"Write a MidJourney prompt for this image within {word_count} words.",
"Write a {length} MidJourney prompt for this image.",
],
"Danbooru tag list": [
"Generate only comma-separated Danbooru tags (lowercase_underscores). Strict order: `artist:`, `copyright:`, `character:`, `meta:`, then general tags. Include counts (1girl), appearance, clothing, accessories, pose, expression, actions, background. Use precise Danbooru syntax. No extra text.",
"Generate only comma-separated Danbooru tags (lowercase_underscores). Strict order: `artist:`, `copyright:`, `character:`, `meta:`, then general tags. Include counts (1girl), appearance, clothing, accessories, pose, expression, actions, background. Use precise Danbooru syntax. No extra text. {word_count} words or less.",
"Generate only comma-separated Danbooru tags (lowercase_underscores). Strict order: `artist:`, `copyright:`, `character:`, `meta:`, then general tags. Include counts (1girl), appearance, clothing, accessories, pose, expression, actions, background. Use precise Danbooru syntax. No extra text. {length} length.",
],
"e621 tag list": [
"Write a comma-separated list of e621 tags in alphabetical order for this image. Start with the artist, copyright, character, species, meta, and lore tags (if any), prefixed by 'artist:', 'copyright:', 'character:', 'species:', 'meta:', and 'lore:'. Then all the general tags.",
"Write a comma-separated list of e621 tags in alphabetical order for this image. Start with the artist, copyright, character, species, meta, and lore tags (if any), prefixed by 'artist:', 'copyright:', 'character:', 'species:', 'meta:', and 'lore:'. Then all the general tags. Keep it under {word_count} words.",
"Write a {length} comma-separated list of e621 tags in alphabetical order for this image. Start with the artist, copyright, character, species, meta, and lore tags (if any), prefixed by 'artist:', 'copyright:', 'character:', 'species:', 'meta:', and 'lore:'. Then all the general tags.",
],
"Rule34 tag list": [
"Write a comma-separated list of rule34 tags in alphabetical order for this image. Start with the artist, copyright, character, and meta tags (if any), prefixed by 'artist:', 'copyright:', 'character:', and 'meta:'. Then all the general tags.",
"Write a comma-separated list of rule34 tags in alphabetical order for this image. Start with the artist, copyright, character, and meta tags (if any), prefixed by 'artist:', 'copyright:', 'character:', and 'meta:'. Then all the general tags. Keep it under {word_count} words.",
"Write a {length} comma-separated list of rule34 tags in alphabetical order for this image. Start with the artist, copyright, character, and meta tags (if any), prefixed by 'artist:', 'copyright:', 'character:', and 'meta:'. Then all the general tags.",
],
"Booru-like tag list": [
"Write a list of Booru-like tags for this image.",
"Write a list of Booru-like tags for this image within {word_count} words.",
"Write a {length} list of Booru-like tags for this image.",
],
"Art Critic": [
"Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc.",
"Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc. Keep it within {word_count} words.",
"Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc. Keep it {length}.",
],
"Product Listing": [
"Write a caption for this image as though it were a product listing.",
"Write a caption for this image as though it were a product listing. Keep it under {word_count} words.",
"Write a {length} caption for this image as though it were a product listing.",
],
"Social Media Post": [
"Write a caption for this image as if it were being used for a social media post.",
"Write a caption for this image as if it were being used for a social media post. Limit the caption to {word_count} words.",
"Write a {length} caption for this image as if it were being used for a social media post.",
],
}
NAME_OPTION = "If there is a person/character in the image you must refer to them as {name}."
EXTRA_OPTIONS_LIST = [
"Do NOT include information about people/characters that cannot be changed (like ethnicity, gender, etc), but do still include changeable attributes (like hair style).",
"Include information about lighting.",
"Include information about camera angle.",
"Include information about whether there is a watermark or not.",
"Include information about whether there are JPEG artifacts or not.",
"If it is a photo you MUST include information about what camera was likely used and details such as aperture, shutter speed, ISO, etc.",
"Do NOT include anything sexual; keep it PG.",
"Do NOT mention the image's resolution.",
"You MUST include information about the subjective aesthetic quality of the image from low to very high.",
"Include information on the image's composition style, such as leading lines, rule of thirds, or symmetry.",
"Do NOT mention any text that is in the image.",
"Specify the depth of field and whether the background is in focus or blurred.",
"If applicable, mention the likely use of artificial or natural lighting sources.",
"Do NOT use any ambiguous language.",
"Include whether the image is sfw, suggestive, or nsfw.",
"ONLY describe the most important elements of the image.",
]
# Load model at startup (ZeroGPU will manage GPU allocation)
print("Loading processor...")
processor = AutoProcessor.from_pretrained(MODEL_PATH, token=True)
print("Loading model...")
model = LlavaForConditionalGeneration.from_pretrained(
MODEL_PATH,
torch_dtype="bfloat16",
device_map=0,
token=True,
)
assert isinstance(model, LlavaForConditionalGeneration), f"Expected LlavaForConditionalGeneration, got {type(model)}"
model.eval()
print("Model loaded and ready!")
def build_prompt(caption_type: str, caption_length: str | int, extra_options: list[str], name_input: str) -> str:
"""Build the prompt string from the UI selections."""
# Choose the right template row in CAPTION_TYPE_MAP
if caption_length == "any":
map_idx = 0
elif isinstance(caption_length, str) and caption_length.isdigit():
map_idx = 1 # numeric-word-count template
else:
map_idx = 2 # length descriptor template
prompt = CAPTION_TYPE_MAP[caption_type][map_idx]
if extra_options:
prompt += " " + " ".join(extra_options)
# Fill in template variables
prompt = prompt.format(
name=name_input,
length=caption_length,
word_count=caption_length,
)
return prompt
def toggle_name_box(extra_options: list[str]):
"""Show the name input box only when the name option is selected."""
return gr.update(visible=NAME_OPTION in extra_options)
@spaces.GPU()
@torch.no_grad()
def chat_joycaption(
input_image: Image.Image,
prompt: str,
temperature: float,
top_p: float,
max_new_tokens: int,
) -> Generator[str, None, None]:
"""Run inference with streaming output."""
if input_image is None:
yield "Please upload an image first."
return
torch.cuda.empty_cache()
# Build the conversation
convo = [
{"role": "system", "content": "You are a helpful image captioner."},
{"role": "user", "content": prompt},
]
# Format the conversation
convo_string = processor.apply_chat_template(convo, tokenize=False, add_generation_prompt=True)
assert isinstance(convo_string, str)
# Process the inputs
inputs = processor(text=[convo_string], images=[input_image], return_tensors="pt").to("cuda")
inputs["pixel_values"] = inputs["pixel_values"].to(torch.bfloat16)
# Set up streaming
streamer = TextIteratorStreamer(processor.tokenizer, skip_prompt=True, skip_special_tokens=True)
# Generation kwargs
gen_kwargs = dict(
**inputs,
streamer=streamer,
max_new_tokens=max_new_tokens,
do_sample=True if temperature > 0 else False,
suppress_tokens=None,
use_cache=True,
temperature=temperature if temperature > 0 else None,
top_k=None,
top_p=top_p,
)
# Launch generation in a thread so we can stream
thread = Thread(target=model.generate, kwargs=gen_kwargs)
thread.start()
# Stream the output
output = ""
for new_text in streamer:
output += new_text
yield output.strip()
thread.join()
# ─── Gradio UI ───────────────────────────────────────────────────────────────
with gr.Blocks() as demo:
gr.HTML(TITLE)
with gr.Row():
with gr.Column():
input_image = gr.Image(type="pil", label="Input Image")
caption_type = gr.Dropdown(
choices=list(CAPTION_TYPE_MAP.keys()),
label="Caption Type",
value="Descriptive",
)
caption_length = gr.Dropdown(
choices=["any", "very short", "short", "medium-length", "long", "very long"]
+ [str(i) for i in range(20, 261, 10)],
label="Caption Length",
value="long",
)
with gr.Accordion("Extra Options", open=False):
extra_options = gr.CheckboxGroup(
choices=[NAME_OPTION] + EXTRA_OPTIONS_LIST,
label="Extra Options",
)
name_input = gr.Textbox(
label="Person/Character Name (if applicable)",
visible=False,
)
with gr.Accordion("Generation Settings", open=False):
temperature_slider = gr.Slider(
minimum=0.0,
maximum=2.0,
value=0.6,
step=0.05,
label="Temperature",
)
top_p_slider = gr.Slider(
minimum=0.0,
maximum=1.0,
value=0.9,
step=0.01,
label="Top-p",
)
max_tokens_slider = gr.Slider(
minimum=1,
maximum=2048,
value=512,
step=1,
label="Max New Tokens",
)
with gr.Column():
prompt_box = gr.Textbox(lines=4, label="Prompt", interactive=True)
# Show the name input box only when the specific option is selected
extra_options.change(
toggle_name_box,
inputs=extra_options,
outputs=name_input,
)
# Auto-update prompt box whenever any of the inputs change
for ctrl in (caption_type, caption_length, extra_options, name_input):
ctrl.change(
build_prompt,
inputs=[caption_type, caption_length, extra_options, name_input],
outputs=prompt_box,
)
run_button = gr.Button("Caption")
output_caption = gr.Textbox(label="Caption")
run_button.click(
chat_joycaption,
inputs=[input_image, prompt_box, temperature_slider, top_p_slider, max_tokens_slider],
outputs=output_caption,
)
# Set initial prompt
prompt_box.value = build_prompt(
caption_type.value,
caption_length.value,
extra_options.value,
name_input.value,
)
if __name__ == "__main__":
demo.launch() |