Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify
|
| 2 |
+
from transformers import AutoProcessor, AutoModelForVision2Seq
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import torch
|
| 5 |
+
import io
|
| 6 |
+
|
| 7 |
+
app = Flask(__name__)
|
| 8 |
+
|
| 9 |
+
model_id = "microsoft/phi-3-vision-instruct"
|
| 10 |
+
|
| 11 |
+
# Load processor + model
|
| 12 |
+
processor = AutoProcessor.from_pretrained(model_id)
|
| 13 |
+
model = AutoModelForVision2Seq.from_pretrained(
|
| 14 |
+
model_id,
|
| 15 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
| 16 |
+
device_map="auto"
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
@app.route("/")
|
| 20 |
+
def home():
|
| 21 |
+
return jsonify({"message": "✅ Phi-3 Vision Flask Endpoint Running"})
|
| 22 |
+
|
| 23 |
+
# Text-only
|
| 24 |
+
@app.route("/chat", methods=["POST"])
|
| 25 |
+
def chat():
|
| 26 |
+
data = request.json
|
| 27 |
+
text = data.get("text")
|
| 28 |
+
|
| 29 |
+
if not text:
|
| 30 |
+
return jsonify({"error": "No text provided"}), 400
|
| 31 |
+
|
| 32 |
+
inputs = processor(text=text, return_tensors="pt").to(model.device)
|
| 33 |
+
output = model.generate(**inputs, max_new_tokens=150)
|
| 34 |
+
response = processor.decode(output[0], skip_special_tokens=True)
|
| 35 |
+
|
| 36 |
+
return jsonify({"response": response})
|
| 37 |
+
|
| 38 |
+
# Vision + Text
|
| 39 |
+
@app.route("/vision", methods=["POST"])
|
| 40 |
+
def vision():
|
| 41 |
+
if "image" not in request.files or "text" not in request.form:
|
| 42 |
+
return jsonify({"error": "Send `image` (file) and `text` (string)."}), 400
|
| 43 |
+
|
| 44 |
+
text = request.form["text"]
|
| 45 |
+
image_file = request.files["image"]
|
| 46 |
+
|
| 47 |
+
image = Image.open(io.BytesIO(image_file.read())).convert("RGB")
|
| 48 |
+
|
| 49 |
+
inputs = processor(text=text, images=image, return_tensors="pt").to(model.device)
|
| 50 |
+
output = model.generate(**inputs, max_new_tokens=150)
|
| 51 |
+
response = processor.decode(output[0], skip_special_tokens=True)
|
| 52 |
+
|
| 53 |
+
return jsonify({"response": response})
|
| 54 |
+
|
| 55 |
+
if __name__ == "__main__":
|
| 56 |
+
app.run(host="0.0.0.0", port=7860)
|