Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, HTTPException, Header
|
2 |
+
from pydantic import BaseModel
|
3 |
+
import numpy as np
|
4 |
+
from tensorflow.keras.models import load_model
|
5 |
+
from fastapi.middleware.cors import CORSMiddleware
|
6 |
+
import torch
|
7 |
+
import torch.nn.functional as F
|
8 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
9 |
+
|
10 |
+
# Load model Keras untuk prediksi stres
|
11 |
+
model = load_model("model_stresss.h5")
|
12 |
+
labels = ['Tidak Stress', 'Sedikit Stress', 'Normal', 'Stress', 'Sangat Stress']
|
13 |
+
|
14 |
+
# Load model Hugging Face
|
15 |
+
model_dir = "Chipan/indobert-emotion"
|
16 |
+
tokenizer = AutoTokenizer.from_pretrained(model_dir)
|
17 |
+
model_bert = AutoModelForSequenceClassification.from_pretrained(model_dir)
|
18 |
+
model_bert.eval()
|
19 |
+
|
20 |
+
# Mapping label untuk emosi
|
21 |
+
label_map = {0: "Bersyukur", 1: "Marah", 2: "Sedih", 3: "Senang", 4: "Stress"}
|
22 |
+
|
23 |
+
# Setup FastAPI
|
24 |
+
app = FastAPI()
|
25 |
+
app.add_middleware(
|
26 |
+
CORSMiddleware,
|
27 |
+
allow_origins=["*"],
|
28 |
+
allow_credentials=True,
|
29 |
+
allow_methods=["*"],
|
30 |
+
allow_headers=["*"],
|
31 |
+
)
|
32 |
+
|
33 |
+
# Data schemas
|
34 |
+
class CheckInData(BaseModel):
|
35 |
+
mood: float
|
36 |
+
sleep: float
|
37 |
+
anxiety: float
|
38 |
+
exercise: float
|
39 |
+
support: float
|
40 |
+
|
41 |
+
class TextInput(BaseModel):
|
42 |
+
text: str
|
43 |
+
|
44 |
+
@app.post("/predict")
|
45 |
+
def predict(data: CheckInData, authorization: str = Header(None)):
|
46 |
+
try:
|
47 |
+
raw = np.array([[data.mood, data.sleep, data.anxiety, data.exercise, data.support]])
|
48 |
+
prediction = model.predict(raw)
|
49 |
+
idx = int(np.argmax(prediction))
|
50 |
+
return {
|
51 |
+
"predicted_index": idx,
|
52 |
+
"predicted_label": labels[idx],
|
53 |
+
"raw_prediction": prediction.tolist()
|
54 |
+
}
|
55 |
+
except Exception as e:
|
56 |
+
raise HTTPException(status_code=500, detail=f"Prediction error: {str(e)}")
|
57 |
+
|
58 |
+
@app.post("/analyze")
|
59 |
+
def analyze_emotion(input: TextInput):
|
60 |
+
try:
|
61 |
+
inputs = tokenizer(input.text, return_tensors="pt", padding=True, truncation=True, max_length=128)
|
62 |
+
with torch.no_grad():
|
63 |
+
logits = model_bert(**inputs).logits
|
64 |
+
probs = F.softmax(logits, dim=1)
|
65 |
+
idx = int(torch.argmax(probs))
|
66 |
+
return {
|
67 |
+
"emotion": label_map.get(idx, "unknown"),
|
68 |
+
"confidence": round(probs[0, idx].item(), 4)
|
69 |
+
}
|
70 |
+
except Exception as e:
|
71 |
+
raise HTTPException(status_code=500, detail=f"Emotion analysis error: {str(e)}")
|
72 |
+
|
73 |
+
@app.get("/")
|
74 |
+
def root():
|
75 |
+
return {"status": "ok"}
|