Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import requests
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
# Set your Inference Endpoint URL and API key
|
| 7 |
+
INFERENCE_ENDPOINT = "https://your-endpoint-url" # Replace with your endpoint URL
|
| 8 |
+
API_TOKEN = "your-api-token" # Replace with your Hugging Face API token
|
| 9 |
+
|
| 10 |
+
def generate_caption(image):
|
| 11 |
+
"""
|
| 12 |
+
Sends an image to the Hugging Face Inference Endpoint for caption generation.
|
| 13 |
+
:param image: An image in PIL format.
|
| 14 |
+
:return: Generated caption or error message.
|
| 15 |
+
"""
|
| 16 |
+
headers = {"Authorization": f"Bearer {API_TOKEN}"}
|
| 17 |
+
files = {"inputs": image}
|
| 18 |
+
response = requests.post(INFERENCE_ENDPOINT, headers=headers, files=files)
|
| 19 |
+
|
| 20 |
+
if response.status_code == 200:
|
| 21 |
+
return response.json().get("generated_text", "No caption generated.")
|
| 22 |
+
else:
|
| 23 |
+
return f"Error: {response.status_code} - {response.text}"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# Gradio interface
|
| 28 |
+
|
| 29 |
+
demo = gr.Interface(
|
| 30 |
+
fn=generate_caption,
|
| 31 |
+
inputs=gr.inputs.Image(type="file", label="Upload Image"),
|
| 32 |
+
outputs=gr.outputs.Textbox(label="Generated Caption"),
|
| 33 |
+
examples=[image1, image2, image3],
|
| 34 |
+
title="Image Captioning App",
|
| 35 |
+
description=(
|
| 36 |
+
"Upload an image or use one of the predefined samples to generate a caption. "
|
| 37 |
+
"This app uses a Hugging Face Inference Endpoint for the `Salesforce/blip-image-captioning-base` model."
|
| 38 |
+
),
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
if __name__ == "__main__":
|
| 42 |
+
demo.launch()
|