MohitRajput45 commited on
Commit
cb223c6
·
verified ·
1 Parent(s): f220034

Update src/core_model/predict.py

Browse files
Files changed (1) hide show
  1. src/core_model/predict.py +14 -36
src/core_model/predict.py CHANGED
@@ -1,14 +1,15 @@
 
1
  import os
2
  import torch
3
  import torch.nn.functional as F
4
  from transformers import XLMRobertaTokenizer, XLMRobertaForSequenceClassification
5
 
6
  class MindGuardPredictor:
7
- # 1. Identify the Model Hub ID
 
8
  self.model_id = "MohitRajput45/mindguard-xlmr"
9
 
10
  # 2. Load the components
11
- # Note: If your files are in the root of the repo, remove subfolder="final_mindguard_model"
12
  try:
13
  self.tokenizer = XLMRobertaTokenizer.from_pretrained(
14
  self.model_id,
@@ -21,17 +22,11 @@ class MindGuardPredictor:
21
  print("✅ Model and Tokenizer loaded successfully from Hub.")
22
  except Exception as e:
23
  print(f"❌ Error loading model: {e}")
24
- # Fallback attempt without subfolder if the above fails
25
  self.tokenizer = XLMRobertaTokenizer.from_pretrained(self.model_id)
26
  self.model = XLMRobertaForSequenceClassification.from_pretrained(self.model_id)
27
 
28
- # --- THE FIX: The English Translation Dictionary ---
29
- # Paste the exact dictionary that printed in your Colab terminal here!
30
- # This is the 35-emotion dictionary from your earlier local test:
31
- # --- THE FIX: The English Translation Dictionary ---
32
- # --- THE FIX: The Final Sanitized Translation Dictionary ---
33
- # --- The Final Sanitized Translation Dictionary ---
34
- # Maps the AI's mathematical output (0-34) back to human-readable English words.
35
  self.emotion_map = {
36
  0: 'Anxiety', 1: 'Bipolar', 2: 'Depression', 3: 'Normal',
37
  4: 'Personality disorder', 5: 'Stress', 6: 'Suicidal', 7: 'admiration',
@@ -44,16 +39,13 @@ class MindGuardPredictor:
44
  32: 'remorse', 33: 'sadness', 34: 'surprise'
45
  }
46
 
47
- # Detect if the computer has a GPU ("cuda"), otherwise fall back to standard processor ("cpu").
48
  self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
49
- # Physically move the neural network to the selected hardware.
50
  self.model.to(self.device)
51
- # CRITICAL: Lock the model in "evaluation" mode so its weights cannot be accidentally changed during predictions.
52
  self.model.eval()
53
 
54
- # A clinical triage function to categorize specific emotions into action-oriented risk buckets.
55
  def determine_risk_level(self, emotion):
56
- # Standardize the text to lowercase to prevent matching errors (e.g., 'Panic' vs 'panic')
57
  emotion = emotion.lower()
58
  high_risk = ['panic', 'severe anxiety', 'depression', 'grief', 'suicidal', 'personality disorder']
59
  medium_risk = ['stress', 'anxiety', 'anger', 'burnout', 'fear', 'nervousness']
@@ -65,36 +57,26 @@ class MindGuardPredictor:
65
  else:
66
  return "Low"
67
 
68
- # The core engine function. Takes English text, passes it through the AI, and returns a dictionary of results.
69
  def predict(self, text):
70
- # 1. Convert the English sentence into a PyTorch tensor (numbers), padding/truncating it to exactly 128 tokens.
 
71
  inputs = self.tokenizer(text, return_tensors="pt", truncation=True, max_length=128, padding=True)
72
- # Move the newly created number tensors to the GPU/CPU to match the model.
73
  inputs = {key: val.to(self.device) for key, val in inputs.items()}
74
 
75
- # 2. Turn off the gradient engine (memory saver) because we are predicting, not training.
76
  with torch.no_grad():
77
- # Feed the numbers into the neural network.
78
  outputs = self.model(**inputs)
79
- # Extract the raw, unformatted mathematical scores for all 35 classes.
80
  logits = outputs.logits
81
 
82
- # 3. Apply Softmax to convert raw math scores into readable percentages (0.0 to 1.0) that sum to 100%.
83
  probabilities = F.softmax(logits, dim=-1)
84
- # Find the single highest percentage (confidence_score) and its corresponding slot number (predicted_class_id).
85
  confidence_score, predicted_class_id = torch.max(probabilities, dim=-1)
86
 
87
- # --- THE FIX: Translate the math ID back to English ---
88
- # Extract the pure Python integer from the PyTorch tensor.
89
  class_id_number = predicted_class_id.item()
90
-
91
- # Look up the number in our dictionary. If it can't find it, default to "Unknown"
92
  predicted_label = self.emotion_map.get(class_id_number, "Unknown")
93
-
94
- # Pass the English emotion to our triage function to determine severity.
95
  risk_level = self.determine_risk_level(predicted_label)
96
 
97
- # Return a cleanly formatted dictionary that a frontend web app or API can easily read.
98
  return {
99
  "text": text,
100
  "emotion": predicted_label,
@@ -102,15 +84,11 @@ class MindGuardPredictor:
102
  "risk_level": risk_level
103
  }
104
 
105
- # --- Quick Test Block ---
106
- # This block only executes if you run this exact file in the terminal. It is ignored if imported elsewhere.
107
  if __name__ == "__main__":
108
  predictor = MindGuardPredictor()
109
  sample_text = "I have a massive presentation tomorrow and my chest is tight."
110
  result = predictor.predict(sample_text)
111
-
112
  print("\n--- Prediction Results ---")
113
- print(f"Input: {result['text']}")
114
- print(f"Emotion: {result['emotion']}")
115
- print(f"Confidence: {result['confidence']}%")
116
  print(f"Risk Level: {result['risk_level']}")
 
1
+ # src/core_model/predict.py
2
  import os
3
  import torch
4
  import torch.nn.functional as F
5
  from transformers import XLMRobertaTokenizer, XLMRobertaForSequenceClassification
6
 
7
  class MindGuardPredictor:
8
+ def __init__(self):
9
+ # 1. Identify the Model Hub ID
10
  self.model_id = "MohitRajput45/mindguard-xlmr"
11
 
12
  # 2. Load the components
 
13
  try:
14
  self.tokenizer = XLMRobertaTokenizer.from_pretrained(
15
  self.model_id,
 
22
  print("✅ Model and Tokenizer loaded successfully from Hub.")
23
  except Exception as e:
24
  print(f"❌ Error loading model: {e}")
25
+ # Fallback attempt if subfolder isn't present
26
  self.tokenizer = XLMRobertaTokenizer.from_pretrained(self.model_id)
27
  self.model = XLMRobertaForSequenceClassification.from_pretrained(self.model_id)
28
 
29
+ # 3. Emotion Mapping (Mathematical ID to English Word)
 
 
 
 
 
 
30
  self.emotion_map = {
31
  0: 'Anxiety', 1: 'Bipolar', 2: 'Depression', 3: 'Normal',
32
  4: 'Personality disorder', 5: 'Stress', 6: 'Suicidal', 7: 'admiration',
 
39
  32: 'remorse', 33: 'sadness', 34: 'surprise'
40
  }
41
 
42
+ # 4. Device Setup (GPU vs CPU)
43
  self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
 
44
  self.model.to(self.device)
 
45
  self.model.eval()
46
 
 
47
  def determine_risk_level(self, emotion):
48
+ """Categorizes emotions into clinical risk buckets."""
49
  emotion = emotion.lower()
50
  high_risk = ['panic', 'severe anxiety', 'depression', 'grief', 'suicidal', 'personality disorder']
51
  medium_risk = ['stress', 'anxiety', 'anger', 'burnout', 'fear', 'nervousness']
 
57
  else:
58
  return "Low"
59
 
 
60
  def predict(self, text):
61
+ """The core engine: Text -> Tensor -> Prediction."""
62
+ # Tokenize input
63
  inputs = self.tokenizer(text, return_tensors="pt", truncation=True, max_length=128, padding=True)
 
64
  inputs = {key: val.to(self.device) for key, val in inputs.items()}
65
 
66
+ # Run inference
67
  with torch.no_grad():
 
68
  outputs = self.model(**inputs)
 
69
  logits = outputs.logits
70
 
71
+ # Convert math to percentages
72
  probabilities = F.softmax(logits, dim=-1)
 
73
  confidence_score, predicted_class_id = torch.max(probabilities, dim=-1)
74
 
75
+ # Map ID back to English
 
76
  class_id_number = predicted_class_id.item()
 
 
77
  predicted_label = self.emotion_map.get(class_id_number, "Unknown")
 
 
78
  risk_level = self.determine_risk_level(predicted_label)
79
 
 
80
  return {
81
  "text": text,
82
  "emotion": predicted_label,
 
84
  "risk_level": risk_level
85
  }
86
 
87
+ # --- Standard Testing Block ---
 
88
  if __name__ == "__main__":
89
  predictor = MindGuardPredictor()
90
  sample_text = "I have a massive presentation tomorrow and my chest is tight."
91
  result = predictor.predict(sample_text)
 
92
  print("\n--- Prediction Results ---")
93
+ print(f"Emotion: {result['emotion']} ({result['confidence']}%)")
 
 
94
  print(f"Risk Level: {result['risk_level']}")