multi-model-orchestrator / multi_model_example.py
kunaliitkgp09's picture
Upload folder using huggingface_hub
b4740c6 verified
#!/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()