Spaces:
Sleeping
Sleeping
Commit ·
6a7d2bf
1
Parent(s): 3cc1949
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, request, render_template
|
| 2 |
+
from transformers import VisionEncoderDecoderModel, ViTFeatureExtractor, AutoTokenizer
|
| 3 |
+
import torch
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import io
|
| 6 |
+
|
| 7 |
+
app = Flask(__name__)
|
| 8 |
+
|
| 9 |
+
# Load the pre-trained model and components
|
| 10 |
+
model = VisionEncoderDecoderModel.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
|
| 11 |
+
feature_extractor = ViTFeatureExtractor.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
|
| 12 |
+
tokenizer = AutoTokenizer.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
|
| 13 |
+
|
| 14 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 15 |
+
model.to(device)
|
| 16 |
+
|
| 17 |
+
# Set the maximum caption length and other generation parameters
|
| 18 |
+
max_length = 16
|
| 19 |
+
num_beams = 4
|
| 20 |
+
gen_kwargs = {"max_length": max_length, "num_beams": num_beams}
|
| 21 |
+
|
| 22 |
+
# Define the image captioning function
|
| 23 |
+
def vit2distilgpt2(image):
|
| 24 |
+
try:
|
| 25 |
+
image = io.BytesIO(image.read())
|
| 26 |
+
i_image = Image.open(image)
|
| 27 |
+
except Exception as e:
|
| 28 |
+
print("Error opening image:", str(e))
|
| 29 |
+
return "Error processing image"
|
| 30 |
+
|
| 31 |
+
if i_image.mode != "RGB":
|
| 32 |
+
i_image = i_image.convert(mode="RGB")
|
| 33 |
+
|
| 34 |
+
pixel_values = feature_extractor(images=i_image, return_tensors="pt").pixel_values
|
| 35 |
+
pixel_values = pixel_values.to(device)
|
| 36 |
+
|
| 37 |
+
# Generate a caption for the input image
|
| 38 |
+
output_ids = model.generate(pixel_values, **gen_kwargs)
|
| 39 |
+
|
| 40 |
+
preds = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
|
| 41 |
+
preds = [pred.strip() for pred in preds]
|
| 42 |
+
|
| 43 |
+
return preds[0]
|
| 44 |
+
|
| 45 |
+
@app.route("/", methods=["GET", "POST"])
|
| 46 |
+
def index():
|
| 47 |
+
caption = None
|
| 48 |
+
if request.method == "POST":
|
| 49 |
+
if "image" in request.files:
|
| 50 |
+
image = request.files["image"]
|
| 51 |
+
caption = vit2distilgpt2(image)
|
| 52 |
+
|
| 53 |
+
return render_template("index.html", caption=caption)
|
| 54 |
+
|
| 55 |
+
if __name__ == "__main__":
|
| 56 |
+
app.run(host="0.0.0.0", port=8080, debug=True)
|