To add batch processing capabilities to your Gradio interface for image captioning, you need to modify both the input component to accept multiple images and adjust the processing function to handle a list of images. Below is the updated code with detailed explanations on the changes made:
Key Changes:
-
Input Component:
- Replace
gr.Image with gr.Images to allow multiple image uploads.
- Adjust the label and other properties accordingly.
-
Processing Function:
- Modify the
stream_chat_mod function (assuming it can handle batch processing) to process a list of images and return a list of captions.
- If
stream_chat_mod doesn't support batch processing, consider creating a wrapper function to handle multiple images.
-
Output Component:
- Change
gr.Textbox to gr.TextArea or another suitable component to display multiple captions.
- Alternatively, use a
gr.Dataframe or a gr.Gallery to pair images with their respective captions.
-
UI Adjustments:
- Update the UI elements to reflect batch processing, such as informing users about the ability to upload multiple images.
- Optionally, add progress indicators if processing multiple images takes time.
Here's the updated code incorporating these changes:
import spaces
import gradio as gr
from joycaption import stream_chat_mod, get_text_model, change_text_model, get_repo_gguf
JC_TITLE_MD = "<h1><center>JoyCaption Alpha One Mod</center></h1>"
JC_DESC_MD = """This space is mod of [fancyfeast/joy-caption-alpha-one](https://huggingface.co/spaces/fancyfeast/joy-caption-alpha-one),
[Wi-zz/joy-caption-pre-alpha](https://huggingface.co/Wi-zz/joy-caption-pre-alpha)"""
css = """
.info {text-align:center; !important}
"""
def batch_stream_chat_mod(images, caption_type, caption_tone, caption_length, tokens, topp, temperature):
captions = []
for img in images:
caption = stream_chat_mod(img, caption_type, caption_tone, caption_length, tokens, topp, temperature)
captions.append(caption)
return captions
with gr.Blocks(fill_width=True, css=css, delete_cache=(60, 3600)) as demo:
gr.HTML(JC_TITLE_MD)
with gr.Row():
with gr.Column():
with gr.Group():
jc_input_images = gr.Images(type="pil", label="Input Images",
sources=["upload", "clipboard"], height=384,
max_num=10, # Set maximum number of images if desired
info="Upload up to 10 images for batch processing.")
with gr.Row():
jc_caption_type = gr.Dropdown(
choices=["descriptive", "training_prompt", "rng-tags"],
label="Caption Type",
value="descriptive",
)
jc_caption_tone = gr.Dropdown(
choices=["formal", "informal"],
label="Caption Tone",
value="formal",
)
jc_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="any",
)
gr.Markdown("**Note:** Caption tone doesn't affect `rng-tags` and `training_prompt`.", elem_classes="info")
with gr.Accordion("Advanced", open=False):
with gr.Row():
jc_text_model = gr.Dropdown(label="LLM Model", info="You can enter a huggingface model repo_id to want to use.",
choices=get_text_model(), value=get_text_model()[0],
allow_custom_value=True, interactive=True, min_width=320)
jc_gguf = gr.Dropdown(label=f"GGUF Filename", choices=[], value="",
allow_custom_value=True, min_width=320, visible=False)
jc_nf4 = gr.Checkbox(label="Use NF4 quantization", value=True)
jc_text_model_button = gr.Button("Load Model", variant="secondary")
jc_use_inference_client = gr.Checkbox(label="Use Inference Client", value=False, visible=False)
with gr.Row():
jc_tokens = gr.Slider(minimum=1, maximum=4096, value=300, step=1, label="Max tokens")
jc_temperature = gr.Slider(minimum=0.1, maximum=4.0, value=0.6, step=0.1, label="Temperature")
jc_topp = gr.Slider(minimum=0, maximum=2.0, value=0.9, step=0.01, label="Top-P")
jc_run_button = gr.Button("Generate Captions", variant="primary")
with gr.Column():
jc_output_captions = gr.Dataframe(
headers=["Image", "Caption"],
datatype=["image", "str"],
label="Captions",
interactive=False
)
gr.Markdown(JC_DESC_MD, elem_classes="info")
gr.LoginButton()
gr.DuplicateButton(value="Duplicate Space for private use (This demo does not work on CPU. Requires GPU Space)")
# Connect the run button to the batch processing function
jc_run_button.click(
fn=batch_stream_chat_mod,
inputs=[jc_input_images, jc_caption_type, jc_caption_tone, jc_caption_length, jc_tokens, jc_topp, jc_temperature],
outputs=[jc_output_captions]
)
# Update the text model based on user selection
jc_text_model_button.click(
change_text_model,
inputs=[jc_text_model, jc_use_inference_client, jc_gguf, jc_nf4],
outputs=[jc_text_model],
show_api=False
)
# Handle changes in the text model dropdown
# Uncomment and adjust the following line if get_repo_gguf is required
# jc_text_model.change(get_repo_gguf, [jc_text_model], [jc_gguf], show_api=False)
jc_use_inference_client.change(
change_text_model,
inputs=[jc_text_model, jc_use_inference_client],
outputs=[jc_text_model],
show_api=False
)
if __name__ == "__main__":
# Enable queueing for handling multiple requests efficiently
demo.queue()
demo.launch(share=True)
Detailed Explanation:
-
Batch Input (gr.Images):
- Change: Replaced
gr.Image with gr.Images to allow multiple image uploads.
- Parameters:
max_num=10: Limits the number of images a user can upload at once. Adjust as needed.
info: Provides additional information to the user about batch processing.
-
Batch Processing Function:
- Function:
batch_stream_chat_mod iterates over each image and generates a caption using the existing stream_chat_mod function.
- Return: A list of captions corresponding to each image.
-
Output Display (gr.Dataframe):
- Change: Changed
gr.Textbox to gr.Dataframe to neatly display each image alongside its caption.
- Parameters:
headers=["Image", "Caption"]: Defines the columns for the dataframe.
datatype=["image", "str"]: Specifies the data types for each column.
- This setup provides a clear and organized view of results.
-
Button Label:
- Updated the run button label to "Generate Captions" to reflect its new functionality.
-
Queueing:
- Enabled
.queue() to handle multiple simultaneous requests efficiently, which is especially useful for batch processing.
-
Additional Notes:
- Model Loading: Ensure that
stream_chat_mod and related functions are optimized for batch processing to handle multiple images without significant performance degradation.
- Error Handling: Consider adding error handling within
batch_stream_chat_mod to manage potential issues with individual image processing without affecting the entire batch.
- UI Enhancements: You might want to add progress indicators or status messages to inform users about the processing state, especially if handling large batches.
Final Thoughts
This updated interface allows users to upload multiple images and receive corresponding captions efficiently. Make sure to test the updated interface thoroughly to ensure that batch processing works seamlessly and that performance remains optimal.