File size: 1,601 Bytes
0bd2821 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
from flask import Flask, request, jsonify
from transformers import ViTImageProcessor, AutoModelForImageClassification
from PIL import Image
import requests
import torch
# Inisialisasi Flask app
app = Flask(__name__)
# Inisialisasi model dan processor
processor = ViTImageProcessor.from_pretrained('AdamCodd/vit-base-nsfw-detector')
model = AutoModelForImageClassification.from_pretrained('AdamCodd/vit-base-nsfw-detector')
# Fungsi untuk memproses gambar dan membuat prediksi
def predict_image(url):
try:
# Mengambil gambar dari URL
image = Image.open(requests.get(url, stream=True).raw)
# Memproses gambar dan membuat prediksi
inputs = processor(images=image, return_tensors="pt")
outputs = model(**inputs)
logits = outputs.logits
# Mengambil prediksi kelas
predicted_class_idx = logits.argmax(-1).item()
predicted_label = model.config.id2label[predicted_class_idx]
return predicted_label
except Exception as e:
return str(e)
# Route untuk menerima permintaan POST dengan URL gambar
@app.route('/predict', methods=['POST'])
def predict():
if request.method == 'POST':
data = request.get_json()
if 'image_url' not in data:
return jsonify({'error': 'URL gambar tidak ditemukan dalam request'}), 400
image_url = data['image_url']
prediction = predict_image(image_url)
return jsonify({'predicted_class': prediction})
# Menjalankan Flask app
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
|