Spaces:
Sleeping
Sleeping
Update predictor.py
Browse files- predictor.py +49 -44
predictor.py
CHANGED
|
@@ -1,44 +1,49 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
# Force Hugging Face to use /tmp as cache
|
| 4 |
+
os.environ["HF_HOME"] = "/tmp/huggingface"
|
| 5 |
+
|
| 6 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
# ✅ Load all three models
|
| 10 |
+
model_names = {
|
| 11 |
+
"label0": "SreyaDvn/savedModelLebel0",
|
| 12 |
+
"label1": "SreyaDvn/savedModelLebel1",
|
| 13 |
+
"balanced": "SreyaDvn/sentiment-model"
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
pipelines = {}
|
| 17 |
+
for name, path in model_names.items():
|
| 18 |
+
tokenizer = AutoTokenizer.from_pretrained(path)
|
| 19 |
+
model = AutoModelForSequenceClassification.from_pretrained(path)
|
| 20 |
+
pipelines[name] = pipeline(
|
| 21 |
+
"text-classification",
|
| 22 |
+
model=model,
|
| 23 |
+
tokenizer=tokenizer,
|
| 24 |
+
device=0 if torch.cuda.is_available() else -1
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
print("✅ All models loaded successfully!")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def predict_sentiment(text: str):
|
| 31 |
+
"""
|
| 32 |
+
Runs input text through all models,
|
| 33 |
+
then selects the best model by IF-ELSE logic.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
results = {}
|
| 37 |
+
for name, pipe in pipelines.items():
|
| 38 |
+
out = pipe(text, truncation=True)[0] # e.g. {'label': 'LABEL_1', 'score': 0.92}
|
| 39 |
+
results[name] = out
|
| 40 |
+
|
| 41 |
+
# ---- IF-ELSE LOGIC ----
|
| 42 |
+
# Currently: Pick the prediction with the HIGHEST confidence score
|
| 43 |
+
best_model = max(results, key=lambda k: results[k]['score'])
|
| 44 |
+
|
| 45 |
+
return {
|
| 46 |
+
"chosen_model": best_model,
|
| 47 |
+
"prediction": results[best_model],
|
| 48 |
+
"all_results": results
|
| 49 |
+
}
|