Spaces:
Sleeping
Sleeping
add imagenwrapper howto use
Browse files- imagenwrapper.py +61 -0
imagenwrapper.py
CHANGED
@@ -1,3 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
from gradio_client import Client
|
2 |
from typing import Dict, Tuple, Optional, Union
|
3 |
from dataclasses import dataclass
|
|
|
1 |
+
|
2 |
+
|
3 |
+
# This wrapper provides several features:
|
4 |
+
|
5 |
+
# 1. A `ImageGenerationParams` dataclass to handle parameters with default values
|
6 |
+
# 2. A `ImageGenerationResult` class to wrap the API response
|
7 |
+
# 3. The main `ImagenWrapper` class with:
|
8 |
+
# - Proper initialization with error handling
|
9 |
+
# - Logging support
|
10 |
+
# - Two methods for generation:
|
11 |
+
# - `generate()` using the `ImageGenerationParams` class
|
12 |
+
# - `generate_simple()` for a more straightforward interface
|
13 |
+
|
14 |
+
# Here's how to use it:
|
15 |
+
|
16 |
+
# # Example usage:
|
17 |
+
|
18 |
+
# # Initialize the wrapper
|
19 |
+
# wrapper = ImagenWrapper("https://bcdb8b7f9c4a57127c.gradio.live/")
|
20 |
+
|
21 |
+
# # Method 1: Using ImageGenerationParams
|
22 |
+
# params = ImageGenerationParams(
|
23 |
+
# prompt="A beautiful sunset over mountains",
|
24 |
+
# width=512,
|
25 |
+
# height=512
|
26 |
+
# )
|
27 |
+
# result = wrapper.generate(params)
|
28 |
+
|
29 |
+
# # Method 2: Using generate_simple
|
30 |
+
# result = wrapper.generate_simple(
|
31 |
+
# prompt="A beautiful sunset over mountains",
|
32 |
+
# width=512,
|
33 |
+
# height=512
|
34 |
+
# )
|
35 |
+
|
36 |
+
# # Access the results
|
37 |
+
# print(f"Image URL: {result.image_url}")
|
38 |
+
# print(f"Seed used: {result.seed}")
|
39 |
+
|
40 |
+
# The wrapper includes:
|
41 |
+
# - Type hints for better IDE support
|
42 |
+
# - Error handling and logging
|
43 |
+
# - Parameter validation
|
44 |
+
# - Flexible parameter input (both through dataclass and dictionary)
|
45 |
+
# - Clean result handling through a dedicated class
|
46 |
+
|
47 |
+
# You can also add error handling in your code:
|
48 |
+
|
49 |
+
# try:
|
50 |
+
# wrapper = ImagenWrapper("https://bcdb8b7f9c4a57127c.gradio.live/")
|
51 |
+
# result = wrapper.generate_simple("A beautiful sunset")
|
52 |
+
# print(f"Generated image: {result}")
|
53 |
+
# except ConnectionError as e:
|
54 |
+
# print(f"Failed to connect to API: {e}")
|
55 |
+
# except RuntimeError as e:
|
56 |
+
# print(f"Generation failed: {e}")
|
57 |
+
# except Exception as e:
|
58 |
+
# print(f"Unexpected error: {e}")
|
59 |
+
|
60 |
+
|
61 |
+
|
62 |
from gradio_client import Client
|
63 |
from typing import Dict, Tuple, Optional, Union
|
64 |
from dataclasses import dataclass
|