Tell me the things I need to put in the requirements.txt to make this script work SAY NOTHING BUT THE REQUIREMENTS.TXT copy paste:
import gradio as gr
import torch
from diffusers import ControlNetModel, StableDiffusionControlNetImg2ImgPipeline
from PIL import Image, ImageDraw
import numpy as np
from controlnet_aux import OpenposeDetector
Check if GPU is available and adjust torch_dtype
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
Install accelerate for better memory management
try:
from accelerate import Accelerator
accelerator = Accelerator()
except ImportError:
accelerator = None
print("Install accelerate for better memory management: pip install accelerate")
Pre-load publicly available Stable Diffusion model and ControlNet for advanced image editing
controlnet = ControlNetModel.from_pretrained("lllyasviel/control_v11p_sd15_openpose", torch_dtype=torch_dtype)
pipe = StableDiffusionControlNetImg2ImgPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5", # Use a model compatible with ControlNet
controlnet=controlnet,
torch_dtype=torch_dtype
)
Enable GPU if available
device = "cuda" if torch.cuda.is_available() else "cpu"
pipe.to(device)
Initialize OpenposeDetector
openpose = OpenposeDetector()
Helper function for image editing with AI models
def apply_modifications(image, text_prompt, resolution, custom_res, model_choice, image_history):
try:
# Use the text prompt directly
parsed_prompt = text_prompt
# Prepare image for processing based on selected resolution
width, height = image.size
aspect_ratio = width / height
if resolution == "low":
new_size = (int(width // 2), int(height // 2))
elif resolution == "mid":
new_size = (width, height)
elif resolution == "high":
new_size = (int(width * 2), int(height * 2))
elif resolution == "custom":
new_width = int(custom_res)
new_height = int(new_width / aspect_ratio)
new_size = (new_width, new_height)
else:
new_size = (width, height)
image = image.resize(new_size)
# Use ControlNet to generate control image (pose map) from input image
control_image = openpose(image)
# Convert control_image to numpy array and normalize
control_image = np.array(control_image)
control_image = control_image.astype(np.float32) / 255.0
control_image = torch.from_numpy(control_image).permute(2, 0, 1).unsqueeze(0).to(device)
# Convert input image to tensor
init_image = image.convert("RGB")
init_image = init_image.resize(new_size)
init_image = np.array(init_image).astype(np.float32) / 255.0
init_image = torch.from_numpy(init_image).permute(2, 0, 1).unsqueeze(0).to(device)
# Use the pipeline to generate the edited image
edited_image = pipe(
prompt=parsed_prompt,
control_image=control_image,
image=init_image,
num_inference_steps=50,
guidance_scale=7.5,
).images[0]
# Save image for undo/redo functionality
image_history.append(edited_image)
return edited_image, image_history
except Exception as e:
print(f"Error: {e}")
# Return the original image in case of error
if image_history:
return image_history[-1], image_history
else:
return image, image_history
Undo functionality
def undo_last_edit(image_history):
if image_history and len(image_history) > 1:
image_history.pop() # Remove last edit
return image_history[-1], image_history # Return the last valid image
elif image_history:
return image_history[0], image_history
else:
return None, image_history
Batch processing of multiple images
def process_batch(files, text_prompt, resolution, custom_res, model_choice):
results = []
for file in files:
img = Image.open(file)
edited_image, _ = apply_modifications(img, text_prompt, resolution, custom_res, model_choice, [])
results.append(edited_image)
return results
Zoom functionality with drag-select (Placeholder)
def zoom_and_select(image, zoom_factor, select_area=None):
width, height = image.size
new_size = (int(width * zoom_factor), int(height * zoom_factor))
image = image.resize(new_size)
if select_area:
draw = ImageDraw.Draw(image)
draw.rectangle(select_area, outline="red", width=5)
return image
Automatically clear uploaded and processed images after processing
def clear_images():
return [], "Images cleared from memory."
Auto-prompt suggestions based on common user queries
def suggest_prompts():
return ["Increase hip size by 10%", "Slim down waist", "Enhance chest size", "Tone thighs"]
Update text prompt based on suggestion
def update_text_prompt(selected_prompt):
return gr.update(value=selected_prompt)
Gradio UI for Testing
with gr.Blocks() as demo:
gr.Markdown("## Test AI-Powered Image Editing Tool")
# Initialize Gradio State for image history
image_history = gr.State([])
# Single Image Test Tab
with gr.Tab("Single Image Test"):
with gr.Row():
image_input = gr.Image(type="pil", label="Upload Image for Testing")
text_prompt = gr.Textbox(label="Enter modification prompt for testing", placeholder="e.g., 'Increase hip size by 10%'")
with gr.Row():
resolution = gr.Radio(choices=["low", "mid", "high", "custom"], label="Resolution", value="mid")
custom_res = gr.Number(label="Custom Resolution Width (Max: 2048px)", value=1024)
model_choice = gr.Dropdown(choices=["Stable Diffusion + ControlNet"], label="Model Choice", value="Stable Diffusion + ControlNet")
# Zoom & Selection (Placeholder components)
zoom_factor = gr.Slider(label="Zoom", minimum=1, maximum=4, step=0.1, value=1, visible=False)
select_area = gr.Image(type="pil", label="Select Area (Optional)", visible=False)
# Buttons for processing and undo/redo
process_button = gr.Button("Test Process Image")
undo_button = gr.Button("Undo Last Edit (Test)")
# Output image display
output_image = gr.Image(label="Processed Test Image")
# Action: process when button is clicked
process_button.click(
fn=apply_modifications,
inputs=[image_input, text_prompt, resolution, custom_res, model_choice, image_history],
outputs=[output_image, image_history]
)
undo_button.click(
fn=undo_last_edit,
inputs=[image_history],
outputs=[output_image, image_history]
)
# Batch Processing Test Tab
with gr.Tab("Batch Processing Test"):
batch_images = gr.File(type="file", file_count="multiple", label="Upload Multiple Images for Test")
batch_prompt = gr.Textbox(label="Enter modification prompt for batch test", placeholder="e.g., 'Increase hip size by 10%'")
batch_resolution = gr.Radio(choices=["low", "mid", "high", "custom"], label="Resolution", value="mid")
batch_custom_res = gr.Number(label="Custom Resolution Width (Max: 2048px)", value=1024)
batch_model = gr.Dropdown(choices=["Stable Diffusion + ControlNet"], label="Model Choice", value="Stable Diffusion + ControlNet")
batch_process_button = gr.Button("Test Process Batch")
batch_output = gr.Gallery(label="Processed Test Images")
batch_process_button.click(
fn=process_batch,
inputs=[batch_images, batch_prompt, batch_resolution, batch_custom_res, batch_model],
outputs=batch_output
)
# Default Templates Test Tab
with gr.Tab("Default Templates Test"):
gr.Markdown("### One-click body-type modifications (Test)")
with gr.Row():
image_input_template = gr.Image(type="pil", label="Upload Image for Template Testing")
skinny_button = gr.Button("Skinny (Test)")
athletic_button = gr.Button("Athletic (Test)")
busty_button = gr.Button("Busty (Test)")
# Output image display for templates
template_output = gr.Image(label="Template Result (Test)")
# Define functions for template buttons
def apply_template(image, prompt):
edited_image, _ = apply_modifications(image, prompt, "mid", 1024, "Stable Diffusion + ControlNet", [])
return edited_image
skinny_button.click(fn=lambda img: apply_template(img, "Slim down and tone body"), inputs=image_input_template, outputs=template_output)
athletic_button.click(fn=lambda img: apply_template(img, "Tighten waist and increase muscle tone"), inputs=image_input_template, outputs=template_output)
busty_button.click(fn=lambda img: apply_template(img, "Enhance chest size"), inputs=image_input_template, outputs=template_output)
# Suggestion Prompts for Testing
prompt_suggestions = gr.Dropdown(label="Suggested Prompts (Test)", choices=suggest_prompts())
prompt_suggestions.change(fn=update_text_prompt, inputs=prompt_suggestions, outputs=text_prompt)
# Clear images button for testing
clear_button = gr.Button("Start Again (Test)")
clear_output = gr.Textbox(visible=False)
clear_button.click(fn=clear_images, outputs=[image_history, clear_output])
Launch the app for testing
demo.launch()