|
| 1 | +from logging import getLogger |
| 2 | + |
| 3 | +from azure.ai.vision.imageanalysis import ImageAnalysisClient |
| 4 | +from azure.ai.vision.imageanalysis.models import VisualFeatures |
| 5 | +from azure.core.credentials import AzureKeyCredential |
| 6 | + |
| 7 | +from backend.settings.azure_ai_vision import Settings |
| 8 | + |
| 9 | +logger = getLogger(__name__) |
| 10 | + |
| 11 | + |
| 12 | +class AzureAiVisionClient: |
| 13 | + def __init__(self, settings: Settings) -> None: |
| 14 | + self.settings = settings |
| 15 | + |
| 16 | + def get_image_analysis_client(self) -> ImageAnalysisClient: |
| 17 | + return ImageAnalysisClient( |
| 18 | + endpoint=self.settings.azure_ai_vision_endpoint, |
| 19 | + credential=AzureKeyCredential(self.settings.azure_ai_vision_api_key), |
| 20 | + ) |
| 21 | + |
| 22 | + def analyze_image( |
| 23 | + self, |
| 24 | + image: bytes, |
| 25 | + ) -> dict: |
| 26 | + image_analysis_client = self.get_image_analysis_client() |
| 27 | + result = image_analysis_client.analyze( |
| 28 | + image_data=image, |
| 29 | + visual_features=[ |
| 30 | + VisualFeatures.CAPTION, |
| 31 | + VisualFeatures.READ, |
| 32 | + ], |
| 33 | + ) |
| 34 | + logger.info("Analyzed image") |
| 35 | + return result.as_dict() |
| 36 | + |
| 37 | + def vectorize_image( |
| 38 | + self, |
| 39 | + image: bytes, |
| 40 | + ) -> dict: |
| 41 | + # FIXME: replace with Azure SDK when available |
| 42 | + from urllib.parse import urljoin |
| 43 | + |
| 44 | + import requests |
| 45 | + |
| 46 | + url = urljoin( |
| 47 | + self.settings.azure_ai_vision_endpoint, |
| 48 | + "/computervision/retrieval:vectorizeImage", |
| 49 | + ) |
| 50 | + params = { |
| 51 | + "overload": "stream", |
| 52 | + "api-version": "2023-02-01-preview", |
| 53 | + "modelVersion": "latest", |
| 54 | + } |
| 55 | + headers = { |
| 56 | + "Content-Type": "application/octet-stream", |
| 57 | + "Ocp-Apim-Subscription-Key": self.settings.azure_ai_vision_api_key, |
| 58 | + } |
| 59 | + response = requests.post( |
| 60 | + url=url, |
| 61 | + params=params, |
| 62 | + headers=headers, |
| 63 | + data=image, |
| 64 | + ) |
| 65 | + response.raise_for_status() |
| 66 | + return response.json() |
0 commit comments