njavidfar commited on
Commit
faa67e9
·
verified ·
1 Parent(s): a9f4cbb

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -111
app.py CHANGED
@@ -1,6 +1,6 @@
1
  import gradio as gr
2
  import torch
3
- from diffusers import DiffusionPipeline
4
  import logging
5
  from PIL import Image
6
  import base64
@@ -10,134 +10,64 @@ from io import BytesIO
10
  logging.basicConfig(level=logging.INFO)
11
  logger = logging.getLogger(__name__)
12
 
 
 
13
  try:
14
- logger.info("Starting model initialization...")
15
- # Initialize the FLUX model
16
- pipe = DiffusionPipeline.from_pretrained(
17
- "black-forest-labs/FLUX.1-schnell",
18
  torch_dtype=torch.float32,
19
  safety_checker=None,
20
  requires_safety_checker=False
21
  )
22
-
23
- # Force CPU usage and optimize memory
24
- pipe = pipe.to("cpu")
25
- pipe.enable_attention_slicing()
26
- logger.info("Model initialization completed successfully")
27
  except Exception as e:
28
  logger.error(f"Error during model initialization: {str(e)}")
29
  raise
30
 
31
- def generate_image(prompt: str, negative_prompt: str, style: str) -> dict:
32
  try:
33
- logger.info(f"Starting image generation with prompt: {prompt}, style: {style}")
34
-
35
- # Base negative prompt for better quality
36
- base_negative = "ugly, deformed, noisy, blurry, distorted, grainy, text, watermark, signature, frame, deformed face"
37
- negative_prompt = f"{base_negative}, {negative_prompt}" if negative_prompt else base_negative
38
-
39
- # Adjust the prompt based on style
40
- if style == "Realistic":
41
- prompt = f"ultra realistic, highly detailed photograph, professional photography, 8k uhd, muted colors, {prompt}"
42
- elif style == "Artistic":
43
- prompt = f"artistic, vibrant colors, stylized, digital art masterpiece, detailed, {prompt}"
44
- elif style == "Abstract":
45
- prompt = f"abstract, modern art, conceptual, artistic composition, cold color palette, {prompt}"
46
- elif style == "Minimalist":
47
- prompt = f"minimalist, clean lines, simple composition, elegant, muted colors, {prompt}"
48
 
49
- logger.info(f"Modified prompt: {prompt}")
50
- logger.info(f"Negative prompt: {negative_prompt}")
51
-
52
- # Generate the image
53
- with gr.Progress() as progress:
54
- progress(0, desc="Starting generation...")
55
- image = pipe(
56
- prompt=prompt,
57
- negative_prompt=negative_prompt,
58
- num_inference_steps=20,
59
- width=512,
60
- height=512,
61
- guidance_scale=7.5
62
- ).images[0]
63
- progress(1, desc="Finalizing...")
64
-
65
- logger.info("Image generation completed")
66
-
67
- # Convert PIL image to base64
68
  buffered = BytesIO()
69
  image.save(buffered, format="PNG")
70
  img_str = base64.b64encode(buffered.getvalue()).decode()
71
 
72
- return {"data": [img_str]}
73
-
74
  except Exception as e:
75
- error_msg = f"Error during image generation: {str(e)}"
76
- logger.error(error_msg)
77
- return {"error": error_msg}
78
 
79
  # Create Gradio interface
80
- with gr.Blocks(theme=gr.themes.Default()) as iface:
81
- gr.Markdown(
82
- """
83
- # 🖼 Uniwalls AI Wallpaper Generator
84
- Create beautiful wallpapers using FLUX AI. Simply describe what you want to see!
85
- """
86
- )
87
-
88
- with gr.Row():
89
- with gr.Column(scale=2):
90
- prompt = gr.Textbox(
91
- label="Prompt",
92
- placeholder="Describe what you want to generate...",
93
- lines=3
94
- )
95
- negative_prompt = gr.Textbox(
96
- label="Negative Prompt",
97
- placeholder="What you don't want to see...",
98
- lines=2
99
- )
100
- style = gr.Radio(
101
- choices=["Realistic", "Artistic", "Abstract", "Minimalist"],
102
- label="Style",
103
- value="Realistic"
104
- )
105
- generate_btn = gr.Button("🎨 Generate Wallpaper")
106
-
107
- with gr.Column(scale=3):
108
- output = gr.JSON(label="Generated Image")
109
-
110
- # Example prompts
111
- gr.Examples(
112
- examples=[
113
- ["A stunning mountain landscape at golden hour, cinematic", "people, text, watermark", "Realistic"],
114
- ["Ethereal waves of light and color in motion", "sharp edges, realistic", "Abstract"],
115
- ["Zen garden with cherry blossoms, peaceful atmosphere", "cluttered, busy", "Minimalist"],
116
- ["Magical crystal cave with glowing elements", "photorealistic, mundane", "Artistic"],
117
- ],
118
- inputs=[prompt, negative_prompt, style],
119
- outputs=output,
120
- fn=generate_image,
121
- cache_examples=True,
122
- )
123
-
124
- # Set up the generate button click event
125
- generate_btn.click(
126
- fn=generate_image,
127
- inputs=[prompt, negative_prompt, style],
128
- outputs=output,
129
- )
130
-
131
- gr.Markdown(
132
- """
133
- ### 💡 Tips for best results:
134
- - Be specific in your descriptions
135
- - Add details about lighting, atmosphere, and mood
136
- - Use the negative prompt to remove unwanted elements
137
- - Try different styles to find the perfect look
138
- - Add keywords like "cinematic", "professional", or "masterpiece"
139
- """
140
- )
141
 
142
  # Launch with basic settings
143
  if __name__ == "__main__":
 
1
  import gradio as gr
2
  import torch
3
+ from diffusers import StableDiffusionPipeline
4
  import logging
5
  from PIL import Image
6
  import base64
 
10
  logging.basicConfig(level=logging.INFO)
11
  logger = logging.getLogger(__name__)
12
 
13
+ logger.info("Starting model initialization...")
14
+
15
  try:
16
+ pipe = StableDiffusionPipeline.from_pretrained(
17
+ "stabilityai/flux-1-schnell",
 
 
18
  torch_dtype=torch.float32,
19
  safety_checker=None,
20
  requires_safety_checker=False
21
  )
22
+ pipe.enable_model_cpu_offload()
23
+ logger.info("Model initialized successfully")
 
 
 
24
  except Exception as e:
25
  logger.error(f"Error during model initialization: {str(e)}")
26
  raise
27
 
28
+ def generate_image(prompt, negative_prompt="", style=""):
29
  try:
30
+ # Enhance prompt based on style
31
+ if style:
32
+ style_prompts = {
33
+ "Realistic": "highly detailed, photorealistic, 8k resolution",
34
+ "Artistic": "artistic style, vibrant colors, creative composition",
35
+ "Abstract": "abstract art style, modern, conceptual",
36
+ "Minimalist": "minimalist style, clean lines, simple composition"
37
+ }
38
+ prompt = f"{prompt}, {style_prompts.get(style, '')}"
 
 
 
 
 
 
39
 
40
+ # Generate image
41
+ logger.info(f"Generating image with prompt: {prompt}")
42
+ image = pipe(
43
+ prompt=prompt,
44
+ negative_prompt=negative_prompt,
45
+ num_inference_steps=20,
46
+ guidance_scale=7.5
47
+ ).images[0]
48
+
49
+ # Convert to base64
 
 
 
 
 
 
 
 
 
50
  buffered = BytesIO()
51
  image.save(buffered, format="PNG")
52
  img_str = base64.b64encode(buffered.getvalue()).decode()
53
 
54
+ return {"image": f"data:image/png;base64,{img_str}"}
 
55
  except Exception as e:
56
+ logger.error(f"Error generating image: {str(e)}")
57
+ return {"error": str(e)}
 
58
 
59
  # Create Gradio interface
60
+ iface = gr.Interface(
61
+ fn=generate_image,
62
+ inputs=[
63
+ gr.Textbox(label="Prompt", placeholder="Describe the wallpaper you want to generate..."),
64
+ gr.Textbox(label="Negative Prompt", placeholder="What you don't want to see in the image..."),
65
+ gr.Dropdown(choices=["Realistic", "Artistic", "Abstract", "Minimalist"], label="Style", value="Realistic")
66
+ ],
67
+ outputs=gr.Image(type="pil"),
68
+ title="FLUX AI Wallpaper Generator",
69
+ description="Generate unique wallpapers using FLUX AI. Enter a prompt and select a style to create your custom wallpaper."
70
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
  # Launch with basic settings
73
  if __name__ == "__main__":