add button to get random image from the folder i pass, also make it so if image is from the folder, then after saving it should be moved to /saved folder

import gradio as gr
from PIL import Image
# Import your model, tokenizer, and other necessary components
import torch  # Assuming PyTorch is used
import requests
import io
import uuid

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):
    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)

    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 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)}"


# Define the Gradio Blocks interface
with gr.Blocks() as demo:
    with gr.Row():
        image_input = gr.Image(label="Input Image", type="pil", height=768)
    
    #with gr.Tab("Caption Generation"):
    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
	)

    #with gr.Tab("Send to API"):
    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])

demo.launch(server_port=27994, share=True)