intanrly commited on
Commit
f8d61a7
·
verified ·
1 Parent(s): e62a242

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -30
app.py CHANGED
@@ -1,45 +1,32 @@
1
- from flask import Flask, request, jsonify
2
  import torch
3
  from transformers import AutoTokenizer, AutoModelForSequenceClassification
 
 
 
 
4
 
5
- # Load model sekali aja
6
  MODEL_NAME = "taufiqdp/indonesian-sentiment"
7
- tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
8
- model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)
 
 
9
 
10
  class_names = ['negatif', 'netral', 'positif']
11
 
12
  app = Flask(__name__)
13
 
14
- @app.route("/predict", methods=["POST"])
15
  def predict():
16
- try:
17
- data = request.get_json()
18
- text = data.get("text", "")
19
-
20
- if not text.strip():
21
- return jsonify({"error": "Teks kosong"}), 400
22
-
23
- tokenized = tokenizer(text, return_tensors="pt")
24
- with torch.inference_mode():
25
- logits = model(**tokenized).logits
26
-
27
- pred_id = logits.argmax(dim=1).item()
28
- sentiment = class_names[pred_id]
29
- confidence = torch.softmax(logits, dim=1)[0][pred_id].item()
30
-
31
- return jsonify({
32
- "sentiment": sentiment,
33
- "confidence": round(confidence, 4)
34
- })
35
- except Exception as e:
36
- return jsonify({"error": str(e)}), 500
37
-
38
 
39
- @app.route("/", methods=["GET"])
40
- def home():
41
- return jsonify({"message": "Indonesian Sentiment API ready!"})
42
 
 
 
43
 
44
  if __name__ == "__main__":
45
  app.run(host="0.0.0.0", port=7860)
 
1
+ import os
2
  import torch
3
  from transformers import AutoTokenizer, AutoModelForSequenceClassification
4
+ from flask import Flask, request, jsonify
5
+
6
+ # Set cache dir ke folder yang bisa ditulis
7
+ os.environ["TRANSFORMERS_CACHE"] = "/tmp"
8
 
 
9
  MODEL_NAME = "taufiqdp/indonesian-sentiment"
10
+
11
+ # Load model dan tokenizer
12
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, cache_dir="/tmp")
13
+ model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME, cache_dir="/tmp")
14
 
15
  class_names = ['negatif', 'netral', 'positif']
16
 
17
  app = Flask(__name__)
18
 
19
+ @app.route("/", methods=["POST"])
20
  def predict():
21
+ data = request.get_json()
22
+ text = data.get("inputs", "")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
+ tokenized_text = tokenizer(text, return_tensors='pt')
25
+ with torch.inference_mode():
26
+ logits = model(**tokenized_text).logits
27
 
28
+ result = class_names[logits.argmax(dim=1).item()]
29
+ return jsonify([{"label": result, "score": float(torch.softmax(logits, dim=1).max().item())}])
30
 
31
  if __name__ == "__main__":
32
  app.run(host="0.0.0.0", port=7860)