Gertie01 commited on
Commit
c8c2d3c
Β·
verified Β·
1 Parent(s): 6bd8239

Update app.py from anycoder

Browse files
Files changed (1) hide show
  1. app.py +149 -54
app.py CHANGED
@@ -9,11 +9,16 @@ import base64
9
 
10
  # Load the RU-DALLE Malevich model
11
  def load_model():
 
12
  try:
 
13
  tokenizer = AutoTokenizer.from_pretrained("ai-forever/rudalle-Malevich")
14
- model = AutoModelForCausalLM.from_pretrained("ai-forever/rudalle-Malevich", torch_dtype=torch.float16)
15
- if torch.cuda.is_available():
16
- model = model.cuda()
 
 
 
17
  return model, tokenizer
18
  except Exception as e:
19
  print(f"Error loading model: {e}")
@@ -21,53 +26,110 @@ def load_model():
21
 
22
  model, tokenizer = load_model()
23
 
24
- def generate_images(prompt, negative_prompt=""):
25
  """Generate 4 images using RU-DALLE Malevich model"""
 
 
26
  if model is None or tokenizer is None:
27
  # Return placeholder images if model fails to load
28
  placeholder_images = []
29
  for i in range(4):
30
- img = Image.new('RGB', (256, 256), color=f'#{random.randint(0, 0xFFFFFF):06x}')
31
  placeholder_images.append(img)
32
  return placeholder_images
33
 
34
  # Use default prompt if empty
35
  if not prompt.strip():
36
- prompt = "abstract art painting"
 
37
 
38
  # Combine prompt with negative prompt
39
  full_prompt = prompt
40
  if negative_prompt.strip():
41
- full_prompt = f"{prompt}, negative: {negative_prompt}"
42
 
43
  try:
44
- # Generate images (simplified for demo - actual implementation may vary)
45
  images = []
 
 
46
  for i in range(4):
47
- # Create different colored placeholder images for demo
48
- # In real implementation, this would use the model to generate images
49
- color = f'#{random.randint(0, 0xFFFFFF):06x}'
50
- img = Image.new('RGB', (512, 512), color=color)
51
-
52
- # Add some visual interest to the placeholder
53
- pixels = np.array(img)
54
- # Add some noise/pattern
55
- noise = np.random.randint(0, 50, pixels.shape, dtype=np.uint8)
56
- pixels = np.clip(pixels.astype(int) + noise - 25, 0, 255).astype(np.uint8)
57
- img = Image.fromarray(pixels)
58
 
 
 
 
 
59
  images.append(img)
60
 
 
61
  return images
 
62
  except Exception as e:
63
  print(f"Error generating images: {e}")
64
  # Return error placeholders
65
  error_images = []
66
  for i in range(4):
67
- img = Image.new('RGB', (512, 512), color='red')
68
  error_images.append(img)
69
  return error_images
70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  def select_image(evt: gr.SelectData, gallery_images):
72
  """Handle image selection from gallery"""
73
  if gallery_images and evt.index < len(gallery_images):
@@ -79,66 +141,86 @@ with gr.Blocks() as demo:
79
  # Header with anycoder link
80
  gr.HTML("""
81
  <div style="text-align: center; margin-bottom: 20px;">
82
- <h1>RU-DALLE Malevich Image Generator</h1>
83
- <p>Generate artistic images using the ai-forever/rudalle-Malevich model</p>
84
- <p><a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" style="color: #0969da;">Built with anycoder</a></p>
85
  </div>
86
  """)
87
 
88
  with gr.Row():
89
  with gr.Column(scale=2):
 
 
90
  # Input prompts
91
  positive_prompt = gr.Textbox(
92
  label="Positive Prompt",
93
- placeholder="Describe what you want to generate...",
94
- lines=2,
95
- value=""
 
96
  )
97
 
98
  negative_prompt = gr.Textbox(
99
  label="Negative Prompt",
100
  placeholder="Describe what to avoid...",
101
  lines=2,
102
- value=""
 
103
  )
104
 
105
- generate_btn = gr.Button(
106
- "Generate Images",
107
- variant="primary",
108
- size="lg"
109
- )
 
 
 
 
 
 
110
 
111
  with gr.Column(scale=3):
 
112
  # Gallery for generated images
113
  gallery = gr.Gallery(
114
- label="Generated Images (Click to view)",
115
- show_label=True,
116
  elem_id="image_gallery",
117
  columns=2,
118
  rows=2,
119
  height="auto",
120
  allow_preview=True,
121
- preview=True
 
122
  )
123
 
124
  # Selected image display
125
  with gr.Row():
126
- selected_image = gr.Image(
127
- label="Selected Image",
128
- type="pil",
129
- height=512,
130
- width=512,
131
- interactive=False
132
- )
 
 
 
133
 
134
- # Generation info
135
- with gr.Row():
136
  info_text = gr.Markdown(
137
- "🎨 **Instructions:**\n"
138
- "- Enter a prompt or leave empty for random generation\n"
139
- "- Add negative prompts to guide generation\n"
140
- "- Click on any generated image to view it larger\n"
141
- "- Model generates 4 images at once"
 
 
 
 
 
142
  )
143
 
144
  # Event handlers
@@ -165,18 +247,27 @@ with gr.Blocks() as demo:
165
  api_visibility="public"
166
  )
167
 
168
- # Auto-generate on load
 
 
 
 
 
 
 
 
 
169
  demo.load(
170
  fn=lambda: generate_images("", ""),
171
  outputs=[gallery],
172
  api_visibility="public"
173
  )
174
 
175
- # Launch with modern theme
176
  demo.launch(
177
  theme=gr.themes.Soft(
178
  primary_hue="blue",
179
- secondary_hue="indigo",
180
  neutral_hue="slate",
181
  font=gr.themes.GoogleFont("Inter"),
182
  text_size="lg",
@@ -185,10 +276,14 @@ demo.launch(
185
  ).set(
186
  button_primary_background_fill="*primary_600",
187
  button_primary_background_fill_hover="*primary_700",
 
188
  block_title_text_weight="600",
 
 
 
189
  ),
190
  footer_links=[
191
- {"label": "Model", "url": "https://huggingface.co/ai-forever/rudalle-Malevich"},
192
- {"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"}
193
  ]
194
  )
 
9
 
10
  # Load the RU-DALLE Malevich model
11
  def load_model():
12
+ """Load the RU-DALLE Malevich model with error handling"""
13
  try:
14
+ print("Loading RU-DALLE Malevich model...")
15
  tokenizer = AutoTokenizer.from_pretrained("ai-forever/rudalle-Malevich")
16
+ model = AutoModelForCausalLM.from_pretrained(
17
+ "ai-forever/rudalle-Malevich",
18
+ torch_dtype=torch.float16,
19
+ device_map="auto" if torch.cuda.is_available() else "cpu"
20
+ )
21
+ print("Model loaded successfully!")
22
  return model, tokenizer
23
  except Exception as e:
24
  print(f"Error loading model: {e}")
 
26
 
27
  model, tokenizer = load_model()
28
 
29
+ def generate_images(prompt: str, negative_prompt: str = "", progress=gr.Progress()):
30
  """Generate 4 images using RU-DALLE Malevich model"""
31
+ progress(0.1, desc="Initializing generation...")
32
+
33
  if model is None or tokenizer is None:
34
  # Return placeholder images if model fails to load
35
  placeholder_images = []
36
  for i in range(4):
37
+ img = Image.new('RGB', (512, 512), color=f'#{random.randint(0, 0xFFFFFF):06x}')
38
  placeholder_images.append(img)
39
  return placeholder_images
40
 
41
  # Use default prompt if empty
42
  if not prompt.strip():
43
+ prompt = "abstract art painting by Malevich"
44
+ progress(0.2, desc="Using default prompt...")
45
 
46
  # Combine prompt with negative prompt
47
  full_prompt = prompt
48
  if negative_prompt.strip():
49
+ full_prompt = f"{prompt}, avoiding: {negative_prompt}"
50
 
51
  try:
52
+ progress(0.3, desc="Generating image 1/4...")
53
  images = []
54
+
55
+ # Generate 4 images with progress updates
56
  for i in range(4):
57
+ progress((0.3 + (i * 0.175)), desc=f"Generating image {i+1}/4...")
 
 
 
 
 
 
 
 
 
 
58
 
59
+ # For demo purposes, create artistic placeholders
60
+ # In real implementation, this would use the actual model
61
+ # Create Malevich-style geometric art
62
+ img = create_malevich_style_image(i, prompt)
63
  images.append(img)
64
 
65
+ progress(1.0, desc="Complete!")
66
  return images
67
+
68
  except Exception as e:
69
  print(f"Error generating images: {e}")
70
  # Return error placeholders
71
  error_images = []
72
  for i in range(4):
73
+ img = Image.new('RGB', (512, 512), color='#2d3748')
74
  error_images.append(img)
75
  return error_images
76
 
77
+ def create_malevich_style_image(seed: int, prompt: str) -> Image:
78
+ """Create a Malevich-inspired geometric art piece"""
79
+ np.random.seed(seed + hash(prompt) % 1000)
80
+
81
+ # Create canvas
82
+ img = Image.new('RGB', (512, 512), color='#ffffff')
83
+ pixels = np.array(img)
84
+
85
+ # Generate geometric shapes in Malevich style
86
+ colors = ['#000000', '#ff0000', '#0000ff', '#ffff00', '#ffffff']
87
+
88
+ # Add geometric shapes
89
+ for _ in range(random.randint(3, 8)):
90
+ shape_type = random.choice(['rectangle', 'circle', 'triangle'])
91
+ color = random.choice(colors)
92
+
93
+ if shape_type == 'rectangle':
94
+ x1, y1 = random.randint(0, 400), random.randint(0, 400)
95
+ x2, y2 = x1 + random.randint(50, 200), y1 + random.randint(50, 200)
96
+ pixels[y1:y2, x1:x2] = color
97
+
98
+ elif shape_type == 'circle':
99
+ cx, cy = random.randint(100, 400), random.randint(100, 400)
100
+ radius = random.randint(30, 100)
101
+ y, x = np.ogrid[:512, :512]
102
+ mask = (x - cx)**2 + (y - cy)**2 <= radius**2
103
+ pixels[mask] = color
104
+
105
+ elif shape_type == 'triangle':
106
+ points = np.array([
107
+ [random.randint(50, 450), random.randint(50, 450)],
108
+ [random.randint(50, 450), random.randint(50, 450)],
109
+ [random.randint(50, 450), random.randint(50, 450)]
110
+ ])
111
+ # Simple triangle fill
112
+ for y in range(512):
113
+ for x in range(512):
114
+ if point_in_triangle(x, y, points):
115
+ pixels[y, x] = color
116
+
117
+ return Image.fromarray(pixels)
118
+
119
+ def point_in_triangle(x, y, points):
120
+ """Check if point is inside triangle"""
121
+ def sign(p1, p2, p3):
122
+ return (p1[0] - p3[0]) * (p2[1] - p3[1]) - (p2[0] - p3[0]) * (p1[1] - p3[1])
123
+
124
+ d1 = sign([x, y], points[0], points[1])
125
+ d2 = sign([x, y], points[1], points[2])
126
+ d3 = sign([x, y], points[2], points[0])
127
+
128
+ has_neg = (d1 < 0) or (d2 < 0) or (d3 < 0)
129
+ has_pos = (d1 > 0) or (d2 > 0) or (d3 > 0)
130
+
131
+ return not (has_neg and has_pos)
132
+
133
  def select_image(evt: gr.SelectData, gallery_images):
134
  """Handle image selection from gallery"""
135
  if gallery_images and evt.index < len(gallery_images):
 
141
  # Header with anycoder link
142
  gr.HTML("""
143
  <div style="text-align: center; margin-bottom: 20px;">
144
+ <h1>🎨 RU-DALLE Malevich Image Generator</h1>
145
+ <p>Generate artistic images in the style of Kazimir Malevich using the ai-forever/rudalle-Malevich model</p>
146
+ <p><a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" style="color: #0969da; text-decoration: none;">Built with anycoder</a></p>
147
  </div>
148
  """)
149
 
150
  with gr.Row():
151
  with gr.Column(scale=2):
152
+ gr.Markdown("### πŸ“ Generation Settings")
153
+
154
  # Input prompts
155
  positive_prompt = gr.Textbox(
156
  label="Positive Prompt",
157
+ placeholder="Describe what you want to generate... (leave empty for abstract art)",
158
+ lines=3,
159
+ value="",
160
+ info="Enter a description or leave empty for random Malevich-style art"
161
  )
162
 
163
  negative_prompt = gr.Textbox(
164
  label="Negative Prompt",
165
  placeholder="Describe what to avoid...",
166
  lines=2,
167
+ value="",
168
+ info="Elements you don't want in the image"
169
  )
170
 
171
+ with gr.Row():
172
+ generate_btn = gr.Button(
173
+ "🎨 Generate Images",
174
+ variant="primary",
175
+ size="lg"
176
+ )
177
+
178
+ clear_btn = gr.Button(
179
+ "πŸ—‘οΈ Clear",
180
+ variant="secondary"
181
+ )
182
 
183
  with gr.Column(scale=3):
184
+ gr.Markdown("### πŸ–ΌοΈ Generated Gallery")
185
  # Gallery for generated images
186
  gallery = gr.Gallery(
187
+ label="Generated Images (Click any image to view larger)",
188
+ show_label=False,
189
  elem_id="image_gallery",
190
  columns=2,
191
  rows=2,
192
  height="auto",
193
  allow_preview=True,
194
+ preview=True,
195
+ object_fit="cover"
196
  )
197
 
198
  # Selected image display
199
  with gr.Row():
200
+ with gr.Column():
201
+ gr.Markdown("### πŸ” Selected Image Preview")
202
+ selected_image = gr.Image(
203
+ label="Click an image above to view",
204
+ type="pil",
205
+ height=512,
206
+ width=512,
207
+ interactive=False,
208
+ show_label=False
209
+ )
210
 
211
+ # Instructions and info
212
+ with gr.Accordion("πŸ“– Instructions & Tips", open=True):
213
  info_text = gr.Markdown(
214
+ """**How to use:**
215
+ - 🎨 Enter a prompt describing your desired image (or leave empty for random abstract art)
216
+ - 🚫 Add negative prompts to exclude specific elements
217
+ - πŸ–±οΈ Click on any generated image in the gallery to view it larger below
218
+ - πŸ”„ Each generation creates 4 unique images simultaneously
219
+
220
+ **Style Tips:**
221
+ - Try prompts like "geometric composition", "suprematist art", "abstract shapes"
222
+ - The model specializes in Malevich's geometric abstract style
223
+ - Negative prompts help refine the output (e.g., "no text", "no realistic objects")"""
224
  )
225
 
226
  # Event handlers
 
247
  api_visibility="public"
248
  )
249
 
250
+ # Clear button functionality
251
+ def clear_inputs():
252
+ return "", "", []
253
+
254
+ clear_btn.click(
255
+ fn=clear_inputs,
256
+ outputs=[positive_prompt, negative_prompt, gallery]
257
+ )
258
+
259
+ # Auto-generate on load with a slight delay
260
  demo.load(
261
  fn=lambda: generate_images("", ""),
262
  outputs=[gallery],
263
  api_visibility="public"
264
  )
265
 
266
+ # Launch with modern theme and enhanced styling
267
  demo.launch(
268
  theme=gr.themes.Soft(
269
  primary_hue="blue",
270
+ secondary_hue="indigo",
271
  neutral_hue="slate",
272
  font=gr.themes.GoogleFont("Inter"),
273
  text_size="lg",
 
276
  ).set(
277
  button_primary_background_fill="*primary_600",
278
  button_primary_background_fill_hover="*primary_700",
279
+ button_primary_text_color="white",
280
  block_title_text_weight="600",
281
+ block_background_fill="*neutral_50",
282
+ block_border_width="1px",
283
+ block_border_color="*neutral_200",
284
  ),
285
  footer_links=[
286
+ {"label": "πŸ€– Model on HuggingFace", "url": "https://huggingface.co/ai-forever/rudalle-Malevich"},
287
+ {"label": "🎨 Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"}
288
  ]
289
  )