Spaces:
Runtime error
Runtime error
123LETSPLAY
commited on
Commit
•
9f1674d
1
Parent(s):
1387b9b
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, request, jsonify, render_template
|
2 |
+
from transformers import BlipProcessor, BlipForConditionalGeneration
|
3 |
+
from PIL import Image
|
4 |
+
import torch
|
5 |
+
import os
|
6 |
+
|
7 |
+
app = Flask(__name__)
|
8 |
+
|
9 |
+
# Load the processor and model
|
10 |
+
processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
11 |
+
model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
|
12 |
+
|
13 |
+
@app.route('/')
|
14 |
+
def home():
|
15 |
+
return render_template('index.html')
|
16 |
+
|
17 |
+
@app.route('/upload', methods=['POST'])
|
18 |
+
def upload():
|
19 |
+
if 'file' not in request.files:
|
20 |
+
return jsonify({"error": "No file uploaded"}), 400
|
21 |
+
|
22 |
+
file = request.files['file']
|
23 |
+
|
24 |
+
if file.filename == '':
|
25 |
+
return jsonify({"error": "No selected file"}), 400
|
26 |
+
|
27 |
+
# Save the file to a temporary location
|
28 |
+
image_path = os.path.join('uploads', file.filename)
|
29 |
+
file.save(image_path)
|
30 |
+
|
31 |
+
# Load and process the image
|
32 |
+
image = Image.open(image_path)
|
33 |
+
inputs = processor(image, return_tensors="pt")
|
34 |
+
|
35 |
+
# Generate caption
|
36 |
+
with torch.no_grad():
|
37 |
+
out = model.generate(**inputs)
|
38 |
+
|
39 |
+
# Decode the output
|
40 |
+
caption = processor.decode(out[0], skip_special_tokens=True)
|
41 |
+
|
42 |
+
# Clean up the uploaded file
|
43 |
+
os.remove(image_path)
|
44 |
+
|
45 |
+
return jsonify({"caption": caption})
|
46 |
+
|
47 |
+
if __name__ == '__main__':
|
48 |
+
app.run(debug=True)
|