import os import requests from dotenv import load_dotenv load_dotenv() def caption_from_url(image_url): """ Generates a caption for an image using the Azure Computer Vision API. Parameters: image_url (str): The URL of the image for which a caption should be generated. Returns: str: The generated caption for the image. Raises: requests.exceptions.HTTPError: If the request to the Azure API fails. """ subscription_key = os.getenv('AZURE_SUBSCRIPTION_KEY') endpoint = 'https://icmvp.cognitiveservices.azure.com/' analyze_url = endpoint + "computervision/imageanalysis:analyze?api-version=2023-10-01" headers = { "Content-Type": "application/json", 'Ocp-Apim-Subscription-Key': subscription_key } params = { 'features': 'caption' } data = {'url': image_url} response = requests.post(analyze_url, headers=headers, params=params, json=data) response.raise_for_status() analysis = response.json() # Extract the description from the returned JSON description = analysis['captionResult']['text'] return description