|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Example script demonstrating the classify_single method.""" |
| 3 | + |
| 4 | +import asyncio |
| 5 | +import logging |
| 6 | +import os |
| 7 | +import sys |
| 8 | +import uuid |
| 9 | +from pathlib import Path |
| 10 | + |
| 11 | +from create_image import create_test_image |
| 12 | +from dotenv import load_dotenv |
| 13 | + |
| 14 | +from resolver_athena_client.client.athena_client import AthenaClient |
| 15 | +from resolver_athena_client.client.athena_options import AthenaOptions |
| 16 | +from resolver_athena_client.client.channel import ( |
| 17 | + CredentialHelper, |
| 18 | + create_channel_with_credentials, |
| 19 | +) |
| 20 | +from resolver_athena_client.client.models import ImageData |
| 21 | + |
| 22 | + |
| 23 | +async def classify_single_image_example( |
| 24 | + logger: logging.Logger, |
| 25 | + options: AthenaOptions, |
| 26 | + credential_helper: CredentialHelper, |
| 27 | + image_path: str | None = None, |
| 28 | +) -> bool: |
| 29 | + """Demonstrate single image classification. |
| 30 | +
|
| 31 | + Args: |
| 32 | + logger: Logger instance for output |
| 33 | + options: Configuration options for the Athena client |
| 34 | + credential_helper: OAuth credential helper for authentication |
| 35 | + image_path: Path to image file to classify (optional) |
| 36 | +
|
| 37 | + Returns: |
| 38 | + True if classification was successful, False otherwise |
| 39 | +
|
| 40 | + """ |
| 41 | + # Create gRPC channel with credentials |
| 42 | + channel = await create_channel_with_credentials( |
| 43 | + options.host, credential_helper |
| 44 | + ) |
| 45 | + |
| 46 | + async with AthenaClient(channel, options) as client: |
| 47 | + # Load image data |
| 48 | + if image_path and Path(image_path).exists(): |
| 49 | + logger.info("Loading image from: %s", image_path) |
| 50 | + image_bytes = Path(image_path).read_bytes() |
| 51 | + else: |
| 52 | + # Create a simple test image if no path provided |
| 53 | + logger.info("Creating synthetic test image") |
| 54 | + image_bytes = create_test_image() |
| 55 | + |
| 56 | + # Create ImageData object |
| 57 | + image_data = ImageData(image_bytes) |
| 58 | + logger.info( |
| 59 | + "Image loaded: %d bytes, MD5: %s", |
| 60 | + len(image_data.data), |
| 61 | + image_data.md5_hashes[0][:8] + "...", |
| 62 | + ) |
| 63 | + |
| 64 | + try: |
| 65 | + # Classify the single image |
| 66 | + logger.info("Classifying single image...") |
| 67 | + correlation_id = uuid.uuid4().hex[:63] |
| 68 | + logger.info("Correlation ID: %s", correlation_id) |
| 69 | + result = await client.classify_single( |
| 70 | + image_data, correlation_id=correlation_id |
| 71 | + ) |
| 72 | + |
| 73 | + # Process the result |
| 74 | + logger.info("Classification completed successfully!") |
| 75 | + |
| 76 | + if result.error.code: |
| 77 | + logger.error( |
| 78 | + "Classification error: %s (%s)", |
| 79 | + result.error.message, |
| 80 | + result.error.code, |
| 81 | + ) |
| 82 | + if result.error.details: |
| 83 | + logger.error("Error details: %s", result.error.details) |
| 84 | + return False |
| 85 | + |
| 86 | + if result.classifications: |
| 87 | + logger.info( |
| 88 | + "Found %d classifications:", len(result.classifications) |
| 89 | + ) |
| 90 | + for i, classification in enumerate(result.classifications, 1): |
| 91 | + logger.info( |
| 92 | + " %d. Label: %s, Weight: %.3f", |
| 93 | + i, |
| 94 | + classification.label, |
| 95 | + classification.weight, |
| 96 | + ) |
| 97 | + else: |
| 98 | + logger.info("No classifications found for this image") |
| 99 | + |
| 100 | + except Exception: |
| 101 | + logger.exception("Error during single image classification") |
| 102 | + return False |
| 103 | + else: |
| 104 | + return True |
| 105 | + |
| 106 | + |
| 107 | +async def classify_multiple_single_images_example( |
| 108 | + logger: logging.Logger, |
| 109 | + options: AthenaOptions, |
| 110 | + credential_helper: CredentialHelper, |
| 111 | + num_images: int = 3, |
| 112 | +) -> int: |
| 113 | + """Demonstrate classifying multiple images individually. |
| 114 | +
|
| 115 | + This shows how classify_single can be used for multiple images |
| 116 | + when you want individual control over each classification request. |
| 117 | +
|
| 118 | + Args: |
| 119 | + logger: Logger instance for output |
| 120 | + options: Configuration options for the Athena client |
| 121 | + credential_helper: OAuth credential helper for authentication |
| 122 | + num_images: Number of test images to classify |
| 123 | +
|
| 124 | + Returns: |
| 125 | + Number of successfully classified images |
| 126 | +
|
| 127 | + """ |
| 128 | + # Create gRPC channel with credentials |
| 129 | + channel = await create_channel_with_credentials( |
| 130 | + options.host, credential_helper |
| 131 | + ) |
| 132 | + |
| 133 | + successful_count = 0 |
| 134 | + |
| 135 | + async with AthenaClient(channel, options) as client: |
| 136 | + logger.info("Classifying %d images individually...", num_images) |
| 137 | + |
| 138 | + for i in range(num_images): |
| 139 | + try: |
| 140 | + # Create a unique test image for each iteration |
| 141 | + image_bytes = create_test_image(seed=i) |
| 142 | + image_data = ImageData(image_bytes) |
| 143 | + |
| 144 | + # Classify with auto-generated correlation ID |
| 145 | + result = await client.classify_single(image_data) |
| 146 | + |
| 147 | + logger.info( |
| 148 | + "Image %d/%d - Correlation: %s", |
| 149 | + i + 1, |
| 150 | + num_images, |
| 151 | + result.correlation_id[:8] + "...", |
| 152 | + ) |
| 153 | + |
| 154 | + if result.error.code: |
| 155 | + logger.warning( |
| 156 | + "Image %d failed: %s", i + 1, result.error.message |
| 157 | + ) |
| 158 | + elif result.classifications: |
| 159 | + top_classification = max( |
| 160 | + result.classifications, key=lambda c: c.weight |
| 161 | + ) |
| 162 | + logger.info( |
| 163 | + "Image %d - Top result: %s (%.3f)", |
| 164 | + i + 1, |
| 165 | + top_classification.label, |
| 166 | + top_classification.weight, |
| 167 | + ) |
| 168 | + successful_count += 1 |
| 169 | + else: |
| 170 | + logger.info("Image %d - No classifications", i + 1) |
| 171 | + successful_count += 1 |
| 172 | + |
| 173 | + except Exception: # noqa: PERF203 |
| 174 | + logger.exception("Failed to classify image %d", i + 1) |
| 175 | + |
| 176 | + logger.info( |
| 177 | + "Completed: %d/%d images classified successfully", |
| 178 | + successful_count, |
| 179 | + num_images, |
| 180 | + ) |
| 181 | + return successful_count |
| 182 | + |
| 183 | + |
| 184 | +async def main() -> int: |
| 185 | + """Run the classify_single examples.""" |
| 186 | + logger = logging.getLogger(__name__) |
| 187 | + load_dotenv() |
| 188 | + |
| 189 | + # OAuth credentials from environment |
| 190 | + client_id = os.getenv("OAUTH_CLIENT_ID") |
| 191 | + client_secret = os.getenv("OAUTH_CLIENT_SECRET") |
| 192 | + auth_url = os.getenv( |
| 193 | + "OAUTH_AUTH_URL", "https://crispthinking.auth0.com/oauth/token" |
| 194 | + ) |
| 195 | + audience = os.getenv("OAUTH_AUDIENCE", "crisp-athena-dev") |
| 196 | + |
| 197 | + if not client_id or not client_secret: |
| 198 | + logger.error("OAUTH_CLIENT_ID and OAUTH_CLIENT_SECRET must be set") |
| 199 | + return 1 |
| 200 | + |
| 201 | + host = os.getenv("ATHENA_HOST", "localhost") |
| 202 | + logger.info("Connecting to %s", host) |
| 203 | + |
| 204 | + # Create credential helper |
| 205 | + credential_helper = CredentialHelper( |
| 206 | + client_id=client_id, |
| 207 | + client_secret=client_secret, |
| 208 | + auth_url=auth_url, |
| 209 | + audience=audience, |
| 210 | + ) |
| 211 | + |
| 212 | + # Test token acquisition |
| 213 | + try: |
| 214 | + logger.info("Acquiring OAuth token...") |
| 215 | + token = await credential_helper.get_token() |
| 216 | + logger.info("Successfully acquired token (length: %d)", len(token)) |
| 217 | + except Exception: |
| 218 | + logger.exception("Failed to acquire OAuth token") |
| 219 | + return 1 |
| 220 | + |
| 221 | + # Configure client options |
| 222 | + options = AthenaOptions( |
| 223 | + host=host, |
| 224 | + resize_images=True, |
| 225 | + compress_images=True, |
| 226 | + timeout=30.0, # Shorter timeout for single requests |
| 227 | + affiliate="Crisp", |
| 228 | + deployment_id="single-example-deployment", # Not used |
| 229 | + ) |
| 230 | + |
| 231 | + try: |
| 232 | + # Example 1: Classify a single image |
| 233 | + logger.info("\n=== Example 1: Single Image Classification ===") |
| 234 | + success = await classify_single_image_example( |
| 235 | + logger, |
| 236 | + options, |
| 237 | + credential_helper, |
| 238 | + image_path=os.getenv("TEST_IMAGE_PATH"), # Optional image path |
| 239 | + ) |
| 240 | + |
| 241 | + if not success: |
| 242 | + logger.error("Single image classification failed") |
| 243 | + return 1 |
| 244 | + |
| 245 | + # Example 2: Classify multiple images individually |
| 246 | + logger.info("\n=== Example 2: Multiple Individual Classifications ===") |
| 247 | + successful_count = await classify_multiple_single_images_example( |
| 248 | + logger, options, credential_helper, num_images=5 |
| 249 | + ) |
| 250 | + |
| 251 | + if successful_count == 0: |
| 252 | + logger.error("No images were successfully classified") |
| 253 | + return 1 |
| 254 | + |
| 255 | + logger.info("\n=== All examples completed successfully! ===") |
| 256 | + |
| 257 | + except Exception: |
| 258 | + logger.exception("Examples failed") |
| 259 | + return 1 |
| 260 | + else: |
| 261 | + return 0 |
| 262 | + |
| 263 | + |
| 264 | +if __name__ == "__main__": |
| 265 | + logging.basicConfig( |
| 266 | + level=logging.INFO, |
| 267 | + format="%(asctime)s.%(msecs)03d %(levelname)s: %(message)s", |
| 268 | + datefmt="%H:%M:%S", |
| 269 | + ) |
| 270 | + |
| 271 | + sys.exit(asyncio.run(main())) |
0 commit comments