indoxrouter 0.1.19__tar.gz → 0.1.22__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. {indoxrouter-0.1.19 → indoxrouter-0.1.22}/PKG-INFO +1 -1
  2. indoxrouter-0.1.22/examples/google_image_generation.py +89 -0
  3. indoxrouter-0.1.22/examples/openai_image_generation.py +87 -0
  4. indoxrouter-0.1.22/examples/provider_specific_image_generation.py +191 -0
  5. indoxrouter-0.1.22/examples/xai_image_generation.py +90 -0
  6. {indoxrouter-0.1.19 → indoxrouter-0.1.22}/indoxrouter/client.py +33 -10
  7. {indoxrouter-0.1.19 → indoxrouter-0.1.22}/indoxrouter.egg-info/PKG-INFO +1 -1
  8. {indoxrouter-0.1.19 → indoxrouter-0.1.22}/indoxrouter.egg-info/SOURCES.txt +3 -0
  9. {indoxrouter-0.1.19 → indoxrouter-0.1.22}/pyproject.toml +1 -1
  10. indoxrouter-0.1.19/examples/google_image_generation.py +0 -159
  11. {indoxrouter-0.1.19 → indoxrouter-0.1.22}/MANIFEST.in +0 -0
  12. {indoxrouter-0.1.19 → indoxrouter-0.1.22}/README.md +0 -0
  13. {indoxrouter-0.1.19 → indoxrouter-0.1.22}/cookbook/README.md +0 -0
  14. {indoxrouter-0.1.19 → indoxrouter-0.1.22}/cookbook/indoxRouter_cookbook.ipynb +0 -0
  15. {indoxrouter-0.1.19 → indoxrouter-0.1.22}/examples/image_generation.py +0 -0
  16. {indoxrouter-0.1.19 → indoxrouter-0.1.22}/indoxrouter/__init__.py +0 -0
  17. {indoxrouter-0.1.19 → indoxrouter-0.1.22}/indoxrouter/constants.py +0 -0
  18. {indoxrouter-0.1.19 → indoxrouter-0.1.22}/indoxrouter/exceptions.py +0 -0
  19. {indoxrouter-0.1.19 → indoxrouter-0.1.22}/indoxrouter.egg-info/dependency_links.txt +0 -0
  20. {indoxrouter-0.1.19 → indoxrouter-0.1.22}/indoxrouter.egg-info/requires.txt +0 -0
  21. {indoxrouter-0.1.19 → indoxrouter-0.1.22}/indoxrouter.egg-info/top_level.txt +0 -0
  22. {indoxrouter-0.1.19 → indoxrouter-0.1.22}/setup.cfg +0 -0
  23. {indoxrouter-0.1.19 → indoxrouter-0.1.22}/tests/test_image.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: indoxrouter
3
- Version: 0.1.19
3
+ Version: 0.1.22
4
4
  Summary: A unified client for various AI providers
5
5
  Author-email: indoxRouter Team <ashkan.eskandari.dev@gmail.com>
6
6
  License: MIT
@@ -0,0 +1,89 @@
1
+ """
2
+ Example script demonstrating Google image generation through indoxRouter.
3
+
4
+ This script shows how to generate images using Google's Imagen models
5
+ with their specific parameters, especially aspect_ratio instead of size.
6
+
7
+ Requirements:
8
+ - Install indoxRouter: pip install indoxrouter
9
+ - Set INDOX_ROUTER_API_KEY environment variable with your API key
10
+ """
11
+
12
+ import os
13
+ from indoxrouter import Client
14
+
15
+ # Initialize client with API key from environment variable
16
+ api_key = os.environ.get("INDOX_ROUTER_API_KEY")
17
+ if not api_key:
18
+ print("Please set the INDOX_ROUTER_API_KEY environment variable")
19
+ exit(1)
20
+
21
+ client = Client(api_key=api_key)
22
+
23
+
24
+ def generate_image(model, prompt, **kwargs):
25
+ """Generate an image with the specified Google model and parameters."""
26
+ print(f"\n=== Generating image with {model} ===")
27
+ print(f"Prompt: {prompt}")
28
+
29
+ try:
30
+ response = client.images(prompt=prompt, model=f"google/{model}", **kwargs)
31
+
32
+ # Print the URL of the generated image
33
+ if "data" in response and response["data"] and "url" in response["data"][0]:
34
+ print(f"Image URL: {response['data'][0]['url']}")
35
+
36
+ # Print usage/cost information if available
37
+ if "usage" in response and "cost" in response["usage"]:
38
+ print(f"Cost: ${response['usage']['cost']:.4f}")
39
+
40
+ return response
41
+ except Exception as e:
42
+ print(f"Error: {str(e)}")
43
+ return None
44
+
45
+
46
+ def main():
47
+ """Main function demonstrating Google image generation."""
48
+
49
+ # Basic example with square aspect ratio
50
+ imagen_square = generate_image(
51
+ model="imagen-3.0-generate-002",
52
+ prompt="A serene Japanese garden with a koi pond",
53
+ aspect_ratio="1:1", # Use aspect_ratio instead of size
54
+ response_format="url",
55
+ )
56
+
57
+ # Example with landscape aspect ratio
58
+ imagen_landscape = generate_image(
59
+ model="imagen-3.0-generate-002",
60
+ prompt="A panoramic view of the Grand Canyon at sunset",
61
+ aspect_ratio="16:9", # Landscape orientation
62
+ response_format="url",
63
+ )
64
+
65
+ # Example with portrait aspect ratio
66
+ imagen_portrait = generate_image(
67
+ model="imagen-3.0-generate-002",
68
+ prompt="A tall redwood tree in a misty forest",
69
+ aspect_ratio="9:16", # Portrait orientation
70
+ response_format="url",
71
+ )
72
+
73
+ # Example with additional parameters
74
+ imagen_advanced = generate_image(
75
+ model="imagen-3.0-generate-002",
76
+ prompt="A cyberpunk cityscape with neon lights and flying vehicles",
77
+ aspect_ratio="4:3",
78
+ negative_prompt="cartoon, illustration, drawing, painting", # What to avoid
79
+ guidance_scale=12.0, # Controls adherence to the text prompt (7-20)
80
+ seed=12345, # For reproducible results
81
+ response_format="url",
82
+ )
83
+
84
+ # Close the client when done
85
+ client.close()
86
+
87
+
88
+ if __name__ == "__main__":
89
+ main()
@@ -0,0 +1,87 @@
1
+ """
2
+ Example script demonstrating OpenAI image generation through indoxRouter.
3
+
4
+ This script shows how to generate images using different OpenAI models:
5
+ - DALL-E 2
6
+ - DALL-E 3
7
+ - GPT-image-1
8
+
9
+ Requirements:
10
+ - Install indoxRouter: pip install indoxrouter
11
+ - Set INDOX_ROUTER_API_KEY environment variable with your API key
12
+ """
13
+
14
+ import os
15
+ from indoxrouter import Client
16
+
17
+ # Initialize client with API key from environment variable
18
+ api_key = os.environ.get("INDOX_ROUTER_API_KEY")
19
+ if not api_key:
20
+ print("Please set the INDOX_ROUTER_API_KEY environment variable")
21
+ exit(1)
22
+
23
+ client = Client(api_key=api_key)
24
+
25
+
26
+ def generate_image(model, prompt, **kwargs):
27
+ """Generate an image with the specified model and parameters."""
28
+ print(f"\n=== Generating image with {model} ===")
29
+ print(f"Prompt: {prompt}")
30
+
31
+ try:
32
+ response = client.images(prompt=prompt, model=f"openai/{model}", **kwargs)
33
+
34
+ # Print the URL of the generated image
35
+ if "data" in response and response["data"] and "url" in response["data"][0]:
36
+ print(f"Image URL: {response['data'][0]['url']}")
37
+
38
+ # Check for revised prompt (DALL-E 3 often revises prompts)
39
+ if "revised_prompt" in response["data"][0]:
40
+ print(f"Revised prompt: {response['data'][0]['revised_prompt']}")
41
+
42
+ # Print usage/cost information if available
43
+ if "usage" in response and "cost" in response["usage"]:
44
+ print(f"Cost: ${response['usage']['cost']:.4f}")
45
+
46
+ return response
47
+ except Exception as e:
48
+ print(f"Error: {str(e)}")
49
+ return None
50
+
51
+
52
+ def main():
53
+ """Main function demonstrating OpenAI image generation."""
54
+
55
+ # Basic DALL-E 2 example
56
+ dalle2_response = generate_image(
57
+ model="dall-e-2",
58
+ prompt="A beautiful mountain landscape at sunset",
59
+ size="1024x1024", # Required parameter
60
+ response_format="url", # Optional parameter
61
+ )
62
+
63
+ # DALL-E 3 with quality and style options
64
+ dalle3_response = generate_image(
65
+ model="dall-e-3",
66
+ prompt="A futuristic city with flying cars and tall skyscrapers",
67
+ size="1024x1024", # Required parameter
68
+ quality="hd", # Optional parameter ('standard' or 'hd')
69
+ style="vivid", # Optional parameter ('vivid' or 'natural')
70
+ response_format="url",
71
+ )
72
+
73
+ # GPT-image-1 example
74
+ # Note: For GPT-image-1, don't include response_format unless you need it
75
+ gpt_image_response = generate_image(
76
+ model="gpt-image-1",
77
+ prompt="A whimsical fantasy castle with dragons flying around it",
78
+ size="1024x1024", # Required parameter
79
+ # response_format is omitted as it can cause errors with gpt-image-1
80
+ )
81
+
82
+ # Close the client when done
83
+ client.close()
84
+
85
+
86
+ if __name__ == "__main__":
87
+ main()
@@ -0,0 +1,191 @@
1
+ """
2
+ Example script demonstrating image generation with different providers through indoxRouter.
3
+
4
+ This script shows how to generate images using different providers (OpenAI, Google, xAI)
5
+ with their provider-specific parameters and handling.
6
+
7
+ Requirements:
8
+ - Install indoxRouter: pip install indoxrouter
9
+ - Set INDOX_ROUTER_API_KEY environment variable with your API key
10
+ """
11
+
12
+ import os
13
+ import base64
14
+ from io import BytesIO
15
+ import requests
16
+ from datetime import datetime
17
+
18
+ from indoxrouter import Client
19
+
20
+ # For displaying images in notebooks
21
+ try:
22
+ from IPython.display import Image, display
23
+
24
+ in_notebook = True
25
+ except ImportError:
26
+ in_notebook = False
27
+
28
+ # Initialize client with API key from environment variable
29
+ api_key = os.environ.get("INDOX_ROUTER_API_KEY")
30
+ if not api_key:
31
+ print("Please set the INDOX_ROUTER_API_KEY environment variable")
32
+ exit(1)
33
+
34
+ client = Client(api_key=api_key)
35
+
36
+
37
+ def save_image_from_url(url, filename):
38
+ """Download and save an image from a URL."""
39
+ response = requests.get(url)
40
+ if response.status_code == 200:
41
+ with open(filename, "wb") as f:
42
+ f.write(response.content)
43
+ print(f"Image saved to {filename}")
44
+ else:
45
+ print(f"Failed to download image: {response.status_code}")
46
+
47
+
48
+ def save_image_from_b64(b64_data, filename):
49
+ """Save an image from base64 data."""
50
+ image_data = base64.b64decode(b64_data)
51
+ with open(filename, "wb") as f:
52
+ f.write(image_data)
53
+ print(f"Image saved to {filename}")
54
+
55
+
56
+ def display_response_image(response, provider, model):
57
+ """Display image from response and save it."""
58
+ try:
59
+ if "data" in response and response["data"]:
60
+ image_data = response["data"][0]
61
+
62
+ # Create a timestamp for unique filenames
63
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
64
+
65
+ if "url" in image_data and image_data["url"]:
66
+ filename = f"{provider}_{model}_{timestamp}.png"
67
+ save_image_from_url(image_data["url"], filename)
68
+
69
+ # Display in notebook if possible
70
+ if in_notebook:
71
+ display(Image(url=image_data["url"]))
72
+
73
+ elif "b64_json" in image_data and image_data["b64_json"]:
74
+ filename = f"{provider}_{model}_{timestamp}.png"
75
+ save_image_from_b64(image_data["b64_json"], filename)
76
+
77
+ # Display in notebook if possible
78
+ if in_notebook:
79
+ display(Image(data=base64.b64decode(image_data["b64_json"])))
80
+
81
+ # Check for revised prompt (DALL-E 3 often revises prompts)
82
+ if "revised_prompt" in image_data and image_data["revised_prompt"]:
83
+ print(f"Revised prompt: {image_data['revised_prompt']}")
84
+ else:
85
+ print("No image data found in response")
86
+ except Exception as e:
87
+ print(f"Error displaying/saving image: {str(e)}")
88
+
89
+
90
+ def main():
91
+ """Main function demonstrating image generation with different providers."""
92
+
93
+ # Example prompt for all providers
94
+ prompt = "A tranquil zen garden with cherry blossoms and a small pond"
95
+
96
+ print("\n=== OpenAI (DALL-E 2) ===")
97
+ print("Uses pixel dimensions (e.g., '1024x1024')")
98
+ try:
99
+ openai_response = client.images(
100
+ prompt=prompt,
101
+ model="openai/dall-e-2",
102
+ size="1024x1024", # OpenAI uses pixel dimensions
103
+ )
104
+ print(f"Response received - Success: {openai_response.get('success', False)}")
105
+ print(f"Cost: ${openai_response.get('usage', {}).get('cost', 0):.4f}")
106
+ display_response_image(openai_response, "openai", "dall-e-2")
107
+ except Exception as e:
108
+ print(f"Error with OpenAI: {str(e)}")
109
+
110
+ print("\n=== OpenAI (GPT-image-1) ===")
111
+ print("Uses pixel dimensions (e.g., '1024x1024')")
112
+ try:
113
+ # For GPT-image-1, don't include response_format parameter unless you specify it
114
+ gpt_image_response = client.images(
115
+ prompt=prompt,
116
+ model="openai/gpt-image-1",
117
+ size="1024x1024", # OpenAI uses pixel dimensions
118
+ # Note: don't include response_format parameter unless explicitly needed
119
+ )
120
+ print(
121
+ f"Response received - Success: {gpt_image_response.get('success', False)}"
122
+ )
123
+ print(f"Cost: ${gpt_image_response.get('usage', {}).get('cost', 0):.4f}")
124
+ display_response_image(gpt_image_response, "openai", "gpt-image-1")
125
+ except Exception as e:
126
+ print(f"Error with GPT-image-1: {str(e)}")
127
+
128
+ print("\n=== Google (Imagen) ===")
129
+ print("Uses aspect ratios (e.g., '1:1', '16:9') instead of pixel dimensions")
130
+ try:
131
+ google_response = client.images(
132
+ prompt=prompt,
133
+ model="google/imagen-3.0-generate-002",
134
+ # Note: Use 'aspect_ratio' instead of 'size' for Google
135
+ aspect_ratio="1:1", # Google uses aspect ratios
136
+ negative_prompt="cartoon, illustration, drawing, painting",
137
+ )
138
+ print(f"Response received - Success: {google_response.get('success', False)}")
139
+ print(f"Cost: ${google_response.get('usage', {}).get('cost', 0):.4f}")
140
+ display_response_image(google_response, "google", "imagen")
141
+ except Exception as e:
142
+ print(f"Error with Google: {str(e)}")
143
+
144
+ print("\n=== xAI (Grok) ===")
145
+ print("Does not use size parameter, only supports specific parameters")
146
+ try:
147
+ xai_response = client.images(
148
+ prompt=prompt,
149
+ model="xai/grok-2-image",
150
+ # Note: xAI doesn't support size parameter, so we don't include it
151
+ # Only include specific parameters that xAI supports
152
+ response_format="url", # xAI supports response_format
153
+ )
154
+ print(f"Response received - Success: {xai_response.get('success', False)}")
155
+ print(f"Cost: ${xai_response.get('usage', {}).get('cost', 0):.4f}")
156
+ display_response_image(xai_response, "xai", "grok-2-image")
157
+ except Exception as e:
158
+ print(f"Error with xAI: {str(e)}")
159
+
160
+ # Advanced example with DALL-E 3
161
+ print("\n=== OpenAI (DALL-E 3) with Advanced Parameters ===")
162
+ try:
163
+ dalle3_response = client.images(
164
+ prompt="A beautiful underwater scene with coral reef and tropical fish",
165
+ model="openai/dall-e-3",
166
+ size="1024x1024",
167
+ quality="standard", # 'standard' or 'hd'
168
+ style="vivid", # 'vivid' or 'natural'
169
+ response_format="url",
170
+ )
171
+ print(f"Response received - Success: {dalle3_response.get('success', False)}")
172
+ print(f"Cost: ${dalle3_response.get('usage', {}).get('cost', 0):.4f}")
173
+ display_response_image(dalle3_response, "openai", "dall-e-3")
174
+ except Exception as e:
175
+ print(f"Error with DALL-E 3: {str(e)}")
176
+
177
+ print("\n=== Provider-Specific Parameter Examples ===")
178
+ print("Each provider supports different parameters:")
179
+ print("OpenAI: size, quality, style, background, response_format...")
180
+ print("Google: aspect_ratio, negative_prompt, guidance_scale, seed...")
181
+ print("xAI: n, response_format (minimal parameters)")
182
+ print(
183
+ "\nRefer to the documentation for the complete list of parameters for each provider."
184
+ )
185
+
186
+ # Close the client when done
187
+ client.close()
188
+
189
+
190
+ if __name__ == "__main__":
191
+ main()
@@ -0,0 +1,90 @@
1
+ """
2
+ Example script demonstrating xAI image generation through indoxRouter.
3
+
4
+ This script shows how to generate images using xAI's Grok model
5
+ with the correct parameters (avoiding 'size' which is not supported).
6
+
7
+ Requirements:
8
+ - Install indoxRouter: pip install indoxrouter
9
+ - Set INDOX_ROUTER_API_KEY environment variable with your API key
10
+ """
11
+
12
+ import os
13
+ from indoxrouter import Client
14
+
15
+ # Initialize client with API key from environment variable
16
+ api_key = os.environ.get("INDOX_ROUTER_API_KEY")
17
+ if not api_key:
18
+ print("Please set the INDOX_ROUTER_API_KEY environment variable")
19
+ exit(1)
20
+
21
+ client = Client(api_key=api_key)
22
+
23
+
24
+ def generate_image(prompt, **kwargs):
25
+ """Generate an image with xAI's Grok model."""
26
+ print(f"\n=== Generating image with xAI Grok ===")
27
+ print(f"Prompt: {prompt}")
28
+
29
+ try:
30
+ response = client.images(
31
+ prompt=prompt,
32
+ model="xai/grok-2-image",
33
+ # DO NOT include 'size' parameter - it will cause an error
34
+ **kwargs,
35
+ )
36
+
37
+ # Print the URL of the generated image
38
+ if "data" in response and response["data"] and "url" in response["data"][0]:
39
+ print(f"Image URL: {response['data'][0]['url']}")
40
+
41
+ # Print usage/cost information if available
42
+ if "usage" in response and "cost" in response["usage"]:
43
+ print(f"Cost: ${response['usage']['cost']:.4f}")
44
+
45
+ return response
46
+ except Exception as e:
47
+ print(f"Error: {str(e)}")
48
+ return None
49
+
50
+
51
+ def main():
52
+ """Main function demonstrating xAI image generation."""
53
+
54
+ # Basic example - minimal parameters
55
+ basic_image = generate_image(
56
+ prompt="A cybernetic fox in a futuristic city",
57
+ # No size parameter - xAI doesn't support it
58
+ response_format="url", # One of the few parameters xAI supports
59
+ )
60
+
61
+ # Multiple images example
62
+ multiple_images = generate_image(
63
+ prompt="A colorful abstract painting of geometric shapes",
64
+ n=2, # Generate 2 images
65
+ response_format="url",
66
+ )
67
+
68
+ # Example with long, detailed prompt
69
+ detailed_prompt = generate_image(
70
+ prompt=(
71
+ "A steampunk-inspired mechanical dragonfly with brass gears, "
72
+ "copper wings, and glowing blue energy cores, hovering above "
73
+ "a Victorian-era cityscape with airships in the cloudy sky"
74
+ ),
75
+ response_format="url",
76
+ )
77
+
78
+ print("\n=== xAI Parameter Notes ===")
79
+ print("xAI/Grok supports very few parameters compared to other providers:")
80
+ print("- prompt: The text prompt (required)")
81
+ print("- n: Number of images to generate (optional)")
82
+ print("- response_format: 'url' or 'b64_json' (optional)")
83
+ print("DO NOT include 'size', 'quality', 'style', or other parameters")
84
+
85
+ # Close the client when done
86
+ client.close()
87
+
88
+
89
+ if __name__ == "__main__":
90
+ main()
@@ -597,6 +597,8 @@ class Client:
597
597
  output_mime_type: Optional[str] = None,
598
598
  add_watermark: Optional[bool] = None,
599
599
  enhance_prompt: Optional[bool] = None,
600
+ # Google-specific direct parameters
601
+ aspect_ratio: Optional[str] = None,
600
602
  **kwargs,
601
603
  ) -> Dict[str, Any]:
602
604
  """
@@ -608,7 +610,7 @@ class Client:
608
610
 
609
611
  # Provider-specific parameters - will only be included if explicitly provided
610
612
  # Note: Different providers support different parameters
611
- size: Image size - For OpenAI: "1024x1024", "512x512", etc. For Google: "1:1", "4:3", etc.
613
+ size: Image size - For OpenAI: "1024x1024", "512x512", etc. For Google: use aspect_ratio instead
612
614
  n: Number of images to generate
613
615
  quality: Image quality (e.g., "standard", "hd") - supported by some providers
614
616
  style: Image style (e.g., "vivid", "natural") - supported by some providers
@@ -635,6 +637,7 @@ class Client:
635
637
  output_mime_type: MIME type of the generated image
636
638
  add_watermark: Whether to add a watermark to the generated images
637
639
  enhance_prompt: Whether to use prompt rewriting logic
640
+ aspect_ratio: Aspect ratio for Google models (e.g., "1:1", "16:9") - preferred over size
638
641
 
639
642
  **kwargs: Additional parameters to pass to the API
640
643
 
@@ -644,10 +647,11 @@ class Client:
644
647
  # Format the model string
645
648
  formatted_model = self._format_model_string(model)
646
649
 
647
- # Extract provider from model string if present
650
+ # Extract provider and model name from model string if present
648
651
  provider = "openai" # Default provider
652
+ model_name = model
649
653
  if "/" in model:
650
- provider, _ = model.split("/", 1)
654
+ provider, model_name = model.split("/", 1)
651
655
 
652
656
  # Filter out problematic parameters
653
657
  filtered_kwargs = {}
@@ -665,13 +669,26 @@ class Client:
665
669
  if n is not None:
666
670
  data["n"] = n
667
671
 
668
- # Handle size parameter with provider-specific formatting
669
- if size is not None:
670
- formatted_size = self._format_image_size_for_provider(size, provider, model)
671
- data["size"] = formatted_size
672
- elif provider.lower() == "google":
673
- # Default size for Google if not provided
674
- data["size"] = "1:1"
672
+ # Handle size/aspect_ratio parameters based on provider
673
+ if provider.lower() == "google":
674
+ # For Google, use aspect_ratio instead of size
675
+ if aspect_ratio is not None:
676
+ data["aspect_ratio"] = aspect_ratio
677
+ elif size is not None:
678
+ # Convert size to aspect_ratio
679
+ formatted_size = self._format_image_size_for_provider(
680
+ size, provider, model_name
681
+ )
682
+ data["aspect_ratio"] = formatted_size
683
+ else:
684
+ # Default aspect_ratio for Google
685
+ data["aspect_ratio"] = "1:1"
686
+ elif provider.lower() == "xai":
687
+ # xAI doesn't support size parameter - do not include it
688
+ pass
689
+ elif size is not None:
690
+ # For other providers (like OpenAI), use size as is
691
+ data["size"] = size
675
692
 
676
693
  if quality is not None:
677
694
  data["quality"] = quality
@@ -722,6 +739,12 @@ class Client:
722
739
  if filtered_kwargs:
723
740
  data["additional_params"] = filtered_kwargs
724
741
 
742
+ # Special case handling for specific models
743
+ if provider.lower() == "openai" and "gpt-image" in model_name.lower():
744
+ # Remove response_format for gpt-image models unless explicitly provided
745
+ if response_format is None and "response_format" in data:
746
+ del data["response_format"]
747
+
725
748
  return self._request("POST", IMAGE_ENDPOINT, data)
726
749
 
727
750
  def models(self, provider: Optional[str] = None) -> Dict[str, Any]:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: indoxrouter
3
- Version: 0.1.19
3
+ Version: 0.1.22
4
4
  Summary: A unified client for various AI providers
5
5
  Author-email: indoxRouter Team <ashkan.eskandari.dev@gmail.com>
6
6
  License: MIT
@@ -5,6 +5,9 @@ cookbook/README.md
5
5
  cookbook/indoxRouter_cookbook.ipynb
6
6
  examples/google_image_generation.py
7
7
  examples/image_generation.py
8
+ examples/openai_image_generation.py
9
+ examples/provider_specific_image_generation.py
10
+ examples/xai_image_generation.py
8
11
  indoxrouter/__init__.py
9
12
  indoxrouter/client.py
10
13
  indoxrouter/constants.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "indoxrouter"
7
- version = "0.1.19"
7
+ version = "0.1.22"
8
8
  authors = [
9
9
  {name = "indoxRouter Team", email = "ashkan.eskandari.dev@gmail.com"},
10
10
  ]
@@ -1,159 +0,0 @@
1
- """
2
- Example script demonstrating image generation with Google's Imagen model through indoxRouter.
3
-
4
- This script shows how to properly format parameters for Google's image generation API,
5
- including the special handling of aspect ratios and other Google-specific parameters.
6
-
7
- Requirements:
8
- - Install indoxRouter: pip install indoxrouter
9
- - Set INDOX_ROUTER_API_KEY environment variable with your API key
10
- """
11
-
12
- import os
13
- import base64
14
- from io import BytesIO
15
- import requests
16
- from datetime import datetime
17
-
18
- from indoxrouter import Client
19
-
20
- # For displaying images in notebooks
21
- try:
22
- from IPython.display import Image, display
23
-
24
- in_notebook = True
25
- except ImportError:
26
- in_notebook = False
27
-
28
- # Initialize client with API key from environment variable
29
- api_key = os.environ.get("INDOX_ROUTER_API_KEY")
30
- if not api_key:
31
- print("Please set the INDOX_ROUTER_API_KEY environment variable")
32
- exit(1)
33
-
34
- client = Client(api_key=api_key)
35
-
36
-
37
- def save_image_from_url(url, filename):
38
- """Download and save an image from a URL."""
39
- response = requests.get(url)
40
- if response.status_code == 200:
41
- with open(filename, "wb") as f:
42
- f.write(response.content)
43
- print(f"Image saved to {filename}")
44
- else:
45
- print(f"Failed to download image: {response.status_code}")
46
-
47
-
48
- def save_image_from_b64(b64_data, filename):
49
- """Save an image from base64 data."""
50
- image_data = base64.b64decode(b64_data)
51
- with open(filename, "wb") as f:
52
- f.write(image_data)
53
- print(f"Image saved to {filename}")
54
-
55
-
56
- def generate_google_image(prompt, aspect_ratio="1:1", **kwargs):
57
- """
58
- Generate an image using Google's Imagen model.
59
-
60
- Args:
61
- prompt: The text prompt to generate an image from
62
- aspect_ratio: The aspect ratio of the image (e.g., "1:1", "4:3", "16:9")
63
- **kwargs: Additional parameters to pass to the API
64
- """
65
- print(f"\n=== Generating image with Google Imagen ===")
66
- print(f"Prompt: {prompt}")
67
- print(f"Aspect ratio: {aspect_ratio}")
68
-
69
- try:
70
- # Generate the image
71
- # Note: The client will automatically convert "1024x1024" to "1:1" for Google models,
72
- # but it's more explicit to use the correct format directly
73
- response = client.images(
74
- prompt=prompt,
75
- model="google/imagen-3.0-generate-002",
76
- size=aspect_ratio, # Google uses aspect ratios instead of pixel dimensions
77
- **kwargs,
78
- )
79
-
80
- print(f"Response received from Google:")
81
- print(f"- Success: {response['success']}")
82
- print(f"- Cost: ${response['usage']['cost']:.4f}")
83
-
84
- # Check if we have image data
85
- if "data" in response and response["data"]:
86
- image_data = response["data"][0]
87
-
88
- # Create a timestamp for unique filenames
89
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
90
-
91
- if "url" in image_data and image_data["url"]:
92
- filename = (
93
- f"google_imagen_{aspect_ratio.replace(':', 'x')}_{timestamp}.png"
94
- )
95
- save_image_from_url(image_data["url"], filename)
96
-
97
- # Display in notebook if possible
98
- if in_notebook:
99
- display(Image(url=image_data["url"]))
100
-
101
- elif "b64_json" in image_data and image_data["b64_json"]:
102
- filename = (
103
- f"google_imagen_{aspect_ratio.replace(':', 'x')}_{timestamp}.png"
104
- )
105
- save_image_from_b64(image_data["b64_json"], filename)
106
-
107
- # Display in notebook if possible
108
- if in_notebook:
109
- display(Image(data=base64.b64decode(image_data["b64_json"])))
110
- else:
111
- print("No image data found in response")
112
- print("Response:", response)
113
-
114
- except Exception as e:
115
- print(f"Error generating image with Google Imagen: {str(e)}")
116
-
117
-
118
- def main():
119
- """Main function demonstrating Google Imagen image generation."""
120
-
121
- # Basic example with 1:1 aspect ratio (square image)
122
- generate_google_image(
123
- prompt="A tranquil zen garden with cherry blossoms and a small pond"
124
- )
125
-
126
- # Example with 16:9 aspect ratio (widescreen)
127
- generate_google_image(
128
- prompt="A wide panoramic view of a futuristic city skyline at sunset with flying vehicles",
129
- aspect_ratio="16:9",
130
- )
131
-
132
- # Example with 9:16 aspect ratio (portrait/mobile)
133
- generate_google_image(
134
- prompt="A tall waterfall surrounded by lush greenery in a tropical forest",
135
- aspect_ratio="9:16",
136
- )
137
-
138
- # Example with negative prompt to influence the generation
139
- generate_google_image(
140
- prompt="A detailed watercolor painting of a coastal village with boats in the harbor",
141
- negative_prompt="dark, moody, sketch, black and white, blurry",
142
- )
143
-
144
- # Example with more parameters
145
- generate_google_image(
146
- prompt="A beautiful tiger resting in a lush jungle environment",
147
- aspect_ratio="4:3",
148
- negative_prompt="cartoon, illustration, low quality",
149
- seed=123456, # Consistent results with the same seed
150
- guidance_scale=7.5, # Controls how closely the model follows the prompt (usually between 1-20)
151
- safety_filter_level="block_none", # Less restrictive safety filter
152
- )
153
-
154
- # Close the client when done
155
- client.close()
156
-
157
-
158
- if __name__ == "__main__":
159
- main()
File without changes
File without changes
File without changes