Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dotenv import load_dotenv, find_dotenv
|
| 2 |
+
import os
|
| 3 |
+
import io
|
| 4 |
+
from io import BytesIO
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import base64
|
| 7 |
+
import requests
|
| 8 |
+
import json
|
| 9 |
+
import warnings
|
| 10 |
+
import gradio as gr
|
| 11 |
+
|
| 12 |
+
# Suppress specific warnings
|
| 13 |
+
warnings.filterwarnings("ignore", message=".*Using the model-agnostic default `max_length`.*")
|
| 14 |
+
|
| 15 |
+
# Load environment variables from .env file
|
| 16 |
+
load_dotenv(find_dotenv())
|
| 17 |
+
hf_api_key = os.getenv('HF_API_KEY')
|
| 18 |
+
endpoint_url = os.getenv('HF_API_ITT_BASE')
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def generate_caption(image):
|
| 22 |
+
"""
|
| 23 |
+
Sends an image to the Hugging Face Inference Endpoint for caption generation.
|
| 24 |
+
:param image: An image in PIL format.
|
| 25 |
+
:return: Generated caption or error message.
|
| 26 |
+
"""
|
| 27 |
+
headers = {"Authorization": f"Bearer {hf_api_key}"}
|
| 28 |
+
files = {"inputs": image}
|
| 29 |
+
response = requests.post(endpoint_url, headers=headers, files=files)
|
| 30 |
+
|
| 31 |
+
if response.status_code == 200:
|
| 32 |
+
return response.json().get("generated_text", "No caption generated.")
|
| 33 |
+
else:
|
| 34 |
+
return f"Error: {response.status_code} - {response.text}"
|
| 35 |
+
|
| 36 |
+
# Predefined sample images
|
| 37 |
+
def get_sample_images():
|
| 38 |
+
"""
|
| 39 |
+
Returns a list of predefined sample images in the assets directory.
|
| 40 |
+
"""
|
| 41 |
+
sample_dir = "CreatureCaptures"
|
| 42 |
+
return [
|
| 43 |
+
os.path.join(sample_dir, file)
|
| 44 |
+
for file in os.listdir(sample_dir)
|
| 45 |
+
if file.lower().endswith((".png", ".jpg", ".jpeg"))
|
| 46 |
+
]
|
| 47 |
+
|
| 48 |
+
# Gradio interface
|
| 49 |
+
sample_images = get_sample_images() # Load predefined sample images
|
| 50 |
+
demo = gr.Interface(
|
| 51 |
+
fn=generate_caption,
|
| 52 |
+
inputs=gr.inputs.Image(type="file", label="Upload Image"),
|
| 53 |
+
outputs=gr.outputs.Textbox(label="Generated Caption"),
|
| 54 |
+
examples=sample_images,
|
| 55 |
+
title="Image Captioning App",
|
| 56 |
+
description=(
|
| 57 |
+
"Upload an image or use one of the predefined samples to generate a caption. "
|
| 58 |
+
"This app uses a Hugging Face Inference Endpoint for the `Salesforce/blip-image-captioning-base` model."
|
| 59 |
+
),
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
if __name__ == "__main__":
|
| 63 |
+
demo.launch()
|