Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,4 @@
|
|
| 1 |
from fastapi import FastAPI
|
| 2 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
from pydantic import BaseModel
|
| 4 |
import joblib
|
| 5 |
import logging
|
|
@@ -11,18 +10,10 @@ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(
|
|
| 11 |
|
| 12 |
app = FastAPI()
|
| 13 |
|
| 14 |
-
# === CORS (fixes connection issues with frontend) ===
|
| 15 |
-
app.add_middleware(
|
| 16 |
-
CORSMiddleware,
|
| 17 |
-
allow_origins=["*"],
|
| 18 |
-
allow_credentials=True,
|
| 19 |
-
allow_methods=["*"],
|
| 20 |
-
allow_headers=["*"],
|
| 21 |
-
)
|
| 22 |
-
|
| 23 |
models = None
|
| 24 |
|
| 25 |
def to_native(value):
|
|
|
|
| 26 |
if isinstance(value, np.integer):
|
| 27 |
return int(value)
|
| 28 |
elif isinstance(value, np.floating):
|
|
@@ -34,29 +25,23 @@ def load_models():
|
|
| 34 |
if models is not None:
|
| 35 |
return
|
| 36 |
logging.info("Loading models...")
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
models = (en_vectorizer, en_classifier, en_label_encoder,
|
| 55 |
-
si_vectorizer, si_classifier, si_label_encoder, tamil_pipe)
|
| 56 |
-
logging.info("✅ All models loaded successfully.")
|
| 57 |
-
except Exception as e:
|
| 58 |
-
logging.error(f"Model loading failed: {type(e).__name__} - {e}")
|
| 59 |
-
raise
|
| 60 |
|
| 61 |
@app.on_event("startup")
|
| 62 |
def startup_event():
|
|
@@ -72,36 +57,35 @@ def root():
|
|
| 72 |
|
| 73 |
@app.post("/predict")
|
| 74 |
def predict(req: PredictRequest):
|
| 75 |
-
if not req.text
|
| 76 |
return {"error": "Text cannot be empty"}
|
| 77 |
|
| 78 |
en_vec, en_clf, en_le, si_vec, si_clf, si_le, tamil_pipe = models
|
| 79 |
|
| 80 |
try:
|
| 81 |
-
|
| 82 |
-
if lang == "english":
|
| 83 |
X = en_vec.transform([req.text])
|
| 84 |
pred = en_clf.predict(X)[0]
|
| 85 |
emotion = en_le.inverse_transform([pred])[0]
|
| 86 |
-
emotion = to_native(emotion)
|
| 87 |
return {"emotion": emotion, "language": "English"}
|
| 88 |
|
| 89 |
-
elif
|
| 90 |
X = si_vec.transform([req.text])
|
| 91 |
pred = si_clf.predict(X)[0]
|
| 92 |
emotion = si_le.inverse_transform([pred])[0]
|
| 93 |
emotion = to_native(emotion)
|
| 94 |
return {"emotion": emotion, "language": "Sinhala"}
|
| 95 |
|
| 96 |
-
elif
|
| 97 |
res = tamil_pipe(req.text)[0]
|
| 98 |
-
return {
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
}
|
| 103 |
else:
|
| 104 |
return {"error": f"Unsupported language: {req.language}"}
|
|
|
|
| 105 |
except Exception as e:
|
| 106 |
-
logging.error(f"Prediction error: {
|
| 107 |
-
return {"error": "Prediction failed. Please try again
|
|
|
|
| 1 |
from fastapi import FastAPI
|
|
|
|
| 2 |
from pydantic import BaseModel
|
| 3 |
import joblib
|
| 4 |
import logging
|
|
|
|
| 10 |
|
| 11 |
app = FastAPI()
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
models = None
|
| 14 |
|
| 15 |
def to_native(value):
|
| 16 |
+
"""Fix for numpy.int64 / numpy types that FastAPI can't serialize"""
|
| 17 |
if isinstance(value, np.integer):
|
| 18 |
return int(value)
|
| 19 |
elif isinstance(value, np.floating):
|
|
|
|
| 25 |
if models is not None:
|
| 26 |
return
|
| 27 |
logging.info("Loading models...")
|
| 28 |
+
|
| 29 |
+
# ==================== CHANGED ONLY THIS PART ====================
|
| 30 |
+
en_vectorizer = joblib.load(hf_hub_download("E-motionAssistant/English_LR_Model_New", "tfidf_vectorizer.joblib"))
|
| 31 |
+
en_classifier = joblib.load(hf_hub_download("E-motionAssistant/English_LR_Model_New", "logreg_model.joblib"))
|
| 32 |
+
en_label_encoder = joblib.load(hf_hub_download("E-motionAssistant/English_LR_Model_New", "label_encoder.joblib"))
|
| 33 |
+
# ================================================================
|
| 34 |
+
|
| 35 |
+
si_vectorizer = joblib.load(hf_hub_download("E-motionAssistant/Sinhala_Text_Emotion_Model_LR", "tfidf_vectorizer.joblib"))
|
| 36 |
+
si_classifier = joblib.load(hf_hub_download("E-motionAssistant/Sinhala_Text_Emotion_Model_LR", "logreg_model.joblib"))
|
| 37 |
+
si_label_encoder = joblib.load(hf_hub_download("E-motionAssistant/Sinhala_Text_Emotion_Model_LR", "label_encoder.joblib"))
|
| 38 |
+
|
| 39 |
+
tamil_pipe = pipeline("text-classification", model="E-motionAssistant/Tamil_Emotion_Recognition_Model", device=-1)
|
| 40 |
+
|
| 41 |
+
models = (en_vectorizer, en_classifier, en_label_encoder,
|
| 42 |
+
si_vectorizer, si_classifier, si_label_encoder, tamil_pipe)
|
| 43 |
+
|
| 44 |
+
logging.info("✅ All models loaded.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
@app.on_event("startup")
|
| 47 |
def startup_event():
|
|
|
|
| 57 |
|
| 58 |
@app.post("/predict")
|
| 59 |
def predict(req: PredictRequest):
|
| 60 |
+
if not req.text.strip():
|
| 61 |
return {"error": "Text cannot be empty"}
|
| 62 |
|
| 63 |
en_vec, en_clf, en_le, si_vec, si_clf, si_le, tamil_pipe = models
|
| 64 |
|
| 65 |
try:
|
| 66 |
+
if req.language.lower() == "english": # Made case-insensitive (safer)
|
|
|
|
| 67 |
X = en_vec.transform([req.text])
|
| 68 |
pred = en_clf.predict(X)[0]
|
| 69 |
emotion = en_le.inverse_transform([pred])[0]
|
| 70 |
+
emotion = to_native(emotion) # ← This fixes the 500 error
|
| 71 |
return {"emotion": emotion, "language": "English"}
|
| 72 |
|
| 73 |
+
elif req.language.lower() == "sinhala":
|
| 74 |
X = si_vec.transform([req.text])
|
| 75 |
pred = si_clf.predict(X)[0]
|
| 76 |
emotion = si_le.inverse_transform([pred])[0]
|
| 77 |
emotion = to_native(emotion)
|
| 78 |
return {"emotion": emotion, "language": "Sinhala"}
|
| 79 |
|
| 80 |
+
elif req.language.lower() == "tamil":
|
| 81 |
res = tamil_pipe(req.text)[0]
|
| 82 |
+
return {"emotion": res["label"],
|
| 83 |
+
"confidence": round(res["score"], 3),
|
| 84 |
+
"language": "Tamil"}
|
| 85 |
+
|
|
|
|
| 86 |
else:
|
| 87 |
return {"error": f"Unsupported language: {req.language}"}
|
| 88 |
+
|
| 89 |
except Exception as e:
|
| 90 |
+
logging.error(f"Prediction error: {e}")
|
| 91 |
+
return {"error": "Prediction failed. Please try again."}
|