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)