indoxrouter 0.1.22__tar.gz → 0.1.23__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.
- {indoxrouter-0.1.22 → indoxrouter-0.1.23}/PKG-INFO +1 -1
- {indoxrouter-0.1.22 → indoxrouter-0.1.23}/indoxrouter/client.py +86 -4
- {indoxrouter-0.1.22 → indoxrouter-0.1.23}/indoxrouter.egg-info/PKG-INFO +1 -1
- {indoxrouter-0.1.22 → indoxrouter-0.1.23}/indoxrouter.egg-info/SOURCES.txt +0 -5
- {indoxrouter-0.1.22 → indoxrouter-0.1.23}/pyproject.toml +1 -1
- indoxrouter-0.1.22/examples/google_image_generation.py +0 -89
- indoxrouter-0.1.22/examples/image_generation.py +0 -141
- indoxrouter-0.1.22/examples/openai_image_generation.py +0 -87
- indoxrouter-0.1.22/examples/provider_specific_image_generation.py +0 -191
- indoxrouter-0.1.22/examples/xai_image_generation.py +0 -90
- {indoxrouter-0.1.22 → indoxrouter-0.1.23}/MANIFEST.in +0 -0
- {indoxrouter-0.1.22 → indoxrouter-0.1.23}/README.md +0 -0
- {indoxrouter-0.1.22 → indoxrouter-0.1.23}/cookbook/README.md +0 -0
- {indoxrouter-0.1.22 → indoxrouter-0.1.23}/cookbook/indoxRouter_cookbook.ipynb +0 -0
- {indoxrouter-0.1.22 → indoxrouter-0.1.23}/indoxrouter/__init__.py +0 -0
- {indoxrouter-0.1.22 → indoxrouter-0.1.23}/indoxrouter/constants.py +0 -0
- {indoxrouter-0.1.22 → indoxrouter-0.1.23}/indoxrouter/exceptions.py +0 -0
- {indoxrouter-0.1.22 → indoxrouter-0.1.23}/indoxrouter.egg-info/dependency_links.txt +0 -0
- {indoxrouter-0.1.22 → indoxrouter-0.1.23}/indoxrouter.egg-info/requires.txt +0 -0
- {indoxrouter-0.1.22 → indoxrouter-0.1.23}/indoxrouter.egg-info/top_level.txt +0 -0
- {indoxrouter-0.1.22 → indoxrouter-0.1.23}/setup.cfg +0 -0
- {indoxrouter-0.1.22 → indoxrouter-0.1.23}/tests/test_image.py +0 -0
@@ -673,6 +673,15 @@ class Client:
|
|
673
673
|
if provider.lower() == "google":
|
674
674
|
# For Google, use aspect_ratio instead of size
|
675
675
|
if aspect_ratio is not None:
|
676
|
+
# Google's imagen-3 has specific supported aspect ratios
|
677
|
+
if model_name == "imagen-3.0-generate-002" and aspect_ratio not in [
|
678
|
+
"1:1",
|
679
|
+
"3:4",
|
680
|
+
"4:3",
|
681
|
+
"9:16",
|
682
|
+
"16:9",
|
683
|
+
]:
|
684
|
+
aspect_ratio = "1:1" # Default to 1:1 if not supported
|
676
685
|
data["aspect_ratio"] = aspect_ratio
|
677
686
|
elif size is not None:
|
678
687
|
# Convert size to aspect_ratio
|
@@ -686,7 +695,7 @@ class Client:
|
|
686
695
|
elif provider.lower() == "xai":
|
687
696
|
# xAI doesn't support size parameter - do not include it
|
688
697
|
pass
|
689
|
-
elif size is not None:
|
698
|
+
elif size is not None and provider.lower() != "xai":
|
690
699
|
# For other providers (like OpenAI), use size as is
|
691
700
|
data["size"] = size
|
692
701
|
|
@@ -697,7 +706,9 @@ class Client:
|
|
697
706
|
|
698
707
|
# Add standard parameters if provided
|
699
708
|
if response_format is not None:
|
709
|
+
# Only add response_format if explicitly provided by the user
|
700
710
|
data["response_format"] = response_format
|
711
|
+
|
701
712
|
if user is not None:
|
702
713
|
data["user"] = user
|
703
714
|
|
@@ -739,14 +750,85 @@ class Client:
|
|
739
750
|
if filtered_kwargs:
|
740
751
|
data["additional_params"] = filtered_kwargs
|
741
752
|
|
742
|
-
# Special case handling for specific models
|
753
|
+
# Special case handling for specific models and providers
|
754
|
+
# Only include parameters supported by each model based on their JSON definitions
|
743
755
|
if provider.lower() == "openai" and "gpt-image" in model_name.lower():
|
744
|
-
#
|
745
|
-
if response_format
|
756
|
+
# For OpenAI's gpt-image models, don't automatically add response_format
|
757
|
+
if "response_format" in data and response_format is None:
|
746
758
|
del data["response_format"]
|
747
759
|
|
760
|
+
if provider.lower() == "xai" and "grok-2-image" in model_name.lower():
|
761
|
+
# For xAI's grok-2-image models, ensure size is not included
|
762
|
+
if "size" in data:
|
763
|
+
del data["size"]
|
764
|
+
|
765
|
+
# Clean up any parameters that shouldn't be sent to specific providers
|
766
|
+
# This ensures we only send parameters that each provider supports
|
767
|
+
supported_params = self._get_supported_parameters_for_model(
|
768
|
+
provider, model_name
|
769
|
+
)
|
770
|
+
if supported_params:
|
771
|
+
for param in list(data.keys()):
|
772
|
+
if param not in ["prompt", "model"] and param not in supported_params:
|
773
|
+
del data[param]
|
774
|
+
|
748
775
|
return self._request("POST", IMAGE_ENDPOINT, data)
|
749
776
|
|
777
|
+
def _get_supported_parameters_for_model(
|
778
|
+
self, provider: str, model_name: str
|
779
|
+
) -> List[str]:
|
780
|
+
"""
|
781
|
+
Get the list of supported parameters for a specific model.
|
782
|
+
This helps avoid sending unsupported parameters to providers.
|
783
|
+
|
784
|
+
Args:
|
785
|
+
provider: The provider name (e.g., 'openai', 'google', 'xai')
|
786
|
+
model_name: The model name (e.g., 'gpt-image-1', 'imagen-3.0-generate-002')
|
787
|
+
|
788
|
+
Returns:
|
789
|
+
List of parameter names supported by the model
|
790
|
+
"""
|
791
|
+
# Define supported parameters for specific models
|
792
|
+
if provider.lower() == "openai" and "gpt-image" in model_name.lower():
|
793
|
+
return [
|
794
|
+
"prompt",
|
795
|
+
"size",
|
796
|
+
"quality",
|
797
|
+
"n",
|
798
|
+
"user",
|
799
|
+
"background",
|
800
|
+
"moderation",
|
801
|
+
"output_compression",
|
802
|
+
"output_format",
|
803
|
+
"style",
|
804
|
+
]
|
805
|
+
|
806
|
+
elif provider.lower() == "google" and "imagen" in model_name.lower():
|
807
|
+
return [
|
808
|
+
"prompt",
|
809
|
+
"n",
|
810
|
+
"negative_prompt",
|
811
|
+
"aspect_ratio",
|
812
|
+
"guidance_scale",
|
813
|
+
"seed",
|
814
|
+
"safety_filter_level",
|
815
|
+
"person_generation",
|
816
|
+
"include_safety_attributes",
|
817
|
+
"include_rai_reason",
|
818
|
+
"language",
|
819
|
+
"output_mime_type",
|
820
|
+
"output_compression_quality",
|
821
|
+
"add_watermark",
|
822
|
+
"enhance_prompt",
|
823
|
+
"response_format",
|
824
|
+
]
|
825
|
+
|
826
|
+
elif provider.lower() == "xai" and "grok-2-image" in model_name.lower():
|
827
|
+
return ["prompt", "n", "response_format"]
|
828
|
+
|
829
|
+
# Default case - allow all parameters
|
830
|
+
return []
|
831
|
+
|
750
832
|
def models(self, provider: Optional[str] = None) -> Dict[str, Any]:
|
751
833
|
"""
|
752
834
|
Get available models.
|
@@ -3,11 +3,6 @@ README.md
|
|
3
3
|
pyproject.toml
|
4
4
|
cookbook/README.md
|
5
5
|
cookbook/indoxRouter_cookbook.ipynb
|
6
|
-
examples/google_image_generation.py
|
7
|
-
examples/image_generation.py
|
8
|
-
examples/openai_image_generation.py
|
9
|
-
examples/provider_specific_image_generation.py
|
10
|
-
examples/xai_image_generation.py
|
11
6
|
indoxrouter/__init__.py
|
12
7
|
indoxrouter/client.py
|
13
8
|
indoxrouter/constants.py
|
@@ -1,89 +0,0 @@
|
|
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()
|
@@ -1,141 +0,0 @@
|
|
1
|
-
"""
|
2
|
-
Example script demonstrating image generation with various providers through indoxRouter.
|
3
|
-
|
4
|
-
This script shows how to generate images using different providers (OpenAI, xAI, Google)
|
5
|
-
and how to handle the responses to display or save the generated images.
|
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
|
-
client = Client()
|
30
|
-
|
31
|
-
|
32
|
-
def save_image_from_url(url, filename):
|
33
|
-
"""Download and save an image from a URL."""
|
34
|
-
response = requests.get(url)
|
35
|
-
if response.status_code == 200:
|
36
|
-
with open(filename, "wb") as f:
|
37
|
-
f.write(response.content)
|
38
|
-
print(f"Image saved to {filename}")
|
39
|
-
else:
|
40
|
-
print(f"Failed to download image: {response.status_code}")
|
41
|
-
|
42
|
-
|
43
|
-
def save_image_from_b64(b64_data, filename):
|
44
|
-
"""Save an image from base64 data."""
|
45
|
-
image_data = base64.b64decode(b64_data)
|
46
|
-
with open(filename, "wb") as f:
|
47
|
-
f.write(image_data)
|
48
|
-
print(f"Image saved to {filename}")
|
49
|
-
|
50
|
-
|
51
|
-
def generate_and_save_image(provider, model, prompt):
|
52
|
-
"""Generate an image and save it to a file."""
|
53
|
-
print(f"\n=== Generating image with {provider}/{model} ===")
|
54
|
-
print(f"Prompt: {prompt}")
|
55
|
-
|
56
|
-
try:
|
57
|
-
# Generate the image
|
58
|
-
response = client.images(
|
59
|
-
prompt=prompt,
|
60
|
-
model=f"{provider}/{model}",
|
61
|
-
size="1024x1024",
|
62
|
-
)
|
63
|
-
|
64
|
-
print(f"Response received from {provider}:")
|
65
|
-
print(f"- Success: {response['success']}")
|
66
|
-
print(f"- Cost: ${response['usage']['cost']:.4f}")
|
67
|
-
|
68
|
-
# Check if we have image data
|
69
|
-
if "data" in response and response["data"]:
|
70
|
-
image_data = response["data"][0]
|
71
|
-
|
72
|
-
# Create a timestamp for unique filenames
|
73
|
-
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
74
|
-
|
75
|
-
if "url" in image_data and image_data["url"]:
|
76
|
-
filename = f"{provider}_{model}_{timestamp}.png"
|
77
|
-
save_image_from_url(image_data["url"], filename)
|
78
|
-
|
79
|
-
# Display in notebook if possible
|
80
|
-
if in_notebook:
|
81
|
-
display(Image(url=image_data["url"]))
|
82
|
-
|
83
|
-
elif "b64_json" in image_data and image_data["b64_json"]:
|
84
|
-
filename = f"{provider}_{model}_{timestamp}.png"
|
85
|
-
save_image_from_b64(image_data["b64_json"], filename)
|
86
|
-
|
87
|
-
# Display in notebook if possible
|
88
|
-
if in_notebook:
|
89
|
-
display(Image(data=base64.b64decode(image_data["b64_json"])))
|
90
|
-
|
91
|
-
# Check for revised prompt (DALL-E 3 often revises prompts)
|
92
|
-
if "revised_prompt" in image_data and image_data["revised_prompt"]:
|
93
|
-
print(f"Revised prompt: {image_data['revised_prompt']}")
|
94
|
-
else:
|
95
|
-
print("No image data found in response")
|
96
|
-
print("Response:", response)
|
97
|
-
|
98
|
-
except Exception as e:
|
99
|
-
print(f"Error generating image with {provider}/{model}: {str(e)}")
|
100
|
-
|
101
|
-
|
102
|
-
# Example prompts
|
103
|
-
prompts = {
|
104
|
-
"landscape": "A beautiful mountain landscape with a lake at sunset",
|
105
|
-
"animal": "A cute puppy playing with a ball in a garden",
|
106
|
-
"abstract": "An abstract digital art piece with vibrant colors and geometric shapes",
|
107
|
-
"space": "A realistic view of Earth from space with the moon in the background",
|
108
|
-
}
|
109
|
-
|
110
|
-
|
111
|
-
def main():
|
112
|
-
# Test OpenAI models
|
113
|
-
generate_and_save_image("openai", "dall-e-2", prompts["landscape"])
|
114
|
-
generate_and_save_image("openai", "dall-e-3", prompts["animal"])
|
115
|
-
|
116
|
-
# Test with gpt-image-1 if available
|
117
|
-
try:
|
118
|
-
generate_and_save_image("openai", "gpt-image-1", prompts["abstract"])
|
119
|
-
except Exception as e:
|
120
|
-
print(f"gpt-image-1 test skipped: {str(e)}")
|
121
|
-
|
122
|
-
# Test xAI models
|
123
|
-
try:
|
124
|
-
generate_and_save_image("xai", "grok-2-image", prompts["space"])
|
125
|
-
except Exception as e:
|
126
|
-
print(f"xAI test skipped: {str(e)}")
|
127
|
-
|
128
|
-
# Test Google models
|
129
|
-
try:
|
130
|
-
generate_and_save_image(
|
131
|
-
"google", "imagen-3.0-generate-002", prompts["abstract"]
|
132
|
-
)
|
133
|
-
except Exception as e:
|
134
|
-
print(f"Google test skipped: {str(e)}")
|
135
|
-
|
136
|
-
# Close the client
|
137
|
-
client.close()
|
138
|
-
|
139
|
-
|
140
|
-
if __name__ == "__main__":
|
141
|
-
main()
|
@@ -1,87 +0,0 @@
|
|
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()
|
@@ -1,191 +0,0 @@
|
|
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()
|
@@ -1,90 +0,0 @@
|
|
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()
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|
File without changes
|