gokaygokay's picture
Update app.py
8b354f3 verified
raw
history blame contribute delete
No virus
2.63 kB
import gradio as gr
from transformers import PaliGemmaForConditionalGeneration, PaliGemmaProcessor
import spaces
import torch
model = PaliGemmaForConditionalGeneration.from_pretrained("gokaygokay/sd3-long-captioner").to("cuda").eval()
processor = PaliGemmaProcessor.from_pretrained("gokaygokay/sd3-long-captioner")
import re
def modify_caption(caption: str) -> str:
"""
Removes specific prefixes from captions.
Args:
caption (str): A string containing a caption.
Returns:
str: The caption with the prefix removed if it was present.
"""
# Define the prefixes to remove
prefix_substrings = [
('captured from ', ''),
('captured at ', '')
]
# Create a regex pattern to match any of the prefixes
pattern = '|'.join([re.escape(opening) for opening, _ in prefix_substrings])
replacers = {opening: replacer for opening, replacer in prefix_substrings}
# Function to replace matched prefix with its corresponding replacement
def replace_fn(match):
return replacers[match.group(0)]
# Apply the regex to the caption
return re.sub(pattern, replace_fn, caption, count=1, flags=re.IGNORECASE)
# Example usage in your existing function
@spaces.GPU
def create_captions_rich(image):
prompt = "caption en"
model_inputs = processor(text=prompt, images=image, return_tensors="pt").to("cuda")
input_len = model_inputs["input_ids"].shape[-1]
with torch.inference_mode():
generation = model.generate(**model_inputs, max_new_tokens=256, do_sample=False)
generation = generation[0][input_len:]
decoded = processor.decode(generation, skip_special_tokens=True)
# Modify the caption to remove specific prefixes
modified_caption = modify_caption(decoded)
return modified_caption
css = """
#mkd {
height: 500px;
overflow: auto;
border: 1px solid #ccc;
}
"""
with gr.Blocks(css=css) as demo:
gr.HTML("<h1><center>PaliGemma Fine-tuned for Long Captioning for Stable Diffusion 3<center><h1>")
with gr.Tab(label="PaliGemma Long Captioner"):
with gr.Row():
with gr.Column():
input_img = gr.Image(label="Input Picture")
submit_btn = gr.Button(value="Submit")
output = gr.Text(label="Caption")
gr.Examples(
[["image1.jpg"], ["image2.jpg"], ["image3.png"], ["image4.jpg"], ["image5.jpg"], ["image6.PNG"]],
inputs = [input_img],
outputs = [output],
fn=create_captions_rich,
label='Try captioning on examples'
)
submit_btn.click(create_captions_rich, [input_img], [output])
demo.launch(debug=True)