Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import VisionEncoderDecoderModel, ViTImageProcessor, AutoTokenizer
|
3 |
+
from PIL import Image
|
4 |
+
import torch
|
5 |
+
|
6 |
+
# Load the pre-trained model, processor, and tokenizer
|
7 |
+
model = VisionEncoderDecoderModel.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
|
8 |
+
feature_extractor = ViTImageProcessor.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
|
9 |
+
tokenizer = AutoTokenizer.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
|
10 |
+
|
11 |
+
# Set the device to GPU if available
|
12 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
13 |
+
model.to(device)
|
14 |
+
|
15 |
+
# Define generation parameters
|
16 |
+
max_length = 16
|
17 |
+
num_beams = 4
|
18 |
+
|
19 |
+
# Function to generate caption from image
|
20 |
+
def generate_caption(image):
|
21 |
+
if image is None:
|
22 |
+
return "Please upload an image."
|
23 |
+
# Convert image to RGB if it's not
|
24 |
+
if image.mode != "RGB":
|
25 |
+
image = image.convert(mode="RGB")
|
26 |
+
# Preprocess the image
|
27 |
+
pixel_values = feature_extractor(images=image, return_tensors="pt").pixel_values
|
28 |
+
pixel_values = pixel_values.to(device)
|
29 |
+
# Generate caption
|
30 |
+
output_ids = model.generate(pixel_values, max_length=max_length, num_beams=num_beams)
|
31 |
+
caption = tokenizer.decode(output_ids[0], skip_special_tokens=True)
|
32 |
+
return caption.strip()
|
33 |
+
|
34 |
+
# Create Gradio interface
|
35 |
+
iface = gr.Interface(
|
36 |
+
fn=generate_caption,
|
37 |
+
inputs=gr.Image(type="pil", label="Upload an Image"),
|
38 |
+
outputs=gr.Textbox(label="Generated Caption"),
|
39 |
+
title="🖼️ AI Image Caption Generator",
|
40 |
+
description="Upload an image, and the AI will generate a descriptive caption for it.",
|
41 |
+
allow_flagging="never"
|
42 |
+
)
|
43 |
+
|
44 |
+
# Launch the app
|
45 |
+
if __name__ == "__main__":
|
46 |
+
iface.launch()
|