Spaces:
Runtime error
Runtime error
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485import gradio as grfrom diffusers import StableDiffusionXLImg2ImgPipelineimport torch# Load a lightweight pipeline that works well on CPUdef load_image_generator():try:model = StableDiffusionXLImg2ImgPipeline.from_pretrained("stabilityai/stable-diffusion-2-1",torch_dtype=torch.float16,variant="fp16",use_safetensors=True)# Ensure it runs on CPU#model = model.to("cpu")return modelexcept Exception as e:print(f"Error loading model: {e}")return None# Generate chatbot icondef generate_chatbot_icon(prompt,negative_prompt="low quality, bad composition, blurry",num_inference_steps=20,guidance_scale=7.5,strength=0.75):# Load the modelmodel = load_image_generator()if model is None:return None# Default icon if no initial imagedefault_init_image = torch.randn((1, 3, 512, 512))try:# Generate the imageimage = model(prompt=prompt,negative_prompt=negative_prompt,num_inference_steps=num_inference_steps,guidance_scale=guidance_scale,strength=strength,image=default_init_image).images[0]return imageexcept Exception as e:print(f"Error generating image: {e}")return None# Create Gradio interfacedef create_gradio_interface():with gr.Blocks() as demo:gr.Markdown("# 🤖 Chatbot Icon Generator")with gr.Row():with gr.Column():# Prompt inputprompt = gr.Textbox(label="Icon Description",value="Cute minimalist chatbot avatar, clean design, friendly expression, cartoon style")# Generate buttongenerate_btn = gr.Button("Generate Icon")with gr.Column():# Output imageoutput_image = gr.Image(label="Generated Chatbot Icon")# Connect generate button to functiongenerate_btn.click(fn=generate_chatbot_icon,inputs=[prompt],outputs=[output_image])return demo# Launch the appif __name__ == "__main__":demo = create_gradio_interface()demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195import gradio as grimport torchfrom diffusers import StableDiffusionXLImg2ImgPipelinefrom PIL import Image, ImageOpsclass ChatbotIconGenerator:def __init__(self):# Predefined size optionsself.SIZE_OPTIONS = {"Small (128x128)": 128,"Medium (256x256)": 256,"Large (512x512)": 512,"Extra Large (1024x1024)": 1024}# Predefined prompt templatesself.PROMPT_TEMPLATES = [# Professional/Corporate"Professional AI chatbot avatar, minimalist design, sleek geometric shapes, corporate blue and white color palette","Elegant corporate chatbot icon, modern flat design, clean lines, subtle technology motif",# Cute/Friendly"Cute cartoon chatbot mascot, big eyes, friendly smile, pastel colors, kawaii style","Adorable robot character avatar, round shape, soft colors, playful expression",# Sci-Fi/Tech"Futuristic AI chatbot icon, glowing circuit patterns, metallic blue and silver, high-tech aesthetic","Cyberpunk chatbot avatar, neon accents, digital glitch effects, modern tech design",# Minimalist"Ultra-minimalist chatbot icon, simple geometric face, monochrome color scheme","Abstract geometric chatbot avatar, clean lines, single color gradient background",# Artistic"Watercolor style chatbot icon, soft brush strokes, dreamy color blend, artistic interpretation","Sketch-style chatbot avatar, hand-drawn look, pencil texture, artistic rendering"]# Rounding optionsself.CORNER_OPTIONS = {"No Rounding": 0,"Slight Rounding": 20,"Medium Rounding": 50,"Full Rounded": 100}# Load the modelself.model = self.load_image_generator()def load_image_generator(self):try:model = StableDiffusionXLImg2ImgPipeline.from_pretrained("stabilityai/stable-diffusion-2-1",torch_dtype=torch.float16,variant="fp16",use_safetensors=True)return model.to("cpu")except Exception as e:print(f"Error loading model: {e}")return Nonedef round_image_corners(self, image, corner_radius):# Create a rounded corner maskif corner_radius == 0:return image# Create a new image with an alpha channelrounded_image = Image.new('RGBA', image.size, (0, 0, 0, 0))# Create a mask for rounded cornersmask = Image.new('L', image.size, 255)from PIL import ImageDrawdraw = ImageDraw.Draw(mask)# Draw rounded rectangledraw.rounded_rectangle([0, 0, image.width-1, image.height-1],radius=corner_radius,fill=255)# Paste the original image with the maskrounded_image.paste(image, mask=mask)return rounded_imagedef generate_chatbot_icon(self,prompt,size,corner_rounding,negative_prompt="low quality, bad composition, blurry, ugly",num_inference_steps=25,guidance_scale=8.0,strength=0.75):if self.model is None:return Nonetry:# Create a random initial image of specified sizedefault_init_image = torch.randn((1, 3, size, size))# Generate the imagegenerated_image = self.model(prompt=prompt,negative_prompt=negative_prompt,num_inference_steps=num_inference_steps,guidance_scale=guidance_scale,strength=strength,image=default_init_image).images[0]# Resize and round cornersgenerated_image = generated_image.resize((size, size))rounded_image = self.round_image_corners(generated_image,self.CORNER_OPTIONS[corner_rounding])return rounded_imageexcept Exception as e:print(f"Error generating image: {e}")return Nonedef create_gradio_interface(self):with gr.Blocks(title="🤖 Chatbot Icon Generator") as demo:gr.Markdown("# 🤖 Chatbot Icon Generator")with gr.Row():with gr.Column():# Prompt selectionprompt_dropdown = gr.Dropdown(label="Quick Templates",choices=self.PROMPT_TEMPLATES,allow_custom_value=True)# Custom prompt inputcustom_prompt = gr.Textbox(label="Custom Prompt (Optional)",placeholder="Enter your own detailed description...")# Size selectionsize_dropdown = gr.Dropdown(label="Icon Size",choices=list(self.SIZE_OPTIONS.keys()),value="Medium (256x256)")# Corner roundingcorner_dropdown = gr.Dropdown(label="Corner Rounding",choices=list(self.CORNER_OPTIONS.keys()),value="Slight Rounding")# Generate buttongenerate_btn = gr.Button("Generate Icon", variant="primary")with gr.Column():# Output imageoutput_image = gr.Image(label="Generated Chatbot Icon")# Logic for prompt selectiondef update_prompt(template):return templateprompt_dropdown.change(fn=update_prompt,inputs=[prompt_dropdown],outputs=[custom_prompt])# Generate button logicgenerate_btn.click(fn=lambda prompt, size, corners: self.generate_chatbot_icon(prompt or "Cute minimalist chatbot avatar, clean design, friendly expression",self.SIZE_OPTIONS[size],corners),inputs=[custom_prompt, size_dropdown, corner_dropdown],outputs=[output_image])return demo# Launch the appdef main():generator = ChatbotIconGenerator()demo = generator.create_gradio_interface()demo.launch()if __name__ == "__main__":main()
app.py+182-72