|
from flask import Flask, request, jsonify |
|
from transformers import ViTImageProcessor, AutoModelForImageClassification |
|
from PIL import Image |
|
import requests |
|
import torch |
|
|
|
|
|
app = Flask(__name__) |
|
|
|
|
|
processor = ViTImageProcessor.from_pretrained('AdamCodd/vit-base-nsfw-detector') |
|
model = AutoModelForImageClassification.from_pretrained('AdamCodd/vit-base-nsfw-detector') |
|
|
|
|
|
def predict_image(url): |
|
try: |
|
|
|
image = Image.open(requests.get(url, stream=True).raw) |
|
|
|
|
|
inputs = processor(images=image, return_tensors="pt") |
|
outputs = model(**inputs) |
|
logits = outputs.logits |
|
|
|
|
|
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) |
|
|
|
|
|
@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}) |
|
|
|
|
|
if __name__ == '__main__': |
|
app.run(host='0.0.0.0', port=5000, debug=True) |
|
|