-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_usage.py
More file actions
453 lines (360 loc) · 15.7 KB
/
example_usage.py
File metadata and controls
453 lines (360 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
#!/usr/bin/env python3
"""
SVG Designer - Example Usage
Simple demonstration of how to use the SVG Designer components
"""
import asyncio
import os
from src.svg_generator import SVGGenerator
from src.models import SVGGenerationRequest
from src.svg_cleaner import SVGCleaner
from tests.test_utils import setup_test_session, create_standard_test_structure, get_output_manager
async def example_basic_generation():
"""Basic example of generating an SVG from text"""
print("🎨 SVG Designer - Basic Example")
print("=" * 40)
# Check for API key
if not os.getenv('OPENAI_API_KEY'):
print("❌ Please set OPENAI_API_KEY environment variable")
print(" export OPENAI_API_KEY='your-key-here'")
return
# Setup organized output
output_manager = get_output_manager()
dirs = create_standard_test_structure("basic_generation")
# Create generator
generator = SVGGenerator()
# Simple request
request = SVGGenerationRequest(
description="a simple coffee cup icon",
style="minimalist",
color_palette="monochrome",
size="1024x1024",
num_variants=1,
vector_quality="medium",
preprocess=True,
preprocess_colors=8,
preprocess_window=5,
preprocess_passes=2,
api_key=os.getenv('OPENAI_API_KEY') or ""
)
print(f"📝 Generating: {request.description}")
print(f" Style: {request.style}")
print(f" Colors: {request.color_palette}")
print(f" Preprocessing: enabled")
# Generate SVG
result = await generator.generate_svg(request, output_dir=dirs["originals"].parent)
if result['success']:
svg_content = result['variants'][0]['svg']
# Save result in organized structure
filename = "example_coffee_cup.svg"
svg_path = output_manager.save_file(
svg_content, filename, "basic_generation", "03_svgs"
)
print(f"✅ Generated: {svg_path}")
print(f" Size: {len(svg_content)} characters")
print(f" Prompt used: {result['prompt_used'][:100]}...")
# Optional: Clean the SVG further
cleaned_svg = SVGCleaner.clean_svg_artifacts(svg_content)
if len(cleaned_svg) < len(svg_content):
cleaned_filename = "example_coffee_cup_cleaned.svg"
cleaned_path = output_manager.save_file(
cleaned_svg, cleaned_filename, "basic_generation", "02_processed"
)
reduction = (1 - len(cleaned_svg) / len(svg_content)) * 100
print(f"🧹 Cleaned version: {cleaned_path} ({reduction:.1f}% smaller)")
# Create comparison report
comparison_report = f"""# Basic Generation Example Report
## Configuration
- **Description:** {request.description}
- **Style:** {request.style}
- **Color Palette:** {request.color_palette}
- **Size:** {request.size}
- **Quality:** {request.vector_quality}
- **Preprocessing:** Enabled
## Results
- **Original SVG:** {len(svg_content):,} characters
- **Cleaned SVG:** {len(cleaned_svg):,} characters
- **Reduction:** {reduction:.1f}%
## Files Generated
- Original: {filename}
- Cleaned: {cleaned_filename}
## AI Prompt Used
```
{result['prompt_used']}
```
This example demonstrates the basic workflow of the SVG Designer pipeline.
"""
report_path = output_manager.save_file(
comparison_report, "basic_generation_report.md", "basic_generation", "04_comparisons"
)
print(f"📊 Report: {report_path}")
else:
print(f"❌ Generation failed: {result['error']}")
async def example_style_comparison():
"""Example comparing different styles for the same subject"""
print("\n🎭 Style Comparison Example")
print("=" * 35)
if not os.getenv('OPENAI_API_KEY'):
print("❌ OpenAI API key required")
return
# Setup organized output for style comparison
dirs = create_standard_test_structure("style_comparison")
output_manager = get_output_manager()
generator = SVGGenerator()
# Test different styles
styles = [
{"style": "minimalist", "color_palette": "monochrome"},
{"style": "tech", "color_palette": "bold"},
{"style": "creative", "color_palette": "vibrant"}
]
base_description = "mountain peak logo"
style_results = []
for i, style_config in enumerate(styles, 1):
print(f"\n🎨 Style {i}: {style_config['style']} + {style_config['color_palette']}")
request = SVGGenerationRequest(
description=base_description,
size="1024x1024", # Smaller for faster generation
num_variants=1,
vector_quality="fast", # Faster for example
preprocess=True,
preprocess_colors=8,
preprocess_window=5,
preprocess_passes=2,
style=style_config['style'],
color_palette=style_config['color_palette'],
api_key=os.getenv('OPENAI_API_KEY') or ""
)
result = await generator.generate_svg(request, output_dir=dirs["originals"].parent)
if result['success']:
filename = f"example_mountain_{style_config['style']}.svg"
svg_path = output_manager.save_file(
result['variants'][0]['svg'], filename, "style_comparison", "03_svgs"
)
style_results.append({
'style': style_config['style'],
'color_palette': style_config['color_palette'],
'svg_size': len(result['variants'][0]['svg']),
'filename': filename,
'success': True
})
print(f" ✅ Generated: {svg_path}")
print(f" Size: {len(result['variants'][0]['svg'])} characters")
else:
print(f" ❌ Failed: {result['error']}")
style_results.append({
'style': style_config['style'],
'color_palette': style_config['color_palette'],
'success': False,
'error': result['error']
})
# Generate style comparison report
if style_results:
comparison_report = f"""# Style Comparison Example Report
## Subject
**Description:** {base_description}
## Configuration
- **Size:** 256x256
- **Quality:** Fast (for demonstration)
- **Preprocessing:** Enabled
## Results
| Style | Color Palette | Status | SVG Size | File |
|-------|---------------|--------|----------|------|
"""
for result in style_results:
if result['success']:
comparison_report += f"| {result['style']} | {result['color_palette']} | ✅ Success | {result['svg_size']:,} | {result['filename']} |\n"
else:
comparison_report += f"| {result['style']} | {result['color_palette']} | ❌ Failed | - | - |\n"
comparison_report += f"""
## Analysis
This example demonstrates how different style and color palette combinations affect the AI's interpretation and output for the same subject matter.
### Style Effects
- **Minimalist + Monochrome:** Clean, simple designs with limited color usage
- **Tech + Bold:** Modern, angular designs with strong color contrasts
- **Creative + Vibrant:** Artistic interpretations with rich color palettes
### Usage Recommendations
- Use **minimalist** styles for clean, professional logos
- Use **tech** styles for modern, technology-focused designs
- Use **creative** styles for artistic or brand-focused applications
This comparison helps users select appropriate style combinations for their specific use cases.
"""
report_path = output_manager.save_file(
comparison_report, "style_comparison_report.md", "style_comparison", "04_comparisons"
)
print(f"\n📊 Style comparison report: {report_path}")
def example_svg_cleaning():
"""Example of SVG cleaning without generation"""
print("\n🧹 SVG Cleaning Example")
print("=" * 30)
# Setup organized output for cleaning example
dirs = create_standard_test_structure("svg_cleaning")
output_manager = get_output_manager()
# Sample SVG with artifacts
sample_svg = '''<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
<rect x="0" y="0" width="200" height="200" fill="white"/>
<circle cx="10" cy="10" r="2" fill="#f0f0f0"/>
<rect x="50" y="50" width="100" height="100" fill="#3366cc"/>
<circle cx="100" cy="100" r="30" fill="#ff6600"/>
<path d="M5,5L6,6" stroke="#cccccc"/>
<rect x="0" y="0" width="3" height="200" fill="#ddd"/>
</svg>'''
print(f"Original SVG: {len(sample_svg)} characters")
# Clean the SVG
cleaned_svg = SVGCleaner.clean_svg_artifacts(sample_svg)
reduction = (1 - len(cleaned_svg) / len(sample_svg)) * 100
print(f"Cleaned SVG: {len(cleaned_svg)} characters ({reduction:.1f}% reduction)")
# Save both versions in organized structure
original_path = output_manager.save_file(
sample_svg, "example_original.svg", "svg_cleaning", "01_originals"
)
cleaned_path = output_manager.save_file(
cleaned_svg, "example_cleaned.svg", "svg_cleaning", "02_processed"
)
print(f"✅ Original: {original_path}")
print(f"✅ Cleaned: {cleaned_path}")
print(" Compare them to see the cleaning effect")
# Create cleaning analysis report
cleaning_report = f"""# SVG Cleaning Example Report
## Overview
This example demonstrates the SVG cleaning functionality that removes common artifacts from vectorized images.
## Sample SVG Analysis
The sample SVG contains several types of artifacts commonly found in automated vectorization:
### Artifacts Identified
1. **White Background**: Full-size rectangle with white fill
2. **Small Noise Elements**: Tiny circle with light gray color
3. **Edge Artifacts**: Small rectangle at image border
4. **Minimal Paths**: Very short path with minimal data
5. **Light Gray Elements**: Low-contrast elements likely from noise
### Cleaning Results
- **Original Size:** {len(sample_svg)} characters
- **Cleaned Size:** {len(cleaned_svg)} characters
- **Reduction:** {reduction:.1f}%
## Files Generated
- **Original:** example_original.svg
- **Cleaned:** example_cleaned.svg
## Original SVG Content
```xml
{sample_svg}
```
## Cleaned SVG Content
```xml
{cleaned_svg}
```
## Cleaning Effectiveness
The SVGCleaner successfully removed:
- White background rectangles
- Small noise elements (< 5px radius)
- Edge artifacts (positioned at x=0 or y=0)
- Short paths with minimal data
- Light gray elements with RGB values > 180
While preserving:
- Main content elements (blue rectangle, orange circle)
- Meaningful paths and shapes
- Proper SVG structure and formatting
This example shows how the cleaning process improves SVG quality by removing vectorization artifacts while maintaining the essential visual content.
"""
report_path = output_manager.save_file(
cleaning_report, "cleaning_example_report.md", "svg_cleaning", "04_comparisons"
)
print(f"📊 Cleaning report: {report_path}")
async def main():
"""Run all examples"""
print("🚀 SVG Designer Examples")
print("=" * 30)
print("This demonstrates basic usage of the SVG Designer components")
print()
# Setup organized output session for examples
output_manager = setup_test_session("examples")
# Run examples
await example_basic_generation()
await example_style_comparison()
example_svg_cleaning()
# Generate comprehensive examples summary
examples_summary = """# SVG Designer Examples Summary
## Overview
This session demonstrates the key features and capabilities of the SVG Designer system through practical examples.
## Examples Completed
### 1. Basic Generation Example
- **Purpose:** Shows the fundamental text-to-SVG generation workflow
- **Features:** AI image generation, preprocessing, SVG conversion, cleaning
- **Output:** Coffee cup icon in minimalist monochrome style
- **Location:** `basic_generation/` directory
### 2. Style Comparison Example
- **Purpose:** Demonstrates how different styles affect AI output
- **Features:** Multiple style/color combinations for same subject
- **Output:** Mountain peak logos in 3 different styles
- **Location:** `style_comparison/` directory
### 3. SVG Cleaning Example
- **Purpose:** Shows artifact removal and SVG optimization
- **Features:** Before/after comparison, detailed analysis
- **Output:** Cleaned sample SVG with comprehensive report
- **Location:** `svg_cleaning/` directory
## Directory Structure
```
test_outputs/{session_id}_examples/
├── basic_generation/
│ ├── 02_processed/ # Cleaned SVG files
│ ├── 03_svgs/ # Generated SVG files
│ └── 04_comparisons/ # Analysis reports
├── style_comparison/
│ ├── 03_svgs/ # Style variant SVGs
│ └── 04_comparisons/ # Style analysis
└── svg_cleaning/
├── 01_originals/ # Original SVG with artifacts
├── 02_processed/ # Cleaned SVG
└── 04_comparisons/ # Cleaning analysis
```
## Key Learning Points
### Workflow Understanding
1. **Text Description** → **AI Image Generation** → **Preprocessing** → **Vectorization** → **SVG Cleaning**
2. Each step in the pipeline contributes to the final output quality
3. Style and color palette parameters significantly affect AI interpretation
### Best Practices Demonstrated
- **Style Selection:** Choose appropriate styles for your use case
- **Preprocessing:** Enable for smoother, more professional results
- **Quality Settings:** Balance speed vs detail based on requirements
- **Cleaning:** Post-process SVGs to remove vectorization artifacts
### Configuration Options
- **Styles:** minimalist, tech, creative, abstract, classic
- **Color Palettes:** monochrome, bold, vibrant, pastel, neutral
- **Quality Levels:** fast, medium, high
- **Preprocessing:** Configurable noise reduction and color simplification
## Next Steps
### For Development
- Review individual example reports for detailed analysis
- Experiment with different style/parameter combinations
- Integrate examples into your own applications
### For Production Use
- Run comprehensive tests: `python tests/integration_test.py`
- Set up proper API key management
- Configure appropriate error handling and logging
- Consider caching strategies for repeated requests
### Advanced Usage
- Combine with batch processing for multiple designs
- Integrate with design workflows and tools
- Customize preprocessing parameters for specific image types
- Implement custom SVG post-processing rules
## Support Resources
- **Integration Tests:** Comprehensive system validation
- **Individual Component Tests:** Focused testing of specific features
- **Documentation:** README.md and code comments
- **Error Handling:** Built-in validation and graceful failure modes
These examples provide a foundation for understanding and using the SVG Designer system effectively in your own projects.
"""
summary_path = output_manager.save_file(
examples_summary, "examples_session_summary.md", "session_overview", "05_metrics"
)
print(f"\n🎉 Examples completed!")
print("Generated files show different aspects of the SVG Designer:")
print("- Basic text-to-SVG generation with preprocessing")
print("- Style and color palette variations")
print("- SVG cleaning and artifact removal")
print()
print(f"📄 Session summary: {summary_path}")
print()
print("For comprehensive testing, run:")
print(" python tests/integration_test.py")
# Print organized session summary
output_manager.print_session_summary()
if __name__ == "__main__":
asyncio.run(main())