Utkarsh64's picture
Upload 5 files
25b651b verified
Raw History Blame Contribute Delete
2.46 kB
import pickle
import numpy as np
import re
from typing import Dict, List, Any
class LogisticEmotionClassifier:
def __init__(self, model_path: str):
with open(model_path, 'rb') as f:
model_data = pickle.load(f)
self.model = model_data['model']
self.vectorizer = model_data['vectorizer']
self.emotions = [
'admiration', 'amusement', 'anger', 'annoyance', 'approval', 'caring',
'confusion', 'curiosity', 'desire', 'disappointment', 'disapproval',
'disgust', 'embarrassment', 'excitement', 'fear', 'gratitude', 'grief',
'joy', 'love', 'nervousness', 'optimism', 'pride', 'realization',
'relief', 'remorse', 'sadness', 'surprise', 'neutral'
]
def preprocess_text(self, text: str) -> str:
# Handle contractions
contractions = {
"won't": "will not", "can't": "cannot", "n't": " not",
"'re": " are", "'ve": " have", "'ll": " will", "'d": " would",
"'m": " am", "it's": "it is", "that's": "that is"
}
for contraction, expansion in contractions.items():
text = text.replace(contraction, expansion)
# Clean and normalize
text = re.sub(r'[^a-zA-Z\s]', '', text)
text = re.sub(r'\s+', ' ', text)
return text.lower().strip()
def predict(self, text: str, threshold: float = 0.5) -> Dict[str, Any]:
# Preprocess
processed_text = self.preprocess_text(text)
# Vectorize
text_vector = self.vectorizer.transform([processed_text])
# Predict
predictions = self.model.predict(text_vector)
probabilities = self.model.predict_proba(text_vector)
# Format results
results = []
for i, emotion in enumerate(self.emotions):
prob = probabilities[i][0, 1] if hasattr(probabilities[i], 'shape') else 0.5
results.append({
'label': emotion,
'score': float(prob)
})
# Sort by score
results.sort(key=lambda x: x['score'], reverse=True)
return results
# For HuggingFace Inference API
def handler(event, context):
classifier = LogisticEmotionClassifier('model.pkl')
inputs = event.get('inputs', '')
return classifier.predict(inputs)