Spaces:
Sleeping
Sleeping
import openai | |
import gradio as gr | |
import os | |
# Set your OpenAI API Key | |
openai.api_key = "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" # Replace with your API key | |
def generate_caption(image): | |
"""Generate a caption for the uploaded image using OpenAI's GPT-4 Vision API.""" | |
with open(image, "rb") as img_file: | |
response = openai.chat.completions.create( | |
model="gpt-4-turbo", | |
messages=[ | |
{ | |
"role": "system", | |
"content": "You are an AI assistant that describes images accurately." | |
}, | |
{ | |
"role": "user", | |
"content": [ | |
{"type": "text", "text": "Describe the contents of this image in detail."}, | |
{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64," + img_file.read().decode()}}, | |
], | |
}, | |
], | |
max_tokens=100 | |
) | |
caption = response.choices[0].message.content | |
return caption | |
# Gradio UI | |
iface = gr.Interface( | |
fn=generate_caption, | |
inputs=gr.Image(type="filepath"), | |
outputs="text", | |
title="Image Captioning App", | |
description="Upload an image, and the AI will generate a descriptive caption." | |
) | |
# Run the app | |
if __name__ == "__main__": | |
iface.launch() |