MeghanaNanuvala's picture
Upload folder using huggingface_hub
8793be1 verified
Raw History Blame Contribute Delete
2.02 kB
"""Apparel Image Caption demo: upload a clothing photo and get alt-text for it."""
import os
import spaces # Hugging Face ZeroGPU: lends the Space a GPU while caption() runs
import gradio as gr
import torch
from transformers import AutoProcessor, Florence2ForConditionalGeneration
# The fine-tuned model on the Hugging Face Hub. Set the MODEL_ID environment variable
# to a local folder (outputs/checkpoints/best) to try the app without the Hub.
MODEL_ID = os.environ.get("MODEL_ID", "MeghanaNanuvala/apparel-image-caption")
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
processor = AutoProcessor.from_pretrained(MODEL_ID)
model = Florence2ForConditionalGeneration.from_pretrained(MODEL_ID).eval().to(DEVICE)
@spaces.GPU(duration=30) # one caption takes about a second on the GPU
@torch.inference_mode()
def caption(image):
if image is None:
return ""
# same prompt and decoding settings as in training and evaluation
inputs = processor(text=["<CAPTION>"], images=[image.convert("RGB")], return_tensors="pt")
ids = model.generate(**inputs.to(DEVICE), max_new_tokens=96, num_beams=3, do_sample=False)
text = processor.batch_decode(ids, skip_special_tokens=True)[0]
return " ".join(text.split()).strip("\"'` ")
demo = gr.Interface(
fn=caption,
inputs=gr.Image(type="pil", label="Clothing photo"),
outputs=gr.Textbox(label="Alt-text"),
examples=["examples/shirt.jpg", "examples/trousers.jpg", "examples/skirt.jpg",
"examples/jacket.jpg"],
cache_examples=False,
flagging_mode="never",
title="Apparel Image Caption",
description="Upload a product photo of one garment and the model writes a short, objective "
"description for screen readers. It is Florence-2-base fine-tuned on H&M product "
"photos, so it works best on studio shots of a single garment, and it can get "
"small details such as pockets and fastenings wrong.",
)
if __name__ == "__main__":
demo.launch()