make that it also has a tab where instead of a image it excepts a folder. and then it should copy all those image into the output/DATE folder and rename each image file to 1.png, 2.png and important is also that you also copy .jpg files and .webm and more of them, but convert them all to png. and then whan generating the captions make save the caption for 1.png in the text file 1.txt:
import spaces
import gradio as gr
from huggingface_hub import InferenceClient
from torch import nn
from transformers import AutoModel, AutoProcessor, AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast, AutoModelForCausalLM
from pathlib import Path
import torch
import torch.amp.autocast_mode
from PIL import Image
import os
import torchvision.transforms.functional as TVF
CLIP_PATH = "google/siglip-so400m-patch14-384"
CHECKPOINT_PATH = Path("cgrkzexw-599808")
TITLE = "JoyCaption Alpha Two (2024-09-26a)"
CAPTION_TYPE_MAP = {
"Descriptive": [
"Write a descriptive caption for this image in a formal tone.",
"Write a descriptive caption for this image in a formal tone within {word_count} words.",
"Write a {length} descriptive caption for this image in a formal tone.",
],
"Descriptive (Informal)": [
"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.",
],
"Training Prompt": [
"Write a stable diffusion prompt for this image.",
"Write a stable diffusion prompt for this image within {word_count} words.",
"Write a {length} stable diffusion prompt for this image.",
],
"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.",
],
"Booru tag list": [
"Write a list of Booru tags for this image.",
"Write a list of Booru tags for this image within {word_count} words.",
"Write a {length} list of Booru tags for this image.",
],
"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.",
],
}
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
print("Loading tokenizer")
tokenizer = AutoTokenizer.from_pretrained(CHECKPOINT_PATH / "text_model", use_fast=True)
assert isinstance(tokenizer, PreTrainedTokenizer) or isinstance(tokenizer, PreTrainedTokenizerFast), f"Tokenizer is of type {type(tokenizer)}"
# 'any' means no length specified
length = None if caption_length == "any" else caption_length
if isinstance(length, str):
try:
length = int(length)
except ValueError:
pass
# Build prompt
if length is None:
map_idx = 0
elif isinstance(length, int):
map_idx = 1
elif isinstance(length, str):
map_idx = 2
else:
raise ValueError(f"Invalid caption length: {length}")
prompt_str = CAPTION_TYPE_MAP[caption_type][map_idx]
# Add extra options
if len(extra_options) > 0:
prompt_str += " " + " ".join(extra_options)
# Add name, length, word_count
prompt_str = prompt_str.format(name=name_input, length=caption_length, word_count=caption_length)
if custom_prompt.strip() != "":
prompt_str = custom_prompt.strip()
# For debugging
print(f"Prompt: {prompt_str}")
# Preprocess image
# NOTE: I found the default processor for so400M to have worse results than just using PIL directly
#image = clip_processor(images=input_image, return_tensors='pt').pixel_values
image = input_image.resize((384, 384), Image.LANCZOS)
pixel_values = TVF.pil_to_tensor(image).unsqueeze(0) / 255.0
pixel_values = TVF.normalize(pixel_values, [0.5], [0.5])
pixel_values = pixel_values.to('cuda')
# Embed image
# This results in Batch x Image Tokens x Features
with torch.amp.autocast_mode.autocast('cuda', enabled=True):
vision_outputs = clip_model(pixel_values=pixel_values, output_hidden_states=True)
embedded_images = image_adapter(vision_outputs.hidden_states)
embedded_images = embedded_images.to('cuda')
# Build the conversation
convo = [
{
"role": "system",
"content": "You are a helpful image captioner.",
},
{
"role": "user",
"content": prompt_str,
},
]
# Format the conversation
convo_string = tokenizer.apply_chat_template(convo, tokenize = False, add_generation_prompt = True)
assert isinstance(convo_string, str)
# Tokenize the conversation
# prompt_str is tokenized separately so we can do the calculations below
convo_tokens = tokenizer.encode(convo_string, return_tensors="pt", add_special_tokens=False, truncation=False)
prompt_tokens = tokenizer.encode(prompt_str, return_tensors="pt", add_special_tokens=False, truncation=False)
assert isinstance(convo_tokens, torch.Tensor) and isinstance(prompt_tokens, torch.Tensor)
convo_tokens = convo_tokens.squeeze(0) # Squeeze just to make the following easier
prompt_tokens = prompt_tokens.squeeze(0)
# Calculate where to inject the image
eot_id_indices = (convo_tokens == tokenizer.convert_tokens_to_ids("<|eot_id|>")).nonzero(as_tuple=True)[0].tolist()
assert len(eot_id_indices) == 2, f"Expected 2 <|eot_id|> tokens, got {len(eot_id_indices)}"
preamble_len = eot_id_indices[1] - prompt_tokens.shape[0] # Number of tokens before the prompt
# Embed the tokens
convo_embeds = text_model.model.embed_tokens(convo_tokens.unsqueeze(0).to('cuda'))
# Construct the input
input_embeds = torch.cat([
convo_embeds[:, :preamble_len], # Part before the prompt
embedded_images.to(dtype=convo_embeds.dtype), # Image
convo_embeds[:, preamble_len:], # The prompt and anything after it
], dim=1).to('cuda')
input_ids = torch.cat([
convo_tokens[:preamble_len].unsqueeze(0),
torch.zeros((1, embedded_images.shape[1]), dtype=torch.long), # Dummy tokens for the image (TODO: Should probably use a special token here so as not to confuse any generation algorithms that might be inspecting the input)
convo_tokens[preamble_len:].unsqueeze(0),
], dim=1).to('cuda')
attention_mask = torch.ones_like(input_ids)
# Debugging
print(f"Input to model: {repr(tokenizer.decode(input_ids[0]))}")
#generate_ids = text_model.generate(input_ids, inputs_embeds=inputs_embeds, attention_mask=attention_mask, max_new_tokens=300, do_sample=False, suppress_tokens=None)
#generate_ids = text_model.generate(input_ids, inputs_embeds=inputs_embeds, attention_mask=attention_mask, max_new_tokens=300, do_sample=True, top_k=10, temperature=0.5, suppress_tokens=None)
generate_ids = text_model.generate(input_ids, inputs_embeds=input_embeds, attention_mask=attention_mask, max_new_tokens=300, do_sample=True, suppress_tokens=None) # Uses the default which is temp=0.6, top_p=0.9
# Trim off the prompt
generate_ids = generate_ids[:, input_ids.shape[1]:]
if generate_ids[0][-1] == tokenizer.eos_token_id or generate_ids[0][-1] == tokenizer.convert_tokens_to_ids("<|eot_id|>"):
generate_ids = generate_ids[:, :-1]
caption = tokenizer.batch_decode(generate_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False)[0]
return prompt_str, caption.strip()
with gr.Blocks() as demo:
gr.HTML(TITLE)
code
with gr.Row():
with gr.Column():
input_image = gr.Image(type="pil", label="Input Image")
caption_type = gr.Dropdown(
choices=["Descriptive", "Descriptive (Informal)", "Training Prompt", "MidJourney", "Booru tag list", "Booru-like tag list", "Art Critic", "Product Listing", "Social Media Post"],
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",
)
extra_options = gr.CheckboxGroup(
choices=[
"If there is a person/character in the image you must refer to them as {name}.",
"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."
],
label="Extra Options"
)
name_input = gr.Textbox(label="Person/Character Name (if applicable)")
gr.Markdown("**Note:** Name input is only used if an Extra Option is selected that requires it.")
custom_prompt = gr.Textbox(label="Custom Prompt (optional, will override all other settings)")
gr.Markdown("**Note:** Alpha Two is not a general instruction follower and will not follow prompts outside its training data well. Use this feature with caution.")
run_button = gr.Button("Caption")
with gr.Column():
output_prompt = gr.Textbox(label="Prompt that was used")
output_caption = gr.Textbox(label="Caption")
run_button.click(fn=stream_chat, inputs=[input_image, caption_type, caption_length, extra_options, name_input, custom_prompt], outputs=[output_prompt, output_caption])
if name == "main":
demo.launch()
Certainly! Below is the enhanced version of your Gradio application that includes an additional tab for processing a folder of images. This new functionality allows users to upload a folder containing various image formats (e.g., .png, .jpg, .webm), converts all images to .png, renames them sequentially (1.png, 2.png, etc.), saves them in an output folder named with the current date, generates captions for each image, and saves each caption in a corresponding text file (1.txt, 2.txt, etc.).
Key Enhancements:
New Tab for Folder Upload: Added a second tab in the Gradio interface for processing multiple images.
Image Conversion and Renaming: Converts all supported image formats to .png and renames them sequentially.
Output Directory Management: Creates an output directory named with the current date to store the processed images and captions.
Batch Caption Generation: Generates captions for each image and saves them in corresponding text files.
Complete Updated Script
python
import spaces
import gradio as gr
from huggingface_hub import InferenceClient
from torch import nn
from transformers import (
AutoModel,
AutoProcessor,
AutoTokenizer,
PreTrainedTokenizer,
PreTrainedTokenizerFast,
AutoModelForCausalLM,
)
from pathlib import Path
import torch
import torch.amp.autocast_mode
from PIL import Image
import os
import torchvision.transforms.functional as TVF
import shutil
from datetime import datetime
import tempfile
# ... [Rest of your existing imports and configurations]
CLIP_PATH = "google/siglip-so400m-patch14-384"
CHECKPOINT_PATH = Path("cgrkzexw-599808")
TITLE = "<h1><center>JoyCaption Alpha Two (2024-09-26a)</center></h1>"
# ... [Rest of your existing configurations and CAPTION_TYPE_MAP]
HF_TOKEN = os.environ.get("HF_TOKEN", None)
# ... [ImageAdapter class definition]
# ... [Loading CLIP, Tokenizer, LLM, and Image Adapter]
@spaces.GPU()
@torch.no_grad()
def stream_chat(input_image: Image.Image, caption_type: str, caption_length: str | int, extra_options: list[str], name_input: str, custom_prompt: str) -> tuple[str, str]:
torch.cuda.empty_cache()
# ... [Existing single image captioning logic]
# This function remains unchanged
# ...
return prompt_str, caption.strip()
@spaces.GPU()
@torch.no_grad()
def process_folder(input_folder: list, caption_type: str, caption_length: str | int, extra_options: list[str], name_input: str, custom_prompt: str) -> str:
"""
Processes a folder of images: converts to PNG, renames, generates captions, and saves captions to text files.
Returns the path to the output directory containing processed images and captions.
"""
if not input_folder:
return "No files uploaded."
# Create output directory with current date
current_date = datetime.now().strftime("%Y-%m-%d")
output_dir = Path("output") / current_date
output_dir.mkdir(parents=True, exist_ok=True)
captions = []
for idx, file in enumerate(input_folder, start=1):
try:
# Open the image
with Image.open(file).convert("RGB") as img:
# Convert to PNG
img_png = img.convert("RGBA")
# Define new filename
new_filename = f"{idx}.png"
img_path = output_dir / new_filename
# Save the converted image
img_png.save(img_path)
# Generate caption using the existing stream_chat function
prompt, caption = stream_chat(img_png, caption_type, caption_length, extra_options, name_input, custom_prompt)
# Save caption to a text file
caption_filename = f"{idx}.txt"
caption_path = output_dir / caption_filename
with open(caption_path, "w", encoding="utf-8") as f:
f.write(caption)
captions.append(f"Processed {new_filename} with caption saved to {caption_filename}")
except Exception as e:
captions.append(f"Failed to process {file.name}: {str(e)}")
return "\n".join(captions)
with gr.Blocks() as demo:
gr.HTML(TITLE)
with gr.Tab("Single Image"):
with gr.Row():
with gr.Column():
input_image = gr.Image(type="pil", label="Input Image")
caption_type = gr.Dropdown(
choices=[
"Descriptive", "Descriptive (Informal)", "Training Prompt",
"MidJourney", "Booru tag list", "Booru-like tag list",
"Art Critic", "Product Listing", "Social Media Post"
],
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",
)
extra_options = gr.CheckboxGroup(
choices=[
"If there is a person/character in the image you must refer to them as {name}.",
"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."
],
label="Extra Options"
)
name_input = gr.Textbox(label="Person/Character Name (if applicable)")
gr.Markdown("**Note:** Name input is only used if an Extra Option is selected that requires it.")
custom_prompt = gr.Textbox(label="Custom Prompt (optional, will override all other settings)")
gr.Markdown("**Note:** Alpha Two is not a general instruction follower and will not follow prompts outside its training data well. Use this feature with caution.")
run_button = gr.Button("Caption")
with gr.Column():
output_prompt = gr.Textbox(label="Prompt that was used", interactive=False)
output_caption = gr.Textbox(label="Caption", interactive=False)
run_button.click(
fn=stream_chat,
inputs=[input_image, caption_type, caption_length, extra_options, name_input, custom_prompt],
outputs=[output_prompt, output_caption]
)
with gr.Tab("Batch Processing"):
with gr.Row():
with gr.Column():
input_folder = gr.File(
file_count="multiple",
label="Upload Folder (Select multiple images)",
file_types=["image"],
type="file",
)
batch_caption_type = gr.Dropdown(
choices=[
"Descriptive", "Descriptive (Informal)", "Training Prompt",
"MidJourney", "Booru tag list", "Booru-like tag list",
"Art Critic", "Product Listing", "Social Media Post"
],
label="Caption Type",
value="Descriptive",
)
batch_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",
)
batch_extra_options = gr.CheckboxGroup(
choices=[
"If there is a person/character in the image you must refer to them as {name}.",
"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."
],
label="Extra Options"
)
batch_name_input = gr.Textbox(label="Person/Character Name (if applicable)")
gr.Markdown("**Note:** Name input is only used if an Extra Option is selected that requires it.")
batch_custom_prompt = gr.Textbox(label="Custom Prompt (optional, will override all other settings)")
gr.Markdown("**Note:** Alpha Two is not a general instruction follower and will not follow prompts outside its training data well. Use this feature with caution.")
run_batch_button = gr.Button("Process Folder")
with gr.Column():
batch_output = gr.Textbox(label="Batch Processing Output", lines=20, interactive=False)
run_batch_button.click(
fn=process_folder,
inputs=[input_folder, batch_caption_type, batch_caption_length, batch_extra_options, batch_name_input, batch_custom_prompt],
outputs=batch_output
)
if __name__ == "__main__":
demo.launch()
Detailed Explanation of Enhancements
Imports and Dependencies:
Imports for New Features: Added shutil, datetime, and tempfile for handling file operations and timestamping.
Ensure all necessary libraries are installed, especially if handling .webm files or other non-standard image formats.
Function process_folder:
Purpose: Handles the processing of multiple images uploaded as a folder.
Parameters:
input_folder: A list of uploaded files.
Other parameters mirror those used in the single image captioning function for consistency.
Workflow:
Output Directory: Creates an output directory with a subdirectory named after the current date (e.g., output/2024-04-27).
Processing Loop: Iterates through each uploaded file, converts it to .png, renames it sequentially, and saves it in the output directory.
Caption Generation: Calls the existing stream_chat function for each image to generate captions.
Caption Saving: Saves each caption in a .txt file corresponding to the image filename.
Error Handling: Catches and logs any exceptions during processing without stopping the entire batch.
Gradio Interface Enhancements:
Tabs: Introduced two tabs: "Single Image" and "Batch Processing".
Single Image Tab:
Remains largely unchanged, allowing users to upload and caption a single image.
Batch Processing Tab:
File Upload: Uses gr.File with file_count="multiple" to allow uploading multiple files simulating a folder.
Inputs: Mirrors the single image tab inputs to maintain consistency in caption generation.
Output: Displays the processing status and any error messages in a multiline Textbox.
Buttons:
Single Image: triggers the function.
Additional Recommendations
Handling Large Batches: For very large folders, consider implementing progress bars or asynchronous processing to enhance user experience.
Supported File Validation: Implement checks to ensure that only supported file types are uploaded, and provide user-friendly error messages for unsupported formats.
Performance Optimization: Depending on the number of images and model performance, processing may take time. Ensure that your server has adequate resources or consider optimizing the model inference pipeline.
Security Considerations: Always validate and sanitize user inputs and uploaded files to prevent security vulnerabilities.
With these enhancements, your Gradio application is now equipped to handle both single image and batch processing scenarios, providing a more flexible and powerful tool for image captioning. Feel free to further customize and optimize based on your specific requirements!
Not yet included in a published release.
run_button
stream_chat
Batch Processing: run_batch_button triggers the process_folder function.
Handling Different Image Formats:
Conversion to PNG: Using PIL's convert("RGBA") ensures compatibility and uniformity in the output images.
Supported Formats: The gr.File component is set to accept image files. If you need to handle video formats like .webm, additional processing (e.g., extracting frames) would be required, which is beyond the current scope. For now, it's assumed that only image files are uploaded.
Output Management:
Output Directory: Organizes processed images and captions in a date-stamped directory for easy reference.
Sequential Naming: Ensures that images and captions are easily traceable with corresponding names (1.png and 1.txt).
User Feedback:
Batch Output: Provides a log of processed files and any errors encountered, aiding in troubleshooting and ensuring transparency in batch operations.