Spaces:
Sleeping
Sleeping
add app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify
|
| 2 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
app = Flask(__name__)
|
| 6 |
+
|
| 7 |
+
# Load model dan tokenizer
|
| 8 |
+
tokenizer = AutoTokenizer.from_pretrained("./hate_speech_model")
|
| 9 |
+
model = AutoModelForSequenceClassification.from_pretrained("./hate_speech_model")
|
| 10 |
+
|
| 11 |
+
@app.route("/")
|
| 12 |
+
def home():
|
| 13 |
+
return jsonify({"message": "Hate Speech API is running!"})
|
| 14 |
+
|
| 15 |
+
@app.route("/predict", methods=["POST"])
|
| 16 |
+
def predict():
|
| 17 |
+
data = request.get_json()
|
| 18 |
+
|
| 19 |
+
if not data or "text" not in data:
|
| 20 |
+
return jsonify({"error": "Please provide 'text'"}), 400
|
| 21 |
+
|
| 22 |
+
text = data["text"]
|
| 23 |
+
|
| 24 |
+
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
|
| 25 |
+
with torch.no_grad():
|
| 26 |
+
outputs = model(**inputs)
|
| 27 |
+
probs = torch.nn.functional.softmax(outputs.logits, dim=1)
|
| 28 |
+
label = "Hate" if torch.argmax(probs).item() == 1 else "Non-Hate"
|
| 29 |
+
|
| 30 |
+
return jsonify({
|
| 31 |
+
"label": label,
|
| 32 |
+
"confidence": float(probs.max())
|
| 33 |
+
})
|
| 34 |
+
|
| 35 |
+
if __name__ == "__main__":
|
| 36 |
+
app.run(host="0.0.0.0", port=7860)
|