Spaces:
Sleeping
Sleeping
SatyamSinghal
commited on
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import requests
|
3 |
+
import os
|
4 |
+
|
5 |
+
# Hugging Face API configuration
|
6 |
+
API_URL = "https://api-inference.huggingface.co/models/nlpconnect/vit-gpt2-image-captioning"
|
7 |
+
API_KEY = os.getenv("HF_API_KEY") # Fetch the API key from Hugging Face secrets
|
8 |
+
|
9 |
+
headers = {"Authorization": f"Bearer {API_KEY}"}
|
10 |
+
|
11 |
+
def generate_caption(image):
|
12 |
+
"""Queries the Hugging Face API to generate an image caption."""
|
13 |
+
if not API_KEY:
|
14 |
+
return "API key is missing! Please set it in Hugging Face secrets."
|
15 |
+
response = requests.post(API_URL, headers=headers, files={"file": image})
|
16 |
+
if response.status_code == 200:
|
17 |
+
result = response.json()
|
18 |
+
return result[0].get("generated_text", "No caption generated.")
|
19 |
+
else:
|
20 |
+
return f"Error: {response.status_code}, {response.text}"
|
21 |
+
|
22 |
+
# Gradio UI components
|
23 |
+
title = "✨Captionator_X ✨"
|
24 |
+
description = """
|
25 |
+
Upload an image, and let AI describe it for you in a creative and accurate way!
|
26 |
+
This application uses Hugging Face's state-of-the-art image captioning model.
|
27 |
+
"""
|
28 |
+
theme = gr.themes.Monochrome()
|
29 |
+
|
30 |
+
with gr.Blocks(theme=theme) as app:
|
31 |
+
gr.Markdown(f"<h1 style='text-align: center;'>{title}</h1>")
|
32 |
+
gr.Markdown(f"<p style='text-align: center;'>{description}</p>")
|
33 |
+
|
34 |
+
with gr.Row():
|
35 |
+
with gr.Column():
|
36 |
+
image_input = gr.Image(type="file", label="Upload Your Image", elem_id="image-uploader")
|
37 |
+
with gr.Column():
|
38 |
+
output_text = gr.Textbox(label="Generated Caption", lines=4, interactive=False, elem_id="output-text")
|
39 |
+
|
40 |
+
submit_button = gr.Button("✨ Generate Caption ✨", elem_id="submit-btn")
|
41 |
+
submit_button.click(generate_caption, inputs=[image_input], outputs=[output_text])
|
42 |
+
|
43 |
+
gr.Markdown("<p style='text-align: center; font-size: 0.9rem;'>Powered by Hugging Face 🤗 and Gradio 🚀</p>")
|
44 |
+
|
45 |
+
app.launch()
|