Rishab7310 commited on
Commit
08c01a4
Β·
verified Β·
1 Parent(s): 5e5b582

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -172
app.py CHANGED
@@ -1,6 +1,6 @@
1
  """
2
  Hugging Face Spaces App for Kolam AI Generator
3
- Interactive web interface for generating Kolam designs
4
  """
5
 
6
  import gradio as gr
@@ -8,10 +8,9 @@ import torch
8
  import numpy as np
9
  import matplotlib.pyplot as plt
10
  from PIL import Image
11
- import io
12
- import base64
13
  from pathlib import Path
14
  import sys
 
15
 
16
  # Add project paths
17
  sys.path.insert(0, str(Path(__file__).parent.parent))
@@ -21,6 +20,7 @@ from models.gan_generator import KolamGenerator
21
  from models.gan_discriminator import KolamDiscriminator
22
  from utils.metrics import KolamDesignMetrics
23
 
 
24
  class KolamAIGenerator:
25
  def __init__(self):
26
  """Initialize the Kolam AI Generator."""
@@ -45,100 +45,105 @@ class KolamAIGenerator:
45
  image_size=64
46
  )
47
 
48
- # Set to evaluation mode
 
 
 
 
 
 
 
 
 
 
49
  self.generator.eval()
50
  self.discriminator.eval()
51
 
52
- print("βœ… Models loaded successfully!")
53
-
54
  except Exception as e:
55
  print(f"❌ Error loading models: {e}")
56
- # Create dummy models for demo
57
  self.generator = KolamGenerator(100, 128, 1, 64)
58
  self.generator.eval()
59
 
60
- def generate_kolam(self, complexity, symmetry, seed=None):
61
  """Generate a Kolam design with specified parameters."""
62
  try:
63
- # Set random seed for reproducibility
64
  if seed is not None:
 
 
 
 
65
  torch.manual_seed(seed)
66
  np.random.seed(seed)
67
 
68
  # Generate random noise
69
- noise = torch.randn(1, 10000)
70
 
71
  # Adjust noise based on complexity
72
  if complexity == "Simple":
73
  noise = noise * 0.5
 
 
74
  elif complexity == "Complex":
75
- noise = noise * 1.5
76
 
77
  # Generate Kolam
78
  with torch.no_grad():
79
  generated_kolam = self.generator(noise)
80
 
81
- # Convert to numpy
82
  kolam_image = generated_kolam.squeeze().cpu().numpy()
83
- kolam_image = (kolam_image + 1) / 2 # Convert to [0,1]
84
  kolam_image = np.clip(kolam_image, 0, 1)
85
 
86
- # Apply symmetry if requested
87
  if symmetry == "High":
88
- # Enhance symmetry
89
  kolam_image = self.enhance_symmetry(kolam_image)
90
 
91
  # Convert to PIL Image
92
- kolam_pil = Image.fromarray((kolam_image * 255).astype(np.uint8), mode='L')
 
 
 
 
93
 
94
  return kolam_pil
95
 
96
  except Exception as e:
97
  print(f"❌ Error generating Kolam: {e}")
98
- # Return a simple pattern as fallback
99
  return self.create_fallback_pattern()
100
 
101
  def enhance_symmetry(self, image):
102
- """Enhance the symmetry of the generated image."""
103
- # Create horizontal symmetry
104
- left_half = image[:, :image.shape[1]//2]
105
- right_half = np.fliplr(left_half)
106
- image[:, image.shape[1]//2:] = right_half
107
 
108
- # Create vertical symmetry
109
- top_half = image[:image.shape[0]//2, :]
110
- bottom_half = np.flipud(top_half)
111
- image[image.shape[0]//2:, :] = bottom_half
112
 
113
- return image
114
 
115
  def create_fallback_pattern(self):
116
- """Create a simple fallback pattern."""
117
- # Create a simple geometric pattern
118
  size = 64
119
  pattern = np.zeros((size, size), dtype=np.float32)
120
-
121
- # Draw concentric circles
122
  center = size // 2
123
  for radius in range(5, center, 8):
124
  y, x = np.ogrid[:size, :size]
125
  mask = (x - center)**2 + (y - center)**2 <= radius**2
126
  pattern[mask] = 1.0
127
-
128
  return Image.fromarray((pattern * 255).astype(np.uint8), mode='L')
129
 
130
  def analyze_quality(self, image):
131
  """Analyze the quality of the generated Kolam."""
132
  try:
133
- # Convert PIL to numpy
134
  if isinstance(image, Image.Image):
135
  image_array = np.array(image) / 255.0
136
  else:
137
  image_array = image
138
-
139
- # Calculate quality metrics
140
  quality = self.metrics.calculate_overall_quality(image_array)
141
-
142
  return {
143
  "Overall Quality": f"{quality['overall_quality']:.3f}",
144
  "Horizontal Symmetry": f"{quality['horizontal']:.3f}",
@@ -147,173 +152,60 @@ class KolamAIGenerator:
147
  "Balance": f"{quality['balance']:.3f}",
148
  "Rhythm": f"{quality['rhythm']:.3f}"
149
  }
150
-
151
  except Exception as e:
152
  print(f"❌ Error analyzing quality: {e}")
153
- return {
154
- "Overall Quality": "N/A",
155
- "Horizontal Symmetry": "N/A",
156
- "Vertical Symmetry": "N/A",
157
- "Complexity": "N/A",
158
- "Balance": "N/A",
159
- "Rhythm": "N/A"
160
- }
161
 
162
  # Initialize the generator
163
  kolam_ai = KolamAIGenerator()
164
 
165
  def generate_and_analyze(complexity, symmetry, seed):
166
- """Generate Kolam and analyze its quality."""
167
- # Generate Kolam
168
- kolam_image = kolam_ai.generate_kolam(complexity, symmetry, seed)
169
-
170
- # Analyze quality
171
  quality_metrics = kolam_ai.analyze_quality(kolam_image)
172
-
173
  return kolam_image, quality_metrics
174
 
 
175
  def create_interface():
176
- """Create the Gradio interface."""
177
-
178
- # Custom CSS for better styling
179
  css = """
180
- .gradio-container {
181
- font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
182
- }
183
- .title {
184
- text-align: center;
185
- color: #2E86AB;
186
- margin-bottom: 20px;
187
- }
188
- .description {
189
- text-align: center;
190
- color: #666;
191
- margin-bottom: 30px;
192
- }
193
  """
194
 
195
  with gr.Blocks(css=css, title="Kolam AI Generator") as interface:
196
-
197
- # Header
198
  gr.HTML("""
199
  <div class="title">
200
  <h1>🎨 Kolam AI Generator</h1>
201
- <p class="description">
202
- Generate beautiful traditional Indian Kolam designs using AI
203
- </p>
204
  </div>
205
  """)
206
 
207
  with gr.Row():
208
  with gr.Column(scale=1):
209
- # Input controls
210
- gr.Markdown("### πŸŽ›οΈ Generation Controls")
211
-
212
- complexity = gr.Dropdown(
213
- choices=["Simple", "Medium", "Complex"],
214
- value="Medium",
215
- label="Pattern Complexity",
216
- info="Controls the intricacy of the design"
217
- )
218
-
219
- symmetry = gr.Dropdown(
220
- choices=["Low", "Medium", "High"],
221
- value="Medium",
222
- label="Symmetry Level",
223
- info="Controls the geometric balance"
224
- )
225
-
226
- seed = gr.Number(
227
- value=None,
228
- label="Random Seed (Optional)",
229
- info="Set a seed for reproducible results"
230
- )
231
-
232
- generate_btn = gr.Button(
233
- "🎨 Generate Kolam",
234
- variant="primary",
235
- size="lg"
236
- )
237
 
238
  with gr.Column(scale=2):
239
- # Output
240
  gr.Markdown("### πŸ–ΌοΈ Generated Kolam")
241
-
242
- output_image = gr.Image(
243
- label="Generated Design",
244
- type="pil",
245
- height=400
246
- )
247
-
248
- # Quality metrics
249
  gr.Markdown("### πŸ“Š Quality Analysis")
250
-
251
- quality_output = gr.JSON(
252
- label="Design Quality Metrics",
253
- value={}
254
- )
255
-
256
- # Examples
257
- gr.Markdown("### 🌟 Example Generations")
258
-
259
- examples = gr.Examples(
260
- examples=[
261
- ["Simple", "High", 42],
262
- ["Medium", "Medium", 123],
263
- ["Complex", "Low", 456],
264
- ["Complex", "High", 789]
265
- ],
266
- inputs=[complexity, symmetry, seed],
267
- label="Try these examples:"
268
- )
269
-
270
- # Information section
271
- with gr.Accordion("ℹ️ About Kolam AI Generator", open=False):
272
- gr.Markdown("""
273
- ## What is Kolam?
274
- Kolam is a traditional Indian floor art created using rice flour, chalk, or colored powders.
275
- It features intricate geometric designs and is used in daily rituals and festivals.
276
-
277
- ## How it Works
278
- - **Generator Network**: Creates Kolam designs from random noise
279
- - **Discriminator Network**: Ensures realistic pattern generation
280
- - **Quality Metrics**: Analyzes symmetry, complexity, and balance
281
-
282
- ## Technical Details
283
- - **Framework**: PyTorch
284
- - **Architecture**: Generative Adversarial Network (GAN)
285
- - **Input**: Random noise (100 dimensions)
286
- - **Output**: 64x64 grayscale Kolam image
287
- - **Generation Time**: <1 second
288
-
289
- ## Quality Metrics
290
- - **Symmetry**: Horizontal and vertical balance
291
- - **Complexity**: Pattern intricacy and density
292
- - **Balance**: Visual weight distribution
293
- - **Rhythm**: Pattern repetition and flow
294
- """)
295
 
296
- # Event handlers
297
- generate_btn.click(
298
- fn=generate_and_analyze,
299
- inputs=[complexity, symmetry, seed],
300
- outputs=[output_image, quality_output]
301
- )
302
 
303
- # Auto-generate on load
304
- interface.load(
305
- fn=lambda: generate_and_analyze("Medium", "Medium", None),
306
- outputs=[output_image, quality_output]
307
- )
308
 
309
  return interface
310
 
311
- # Create and launch the interface
312
  if __name__ == "__main__":
313
  interface = create_interface()
314
- interface.launch(
315
- server_name="0.0.0.0",
316
- server_port=7860,
317
- share=True,
318
- show_error=True
319
- )
 
1
  """
2
  Hugging Face Spaces App for Kolam AI Generator
3
+ Improved version: more beautiful & diverse Kolams
4
  """
5
 
6
  import gradio as gr
 
8
  import numpy as np
9
  import matplotlib.pyplot as plt
10
  from PIL import Image
 
 
11
  from pathlib import Path
12
  import sys
13
+ import matplotlib.cm as cm # for color mapping
14
 
15
  # Add project paths
16
  sys.path.insert(0, str(Path(__file__).parent.parent))
 
20
  from models.gan_discriminator import KolamDiscriminator
21
  from utils.metrics import KolamDesignMetrics
22
 
23
+
24
  class KolamAIGenerator:
25
  def __init__(self):
26
  """Initialize the Kolam AI Generator."""
 
45
  image_size=64
46
  )
47
 
48
+ # Try to load pretrained weights
49
+ weights_path = Path("models/generator.pth")
50
+ if weights_path.exists():
51
+ self.generator.load_state_dict(
52
+ torch.load(weights_path, map_location="cpu")
53
+ )
54
+ print("βœ… Loaded pretrained generator weights!")
55
+ else:
56
+ print("⚠️ No pretrained weights found, using untrained model.")
57
+
58
+ # Set eval mode
59
  self.generator.eval()
60
  self.discriminator.eval()
61
 
 
 
62
  except Exception as e:
63
  print(f"❌ Error loading models: {e}")
 
64
  self.generator = KolamGenerator(100, 128, 1, 64)
65
  self.generator.eval()
66
 
67
+ def generate_kolam(self, complexity, symmetry, seed=None, use_color=True):
68
  """Generate a Kolam design with specified parameters."""
69
  try:
70
+ # Set random seed
71
  if seed is not None:
72
+ torch.manual_seed(int(seed))
73
+ np.random.seed(int(seed))
74
+ else:
75
+ seed = np.random.randint(0, 100000)
76
  torch.manual_seed(seed)
77
  np.random.seed(seed)
78
 
79
  # Generate random noise
80
+ noise = torch.randn(1, 100)
81
 
82
  # Adjust noise based on complexity
83
  if complexity == "Simple":
84
  noise = noise * 0.5
85
+ elif complexity == "Medium":
86
+ noise = noise * 1.0 + torch.randn_like(noise) * 0.3
87
  elif complexity == "Complex":
88
+ noise = noise * 1.5 + torch.randn_like(noise) * 0.5
89
 
90
  # Generate Kolam
91
  with torch.no_grad():
92
  generated_kolam = self.generator(noise)
93
 
94
+ # Convert to numpy [0,1]
95
  kolam_image = generated_kolam.squeeze().cpu().numpy()
96
+ kolam_image = (kolam_image + 1) / 2
97
  kolam_image = np.clip(kolam_image, 0, 1)
98
 
99
+ # Apply symmetry
100
  if symmetry == "High":
 
101
  kolam_image = self.enhance_symmetry(kolam_image)
102
 
103
  # Convert to PIL Image
104
+ if use_color:
105
+ kolam_colored = cm.viridis(kolam_image)[:, :, :3] # RGB colormap
106
+ kolam_pil = Image.fromarray((kolam_colored * 255).astype(np.uint8))
107
+ else:
108
+ kolam_pil = Image.fromarray((kolam_image * 255).astype(np.uint8), mode='L')
109
 
110
  return kolam_pil
111
 
112
  except Exception as e:
113
  print(f"❌ Error generating Kolam: {e}")
 
114
  return self.create_fallback_pattern()
115
 
116
  def enhance_symmetry(self, image):
117
+ """Enhance symmetry with mirror + rotation."""
118
+ # Horizontal + vertical flip
119
+ img_sym = (image + np.fliplr(image)) / 2
120
+ img_sym = (img_sym + np.flipud(img_sym)) / 2
 
121
 
122
+ # Add rotational symmetry (90 degrees)
123
+ rotated = np.rot90(image)
124
+ img_sym = (img_sym + rotated) / 2
 
125
 
126
+ return np.clip(img_sym, 0, 1)
127
 
128
  def create_fallback_pattern(self):
129
+ """Fallback: simple geometric pattern."""
 
130
  size = 64
131
  pattern = np.zeros((size, size), dtype=np.float32)
 
 
132
  center = size // 2
133
  for radius in range(5, center, 8):
134
  y, x = np.ogrid[:size, :size]
135
  mask = (x - center)**2 + (y - center)**2 <= radius**2
136
  pattern[mask] = 1.0
 
137
  return Image.fromarray((pattern * 255).astype(np.uint8), mode='L')
138
 
139
  def analyze_quality(self, image):
140
  """Analyze the quality of the generated Kolam."""
141
  try:
 
142
  if isinstance(image, Image.Image):
143
  image_array = np.array(image) / 255.0
144
  else:
145
  image_array = image
 
 
146
  quality = self.metrics.calculate_overall_quality(image_array)
 
147
  return {
148
  "Overall Quality": f"{quality['overall_quality']:.3f}",
149
  "Horizontal Symmetry": f"{quality['horizontal']:.3f}",
 
152
  "Balance": f"{quality['balance']:.3f}",
153
  "Rhythm": f"{quality['rhythm']:.3f}"
154
  }
 
155
  except Exception as e:
156
  print(f"❌ Error analyzing quality: {e}")
157
+ return {k: "N/A" for k in [
158
+ "Overall Quality", "Horizontal Symmetry",
159
+ "Vertical Symmetry", "Complexity",
160
+ "Balance", "Rhythm"
161
+ ]}
162
+
 
 
163
 
164
  # Initialize the generator
165
  kolam_ai = KolamAIGenerator()
166
 
167
  def generate_and_analyze(complexity, symmetry, seed):
168
+ kolam_image = kolam_ai.generate_kolam(complexity, symmetry, seed, use_color=True)
 
 
 
 
169
  quality_metrics = kolam_ai.analyze_quality(kolam_image)
 
170
  return kolam_image, quality_metrics
171
 
172
+
173
  def create_interface():
 
 
 
174
  css = """
175
+ .gradio-container { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
176
+ .title { text-align: center; color: #2E86AB; margin-bottom: 20px; }
177
+ .description { text-align: center; color: #666; margin-bottom: 30px; }
 
 
 
 
 
 
 
 
 
 
178
  """
179
 
180
  with gr.Blocks(css=css, title="Kolam AI Generator") as interface:
 
 
181
  gr.HTML("""
182
  <div class="title">
183
  <h1>🎨 Kolam AI Generator</h1>
184
+ <p class="description">Generate beautiful traditional Indian Kolam designs using AI</p>
 
 
185
  </div>
186
  """)
187
 
188
  with gr.Row():
189
  with gr.Column(scale=1):
190
+ gr.Markdown("### πŸŽ›οΈ Controls")
191
+ complexity = gr.Dropdown(["Simple", "Medium", "Complex"], value="Medium", label="Pattern Complexity")
192
+ symmetry = gr.Dropdown(["Low", "Medium", "High"], value="Medium", label="Symmetry Level")
193
+ seed = gr.Number(value=None, label="Random Seed (Optional)")
194
+ generate_btn = gr.Button("🎨 Generate Kolam", variant="primary", size="lg")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
 
196
  with gr.Column(scale=2):
 
197
  gr.Markdown("### πŸ–ΌοΈ Generated Kolam")
198
+ output_image = gr.Image(label="Generated Design", type="pil", height=400)
 
 
 
 
 
 
 
199
  gr.Markdown("### πŸ“Š Quality Analysis")
200
+ quality_output = gr.JSON(label="Design Quality Metrics", value={})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
 
202
+ generate_btn.click(fn=generate_and_analyze, inputs=[complexity, symmetry, seed], outputs=[output_image, quality_output])
 
 
 
 
 
203
 
204
+ interface.load(fn=lambda: generate_and_analyze("Medium", "Medium", None), outputs=[output_image, quality_output])
 
 
 
 
205
 
206
  return interface
207
 
208
+
209
  if __name__ == "__main__":
210
  interface = create_interface()
211
+ interface.launch(server_name="0.0.0.0", server_port=7860, share=True, show_error=True)