joy-caption / app.py
luca115's picture
Upload folder using huggingface_hub
2bc9e93 verified
Raw
History Blame Contribute Delete
16 kB
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
UPSAMPLER_THEME = gr.themes.Soft(
primary_hue=gr.themes.colors.indigo,
secondary_hue=gr.themes.colors.purple,
neutral_hue=gr.themes.colors.slate,
).set(
button_primary_background_fill="linear-gradient(135deg, #6366f1, #a855f7)",
button_primary_background_fill_hover="linear-gradient(135deg, #5457e5, #9333ea)",
button_primary_text_color="#ffffff",
button_primary_border_color="*primary_500",
)
UPSAMPLER_CSS = """
footer{display:none !important}
.gradio-container{max-width:1000px !important; margin:0 auto !important}
h1,h2,h3{font-family:system-ui,-apple-system,'Segoe UI',sans-serif}
"""
css = """
#col-container {
margin: 0 auto;
max-width: 960px;
}
"""
header = """<div style="max-width:760px;margin:0 auto;text-align:center;padding:20px 16px 2px;font-family:system-ui,-apple-system,'Segoe UI',sans-serif">
<h1 style="font-size:1.7rem;font-weight:700;margin:0 0 6px;letter-spacing:-.02em">JoyCaption Beta One</h1>
<p style="font-size:1rem;line-height:1.5;opacity:.6;margin:0">Caption any image with a purpose-built image captioning model.</p>
</div>"""
footer = """<div style="max-width:640px;margin:2rem auto .4rem;text-align:center;font-family:system-ui,-apple-system,'Segoe UI',sans-serif">
<p style="font-size:.85rem;line-height:1.6;opacity:.5;margin:0 0 10px">JoyCaption Beta One is a free, open image captioning model that turns any picture into text: detailed natural-language descriptions, concise alt text for accessibility and SEO, Danbooru-style tag lists, and training prompts for Stable Diffusion or LoRA datasets. Pick a caption style, set the length, and get your caption in seconds.</p>
<p style="font-size:.85rem;line-height:1.6;opacity:.65;margin:0">Maintained by <a href="https://upsampler.com" target="_blank" rel="noopener" style="color:#8b7cf6;font-weight:600;text-decoration:none">Upsampler</a>. Check out the <a href="https://upsampler.com/free-image-captioning-no-signup" target="_blank" rel="noopener" style="color:#8b7cf6;font-weight:600;text-decoration:none">free image caption generator</a>, no sign-up required.</p>
</div>"""
MODEL_PATH = "fancyfeast/llama-joycaption-beta-one-hf-llava"
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.",
],
"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}."
# Load model
processor = AutoProcessor.from_pretrained(MODEL_PATH)
model = LlavaForConditionalGeneration.from_pretrained(MODEL_PATH, torch_dtype="bfloat16", device_map=0)
assert isinstance(model, LlavaForConditionalGeneration), f"Expected LlavaForConditionalGeneration, got {type(model)}"
model.eval()
def build_prompt(caption_type: str, caption_length: str | int, extra_options: list[str], name_input: str) -> str:
# 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)
return prompt.format(
name=name_input or "{NAME}",
length=caption_length,
word_count=caption_length,
)
def toggle_name_box(selected_options: list[str]):
"""Show the name textbox only when the specific option is selected."""
return gr.update(visible=NAME_OPTION in selected_options)
def get_duration(input_image, prompt, temperature, top_p, max_new_tokens, log_prompt):
# Generation speed is ~40 tok/s on ZeroGPU; a full 512-token caption measured
# ~13s wall. Scale the GPU request with the token budget instead of the 60s
# default so anonymous visitors with small quotas aren't rejected up front.
return min(90, 12 + int(max_new_tokens) // 25)
@spaces.GPU(duration=get_duration)
@torch.no_grad()
def chat_joycaption(input_image: Image.Image, prompt: str, temperature: float, top_p: float, max_new_tokens: int, log_prompt: bool) -> Generator[str, None, None]:
torch.cuda.empty_cache()
if input_image is None:
yield "No image provided. Please upload an image."
return
convo = [
{
"role": "system",
# Beta One supports a wider range of system prompts, but this is a good default
"content": "You are a helpful assistant and help users with any queries they may have.",
},
{
"role": "user",
"content": prompt.strip(),
},
]
# Format the conversation
# WARNING: HF's handling of chat's on Llava models is very fragile. This specific combination of processor.apply_chat_template(), and processor() works
# but if using other combinations always inspect the final input_ids to ensure they are correct. Often times you will end up with multiple <bos> tokens
# if not careful, which can make the model perform poorly.
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)
streamer = TextIteratorStreamer(processor.tokenizer, timeout=10.0, skip_prompt=True, skip_special_tokens=True)
generate_kwargs = dict(
**inputs,
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 if temperature > 0 else None,
streamer=streamer,
)
t = Thread(target=model.generate, kwargs=generate_kwargs)
t.start()
outputs = []
for text in streamer:
outputs.append(text)
yield "".join(outputs)
with gr.Blocks(css=UPSAMPLER_CSS + "\n" + css, theme=UPSAMPLER_THEME) as demo:
gr.HTML(header)
with gr.Column(elem_id="col-container"):
with gr.Row(equal_height=False):
with gr.Column():
input_image = gr.Image(type="pil", label="Input Image", height=400)
caption_type = gr.Dropdown(
choices=list(CAPTION_TYPE_MAP.keys()),
value="Descriptive",
label="Caption Type",
)
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,
"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.",
"ONLY describe the most important elements of the image.",
"If it is a work of art, do not include the artist's name or the title of the work.",
"Identify the image orientation (portrait, landscape, or square) and aspect ratio if obvious.",
"Include information about the ages of any people/characters when applicable.",
"Mention whether the image depicts an extreme close-up, close-up, medium close-up, medium shot, cowboy shot, medium wide shot, wide shot, or extreme wide shot.",
"Do not mention the mood/feeling/etc of the image.",
"Explicitly specify the vantage height (eye-level, low-angle worm’s-eye, bird’s-eye, drone, rooftop, etc.).",
"If there is a watermark, you must mention it.",
"""Your response will be used by a text-to-image model, so avoid useless meta phrases like “This image shows…”, "You are looking at...", etc.""",
],
label="Select one or more",
)
name_input = gr.Textbox(label="Person / Character Name", visible=False)
with gr.Accordion("Generation settings", open=False):
prompt_box = gr.Textbox(lines=4, label="Prompt (auto-built, editable)", interactive=True)
temperature_slider = gr.Slider(
minimum=0.0, maximum=2.0, value=0.6, step=0.05,
label="Temperature",
info="Higher values make the output more random, lower values make it more deterministic."
)
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",
info="Maximum number of tokens to generate. The model will stop generating if it reaches this limit."
)
log_prompt = gr.Checkbox(value=False, label="Unused (kept for API compatibility)", visible=False)
run_button = gr.Button("Caption", variant="primary")
with gr.Column():
output_caption = gr.Textbox(label="Caption", lines=12)
# 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.click(
chat_joycaption,
inputs=[input_image, prompt_box, temperature_slider, top_p_slider, max_tokens_slider, log_prompt],
outputs=output_caption,
)
# Initial prompt
prompt_box.value = build_prompt(caption_type.value, caption_length.value, extra_options.value, name_input.value)
gr.HTML(footer)
if __name__ == "__main__":
demo.launch(mcp_server=True, ssr_mode=False, show_error=True)