MegaTronX's picture
Update app.py
b779350 verified
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 &mdash; 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()