class GraphicsGenerator
GraphicsGenerator is a coordinator class that orchestrates the generation of different types of graphics (charts, diagrams, illustrations, and sketches) by delegating to specialized generator classes.
/tf/active/vicechatdev/e-ink-llm/graphics_generator.py
529 - 556
moderate
Purpose
This class serves as the main entry point for generating various types of graphics. It manages three specialized generators (ChartGenerator, DiagramGenerator, and IllustrationGenerator) and routes graphic generation requests to the appropriate generator based on the GraphicSpec type. It provides a unified async interface for generating all graphic types, handling errors gracefully and returning None on failure.
Source Code
class GraphicsGenerator:
"""Main graphics generation coordinator"""
def __init__(self, api_key: str):
self.chart_generator = ChartGenerator()
self.diagram_generator = DiagramGenerator()
self.illustration_generator = IllustrationGenerator(api_key)
async def generate_graphic(self, spec: GraphicSpec) -> Optional[GraphicSpec]:
"""Generate a graphic based on its type and specification"""
try:
if spec.type == GraphicType.CHART:
return self.chart_generator.generate_chart(spec)
elif spec.type == GraphicType.DIAGRAM:
return self.diagram_generator.generate_diagram(spec)
elif spec.type == GraphicType.ILLUSTRATION:
return await self.illustration_generator.generate_illustration(spec)
elif spec.type == GraphicType.SKETCH:
# For now, treat sketches similar to illustrations
return await self.illustration_generator.generate_illustration(spec)
else:
print(f"Unknown graphic type: {spec.type}")
return None
except Exception as e:
print(f"Error generating graphic {spec.id}: {e}")
return None
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
- | - |
Parameter Details
api_key: API key string required for the IllustrationGenerator, typically an OpenAI API key used for AI-generated illustrations. This key is passed through to the IllustrationGenerator during initialization.
Return Value
The constructor returns a GraphicsGenerator instance. The generate_graphic method returns an Optional[GraphicSpec] - either the updated GraphicSpec object with generated graphic data on success, or None if generation fails or the graphic type is unknown.
Class Interface
Methods
__init__(self, api_key: str)
Purpose: Initializes the GraphicsGenerator with three specialized generator instances
Parameters:
api_key: OpenAI API key string required for illustration generation
Returns: None (constructor)
async generate_graphic(self, spec: GraphicSpec) -> Optional[GraphicSpec]
Purpose: Routes graphic generation requests to the appropriate specialized generator based on the GraphicSpec type
Parameters:
spec: GraphicSpec object containing the type, id, and other specifications for the graphic to be generated
Returns: The updated GraphicSpec object with generated graphic data on success, or None if generation fails or type is unknown
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
chart_generator |
ChartGenerator | Instance of ChartGenerator responsible for generating chart-type graphics | instance |
diagram_generator |
DiagramGenerator | Instance of DiagramGenerator responsible for generating diagram-type graphics | instance |
illustration_generator |
IllustrationGenerator | Instance of IllustrationGenerator responsible for generating illustration and sketch-type graphics using AI | instance |
Dependencies
asynciomatplotlibnumpyseabornPILnetworkxopenai
Required Imports
import asyncio
from typing import Optional
from enum import Enum
Conditional/Optional Imports
These imports are only needed under specific conditions:
import matplotlib.pyplot as plt
Condition: Required by ChartGenerator for chart generation
Required (conditional)import matplotlib.patches as patches
Condition: Required by DiagramGenerator for diagram generation
Required (conditional)import numpy as np
Condition: Required by ChartGenerator and DiagramGenerator for numerical operations
Required (conditional)import seaborn as sns
Condition: Required by ChartGenerator for enhanced chart styling
Required (conditional)from PIL import Image, ImageDraw, ImageFont
Condition: Required by DiagramGenerator and IllustrationGenerator for image manipulation
Required (conditional)import networkx as nx
Condition: Required by DiagramGenerator for graph-based diagrams
Required (conditional)from openai import OpenAI
Condition: Required by IllustrationGenerator for AI-generated illustrations
Required (conditional)Usage Example
# Assuming GraphicSpec and GraphicType are defined
import asyncio
from graphics_generator import GraphicsGenerator, GraphicSpec, GraphicType
# Initialize the generator with API key
api_key = "your-openai-api-key"
generator = GraphicsGenerator(api_key)
# Create a graphic specification
spec = GraphicSpec(
id="chart_001",
type=GraphicType.CHART,
title="Sales Data",
data={"Q1": 100, "Q2": 150, "Q3": 200}
)
# Generate the graphic asynchronously
async def main():
result = await generator.generate_graphic(spec)
if result:
print(f"Graphic generated successfully: {result.id}")
else:
print("Failed to generate graphic")
asyncio.run(main())
Best Practices
- Always use await when calling generate_graphic() as it is an async method
- Check the return value for None to handle generation failures gracefully
- Ensure the api_key is valid before instantiation to avoid runtime errors in IllustrationGenerator
- The class maintains stateful generator instances, so reuse the same GraphicsGenerator instance for multiple graphic generations
- Handle exceptions at the caller level as the method catches and logs errors internally but returns None
- For SKETCH type graphics, be aware they are currently processed as ILLUSTRATION types
- Ensure GraphicSpec objects have valid 'type' and 'id' attributes before passing to generate_graphic()
- The method is thread-safe for concurrent calls as each generator maintains its own state
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class IllustrationGenerator 73.0% similar
-
class DiagramGenerator 71.2% similar
-
class ChartGenerator 70.0% similar
-
function demo_graphics_generation 68.0% similar
-
class GraphicType 59.2% similar