Spaces:
Runtime error
Runtime error
Jiayu Shi
commited on
Commit
·
afbc5a8
1
Parent(s):
dff3e4b
app.py
Browse files- app.py +41 -0
- requirements.txt +2 -0
app.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
from transformers import GPT2TokenizerFast, ViTImageProcessor, VisionEncoderDecoderModel
|
| 4 |
+
|
| 5 |
+
# Setup device, model, tokenizer, and feature extractor
|
| 6 |
+
device = 'cpu'
|
| 7 |
+
model_checkpoint = "Stoneman/IG-caption-generator-nlpconnect-all"
|
| 8 |
+
feature_extractor = ViTImageProcessor.from_pretrained(model_checkpoint)
|
| 9 |
+
tokenizer = GPT2TokenizerFast.from_pretrained(model_checkpoint)
|
| 10 |
+
model = VisionEncoderDecoderModel.from_pretrained(model_checkpoint).to(device)
|
| 11 |
+
|
| 12 |
+
# Prediction function
|
| 13 |
+
def predict(image, max_length=128):
|
| 14 |
+
image = image.convert('RGB')
|
| 15 |
+
pixel_values = feature_extractor(images=image, return_tensors="pt").pixel_values.to(device)
|
| 16 |
+
caption_ids = model.generate(pixel_values, max_length=max_length)[0]
|
| 17 |
+
caption_text = tokenizer.decode(caption_ids, skip_special_tokens=True)
|
| 18 |
+
return caption_text
|
| 19 |
+
|
| 20 |
+
# Define input and output components
|
| 21 |
+
input_component = gr.components.Image(label="Upload any Image", type="pil")
|
| 22 |
+
output_component = gr.components.Textbox(label="Captions")
|
| 23 |
+
|
| 24 |
+
# Example images
|
| 25 |
+
examples = [f"example{i}.JPG" for i in range(1, 10)]
|
| 26 |
+
|
| 27 |
+
# Interface
|
| 28 |
+
title = "IG-caption-generator"
|
| 29 |
+
description = "Made by: Jiayu Shi"
|
| 30 |
+
interface = gr.Interface(
|
| 31 |
+
fn=predict,
|
| 32 |
+
description=description,
|
| 33 |
+
inputs=input_component,
|
| 34 |
+
theme="huggingface",
|
| 35 |
+
outputs=output_component,
|
| 36 |
+
examples=examples,
|
| 37 |
+
title=title,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
# Launch interface
|
| 41 |
+
interface.launch(debug=True)
|
requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
transformers
|
| 2 |
+
torch
|