Sure! Below is the updated code with the requested features:
- Added a button to get a random image from a specified folder.
- If the image is from the folder, after saving, it moves the original image to the
/saved folder.
import gradio as gr
from PIL import Image
import torch # Assuming PyTorch is used
import requests
import io
import uuid
import os
import random
import shutil
# Define the source and saved folder paths
source_folder = '/mnt/h/gelbooru/Новая папка/test/HardImages'
saved_folder = os.path.join(source_folder, 'saved')
# Ensure the saved folder exists
os.makedirs(saved_folder, exist_ok=True)
def process_tags(tags_string):
# Split tags string by comma, remove empty entries, and trim whitespaces
tags = list(set(tag.strip() for tag in tags_string.split(",") if tag.strip()))
# Sort tags by their length
tags.sort(key=len)
# Remove tags starting with 'by ' or containing 'alternate '
tags = [tag for tag in tags if not (tag.startswith("by ") or "alternate " in tag)]
# Create a reversed list of tags
tags_desc = list(tags)
tags_desc.reverse()
to_remove = set()
# Define a simple helper function for word equality check
def is_words_equal(tag1, tag2):
return tag1.lower() == tag2.lower()
# Iterate through the tags to find those that should be removed
for tag in tags:
for tag2 in tags_desc:
if tag2 != tag and tag in tag2 and not is_words_equal(tag, tag2) and "cutout" not in tag2:
to_remove.add(tag)
break
# Remove all tags that were marked for removal
tags = [tag for tag in tags if tag not in to_remove]
return tags
# Load your model and tokenizer
# model = load_model_function()
# tokenizer = load_tokenizer_function()
def save_image(image, caption, image_path):
filename = '/mnt/h/gelbooru/Новая папка/test/HardImages/sugg_shared/' + str(uuid.uuid4())
image.save(filename + '.jpg', format='JPEG')
with open(filename + '.txt', "w") as f:
f.write(caption)
# If image_path is not None, move the original image to saved_folder
if image_path:
dest_path = os.path.join(saved_folder, os.path.basename(image_path))
shutil.move(image_path, dest_path)
return "OK"
def generate_caption(image, additional_words):
# Open the image using PIL
# Encode the image using your model's encoder
image_encoding = moondream.encode_image(image)
# Generate a caption based on the image encoding and additional words
prompt = f"Reconstruct caption from these tags: {additional_words}"
md_answer = moondream.answer_question(
image_encoding,
prompt,
tokenizer=tokenizer,
num_beams=4,
no_repeat_ngram_size=5,
early_stopping=True,
max_new_tokens=1024
)
# Process and return the caption
caption = process_answer(image, md_answer)
return caption
def make_description(image):
# Open the image using PIL
# Encode the image using your model's encoder
image_encoding = moondream.encode_image(image)
# Generate a caption based on the image encoding and additional words
prompt = f"Make detailed description"
md_answer = moondream.answer_question(
image_encoding,
prompt,
tokenizer=tokenizer,
num_beams=4,
no_repeat_ngram_size=5,
early_stopping=True,
max_new_tokens=1024
)
# Process and return the caption
caption = process_answer(image, md_answer)
return caption
def send_image_to_api(image, threshold):
# Convert the PIL image to bytes
image_byte_array = io.BytesIO()
image.save(image_byte_array, format='JPEG')
image_bytes = image_byte_array.getvalue()
# Define the API endpoint (replace with your actual API endpoint)
api_url = "http://muinezsssdddiiiccckk.keenetic.link:27998/predict"
# FormData keys and consistent settings
model_name = "convnextv2"
character_threshold = "0.6"
# Create the form data
form_data = {
'image': ('image.jpg', image_bytes, 'image/jpeg'),
'model_name': (None, model_name),
'general_threshold': (None, f"{threshold:.2f}"),
'character_threshold': (None, character_threshold)
}
try:
# Send a POST request to the API
response = requests.post(api_url, files=form_data)
print(response.json())
if response.status_code == 200:
# Assuming the response JSON contains 'CharacterTags' and 'GeneralTags'
result = response.json()
character_tags = [tag.replace('_', ' ') for tag in result.get('character_tags', [])]
general_tags = [tag.replace('_', ' ') for tag in result.get('general_tags', [])]
# Combine tags into a single comma-separated string
combined_tags = ",".join(character_tags + general_tags).replace('1girl', 'girl').replace('solo,', '').replace('2girls', '2 girls').replace('1boy', 'man')
# Return the combined tags
return ",".join(process_tags(combined_tags))
else:
return f"API Error: {response.status_code}"
except Exception as e:
return f"An error occurred: {str(e)}"
def get_random_image():
# Get list of image files from source folder
image_files = [os.path.join(source_folder, f) for f in os.listdir(source_folder) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp'))]
if not image_files:
return None, None # No images found
# Choose random image
image_path = random.choice(image_files)
# Open image
image = Image.open(image_path)
return image, image_path
# Define the Gradio Blocks interface
with gr.Blocks() as demo:
with gr.Row():
get_random_image_button = gr.Button("Get Random Image")
image_input = gr.Image(label="Input Image", type="pil", height=768)
image_path_state = gr.State(None) # To store the path of the image
text_input = gr.Textbox(lines=2, label="Additional Words", placeholder="Enter words to guide caption generation...")
caption_output = gr.Textbox(label="Generated Caption", interactive=True)
gr.Button("Generate Caption").click(
generate_caption,
inputs=[image_input, text_input],
outputs=caption_output
)
threshold_input = gr.Number(label="Threshold", value=0.5) # Default threshold value as a float
gr.Button("Make tags").click(
send_image_to_api,
inputs=[image_input, threshold_input],
outputs=text_input
)
gr.Button("Make detailed description").click(
make_description,
inputs=image_input, outputs=caption_output
)
gr.Button("Save").click(
save_image,
inputs=[image_input, caption_output, image_path_state],
outputs=[] # You can add an output confirmation message if needed
)
# Set up the button click for getting a random image
get_random_image_button.click(
get_random_image,
inputs=[],
outputs=[image_input, image_path_state]
)
demo.launch(server_port=27994, share=True)
Explanation of the Changes:
-
Imported Necessary Modules:
import os
import random
import shutil
These modules are used for file operations, selecting random files, and moving files.
-
Defined Source and Saved Folder Paths:
source_folder = '/mnt/h/gelbooru/Новая папка/test/HardImages'
saved_folder = os.path.join(source_folder, 'saved')
# Ensure the saved folder exists
os.makedirs(saved_folder, exist_ok=True)
Update the source_folder path to the folder containing your images. The saved_folder is a subdirectory where processed images will be moved.
-
Added get_random_image Function:
def get_random_image():
# Get list of image files from source folder
image_files = [os.path.join(source_folder, f) for f in os.listdir(source_folder) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp'))]
if not image_files:
return None, None # No images found
# Choose random image
image_path = random.choice(image_files)
# Open image
image = Image.open(image_path)
return image, image_path
This function selects a random image from the source_folder and returns both the image and its path.
-
Modified save_image Function:
def save_image(image, caption, image_path):
filename = '/mnt/h/gelbooru/Новая папка/test/HardImages/sugg_shared/' + str(uuid.uuid4())
image.save(filename + '.jpg', format='JPEG')
with open(filename + '.txt', "w") as f:
f.write(caption)
# If image_path is not None, move the original image to saved_folder
if image_path:
dest_path = os.path.join(saved_folder, os.path.basename(image_path))
shutil.move(image_path, dest_path)
return "OK"
The function now takes image_path as an input and moves the original image to the saved_folder if it exists.
-
Added image_path_state to Gradio Interface:
image_path_state = gr.State(None) # To store the path of the image
The gr.State component is used to keep track of the image path between function calls.
-
Added "Get Random Image" Button to the Interface:
with gr.Row():
get_random_image_button = gr.Button("Get Random Image")
image_input = gr.Image(label="Input Image", type="pil", height=768)
Note:
- Make sure to update the folder paths (
source_folder, saved_folder, and the save location in save_image) to match your actual directory structure.
- Ensure that you have the necessary permissions to read from and write to these directories.
- You might want to handle exceptions and edge cases (e.g., no images in the folder) as per your requirements.
- The
share=True parameter in demo.launch() allows you to share the Gradio app via a public link. Remove it if not needed.
Summary:
- Get Random Image: Clicking this button loads a random image from the specified folder into the app.
- Generate Caption: Generates a caption based on the image and any additional words provided.
- Make Tags: Sends the image to the API to retrieve tags.
- Make Detailed Description: Generates a detailed description of the image.
- Save: Saves the image and caption. If the image was loaded from the folder (using "Get Random Image"), it moves the original image to the
/saved folder.
Let me know if you need further adjustments or explanations!