File size: 11,529 Bytes
b4740c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Comprehensive Example of Multi-Model Orchestrator
Demonstrates parent-child LLM relationships with CLIP-GPT2 and Stable Diffusion
"""

import asyncio
import json
import time
from pathlib import Path
from simple_orchestrator import SimpleMultiModelOrchestrator, AsyncMultiModelOrchestrator

def create_sample_image():
    """Create a sample image for testing (if no image is available)"""
    from PIL import Image, ImageDraw, ImageFont
    import numpy as np
    
    # Create a simple test image
    img = Image.new('RGB', (512, 512), color='lightblue')
    draw = ImageDraw.Draw(img)
    
    # Add some text
    try:
        # Try to use a default font
        font = ImageFont.load_default()
    except:
        font = None
    
    draw.text((50, 50), "Sample Image", fill='black', font=font)
    draw.text((50, 100), "For Testing", fill='black', font=font)
    
    # Add some shapes
    draw.rectangle([100, 200, 400, 300], fill='red', outline='black')
    draw.ellipse([150, 350, 350, 450], fill='green', outline='black')
    
    # Save the image
    sample_path = "sample_image.jpg"
    img.save(sample_path)
    print(f"Created sample image: {sample_path}")
    return sample_path

def example_basic_usage():
    """Example 1: Basic usage of the orchestrator"""
    print("="*60)
    print("EXAMPLE 1: BASIC USAGE")
    print("="*60)
    
    # Initialize orchestrator
    orchestrator = SimpleMultiModelOrchestrator()
    
    # Initialize models
    print("Initializing models...")
    if not orchestrator.initialize_models():
        print("Failed to initialize models. Exiting.")
        return
    
    # Get status
    status = orchestrator.get_status()
    print(f"Orchestrator Status: {json.dumps(status, indent=2)}")
    
    # Create sample image if needed
    sample_image = create_sample_image()
    
    # Example 1: Image captioning
    print("\n--- Image Captioning ---")
    try:
        caption = orchestrator.generate_caption(sample_image)
        print(f"Generated Caption: {caption}")
    except Exception as e:
        print(f"Caption generation failed: {e}")
    
    # Example 2: Text-to-image generation
    print("\n--- Text-to-Image Generation ---")
    try:
        image_path = orchestrator.generate_image("A beautiful sunset over mountains with a lake")
        print(f"Generated Image: {image_path}")
    except Exception as e:
        print(f"Image generation failed: {e}")
    
    # Example 3: Task routing
    print("\n--- Task Routing ---")
    try:
        # Route caption task
        caption = orchestrator.route_task("caption", sample_image)
        print(f"Routed Caption: {caption}")
        
        # Route image generation task
        image_path = orchestrator.route_task("generate_image", "A cat sitting on a windowsill")
        print(f"Routed Image: {image_path}")
    except Exception as e:
        print(f"Task routing failed: {e}")

def example_multimodal_processing():
    """Example 2: Multimodal processing"""
    print("\n" + "="*60)
    print("EXAMPLE 2: MULTIMODAL PROCESSING")
    print("="*60)
    
    orchestrator = SimpleMultiModelOrchestrator()
    
    if not orchestrator.initialize_models():
        print("Failed to initialize models. Exiting.")
        return
    
    sample_image = create_sample_image()
    
    # Process multimodal task
    print("Processing multimodal task...")
    try:
        results = orchestrator.process_multimodal_task(
            image_path=sample_image,
            text_prompt="A serene landscape with mountains and a flowing river"
        )
        
        print("Multimodal Results:")
        for key, value in results.items():
            print(f"  {key}: {value}")
            
    except Exception as e:
        print(f"Multimodal processing failed: {e}")

async def example_async_processing():
    """Example 3: Async processing for better performance"""
    print("\n" + "="*60)
    print("EXAMPLE 3: ASYNC PROCESSING")
    print("="*60)
    
    orchestrator = AsyncMultiModelOrchestrator()
    
    if not orchestrator.initialize_models():
        print("Failed to initialize models. Exiting.")
        return
    
    sample_image = create_sample_image()
    
    # Async multimodal processing
    print("Processing async multimodal task...")
    try:
        results = await orchestrator.process_multimodal_async(
            image_path=sample_image,
            text_prompt="A futuristic cityscape at night with flying cars"
        )
        
        print("Async Multimodal Results:")
        for key, value in results.items():
            print(f"  {key}: {value}")
            
    except Exception as e:
        print(f"Async multimodal processing failed: {e}")

def example_batch_processing():
    """Example 4: Batch processing multiple tasks"""
    print("\n" + "="*60)
    print("EXAMPLE 4: BATCH PROCESSING")
    print("="*60)
    
    orchestrator = SimpleMultiModelOrchestrator()
    
    if not orchestrator.initialize_models():
        print("Failed to initialize models. Exiting.")
        return
    
    sample_image = create_sample_image()
    
    # Define batch tasks
    caption_tasks = [sample_image] * 3  # Generate 3 captions
    image_tasks = [
        "A majestic eagle soaring over mountains",
        "A cozy coffee shop on a rainy day",
        "A vibrant garden with colorful flowers"
    ]
    
    print("Processing batch tasks...")
    
    # Process caption tasks
    print("\n--- Batch Caption Generation ---")
    for i, image_path in enumerate(caption_tasks):
        try:
            caption = orchestrator.generate_caption(image_path)
            print(f"Caption {i+1}: {caption}")
        except Exception as e:
            print(f"Caption {i+1} failed: {e}")
    
    # Process image generation tasks
    print("\n--- Batch Image Generation ---")
    for i, prompt in enumerate(image_tasks):
        try:
            image_path = orchestrator.generate_image(prompt)
            print(f"Image {i+1}: {image_path}")
        except Exception as e:
            print(f"Image {i+1} failed: {e}")

def example_error_handling():
    """Example 5: Error handling and recovery"""
    print("\n" + "="*60)
    print("EXAMPLE 5: ERROR HANDLING")
    print("="*60)
    
    orchestrator = SimpleMultiModelOrchestrator()
    
    if not orchestrator.initialize_models():
        print("Failed to initialize models. Exiting.")
        return
    
    # Test with invalid inputs
    print("Testing error handling...")
    
    # Invalid image path
    try:
        caption = orchestrator.generate_caption("nonexistent_image.jpg")
        print(f"Caption: {caption}")
    except Exception as e:
        print(f"Expected error for invalid image: {e}")
    
    # Empty text prompt
    try:
        image_path = orchestrator.generate_image("")
        print(f"Image: {image_path}")
    except Exception as e:
        print(f"Expected error for empty prompt: {e}")
    
    # Invalid task type
    try:
        result = orchestrator.route_task("invalid_task", "test")
        print(f"Result: {result}")
    except Exception as e:
        print(f"Expected error for invalid task: {e}")

def example_task_history():
    """Example 6: Task history and monitoring"""
    print("\n" + "="*60)
    print("EXAMPLE 6: TASK HISTORY")
    print("="*60)
    
    orchestrator = SimpleMultiModelOrchestrator()
    
    if not orchestrator.initialize_models():
        print("Failed to initialize models. Exiting.")
        return
    
    sample_image = create_sample_image()
    
    # Perform some tasks
    print("Performing tasks to build history...")
    
    try:
        # Task 1
        caption1 = orchestrator.generate_caption(sample_image)
        print(f"Task 1 - Caption: {caption1}")
        
        # Task 2
        image1 = orchestrator.generate_image("A peaceful forest scene")
        print(f"Task 2 - Image: {image1}")
        
        # Task 3
        caption2 = orchestrator.generate_caption(sample_image)
        print(f"Task 3 - Caption: {caption2}")
        
    except Exception as e:
        print(f"Task execution failed: {e}")
    
    # Display task history
    print("\n--- Task History ---")
    history = orchestrator.get_task_history()
    
    for i, task in enumerate(history):
        print(f"\nTask {i+1}:")
        print(f"  Type: {task['task_type']}")
        print(f"  Input: {task['input_data']}")
        print(f"  Output: {task['output']}")
        print(f"  Processing Time: {task['processing_time']:.2f}s")
        print(f"  Success: {task.get('error') is None}")
        if task.get('error'):
            print(f"  Error: {task['error']}")
    
    # Save task history
    orchestrator.save_task_history("example_task_history.json")
    print(f"\nTask history saved to example_task_history.json")

def example_custom_configuration():
    """Example 7: Custom configuration and parameters"""
    print("\n" + "="*60)
    print("EXAMPLE 7: CUSTOM CONFIGURATION")
    print("="*60)
    
    orchestrator = SimpleMultiModelOrchestrator()
    
    if not orchestrator.initialize_models():
        print("Failed to initialize models. Exiting.")
        return
    
    sample_image = create_sample_image()
    
    # Test different generation parameters
    print("Testing different generation parameters...")
    
    # Test with different image generation parameters
    try:
        # Generate image with custom output path
        custom_path = "custom_generated_image.png"
        image_path = orchestrator.generate_image(
            "A magical castle in the clouds", 
            output_path=custom_path
        )
        print(f"Custom path image: {image_path}")
        
    except Exception as e:
        print(f"Custom configuration failed: {e}")

def main():
    """Run all examples"""
    print("Multi-Model Orchestrator Examples")
    print("This script demonstrates various features of the orchestrator.")
    print("Note: Some operations may take time and require significant memory.")
    
    try:
        # Run examples
        example_basic_usage()
        example_multimodal_processing()
        asyncio.run(example_async_processing())
        example_batch_processing()
        example_error_handling()
        example_task_history()
        example_custom_configuration()
        
        print("\n" + "="*60)
        print("ALL EXAMPLES COMPLETED SUCCESSFULLY!")
        print("="*60)
        
        print("\nGenerated files:")
        if Path("sample_image.jpg").exists():
            print("  - sample_image.jpg (test image)")
        if Path("generated_image_*.png").exists():
            print("  - generated_image_*.png (generated images)")
        if Path("example_task_history.json").exists():
            print("  - example_task_history.json (task history)")
        
        print("\nNext steps:")
        print("1. Check the generated images and task history")
        print("2. Experiment with different prompts and parameters")
        print("3. Integrate the orchestrator into your own applications")
        print("4. Add more child models to the system")
        
    except Exception as e:
        print(f"\nError during execution: {e}")
        print("This might be due to:")
        print("- Insufficient memory (try reducing batch sizes)")
        print("- Missing dependencies (check multi_model_requirements.txt)")
        print("- GPU not available (will use CPU instead)")
        print("- Network issues (models need to be downloaded)")

if __name__ == "__main__":
    main()