v1-a commited on
Commit
3099d71
·
1 Parent(s): 624156a

Correction for runtime error

Browse files
Files changed (1) hide show
  1. app.py +10 -27
app.py CHANGED
@@ -17,7 +17,6 @@ LABEL_COLS = ['anger', 'fear', 'joy', 'sadness', 'surprise']
17
  DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
18
 
19
  # --- CORRECTED FILE PATHS ---
20
- # These paths now correctly point to the 'model/' directory.
21
  MODEL_FILE = "Deploy/models/best_deberta_0.8558.pt"
22
  THRESHOLD_FILE = "Deploy/models/optimal_thresholds_deberta.npy"
23
 
@@ -50,21 +49,22 @@ def load_global_assets():
50
 
51
  print(f"Loading assets from {MODEL_FILE}...")
52
  try:
53
- # 🔑 FIX: Add use_fast=False to resolve the 'NoneType' object has no attribute 'endswith' error
54
- # This forces the use of the "slow" tokenizer which correctly resolves the spm.model path.
55
  tokenizer = AutoTokenizer.from_pretrained(
56
  CONFIG['MODEL_NAME'],
57
- use_fast=False # <--- CRITICAL FIX FOR DEBERTA-V3
58
- )
59
-
 
 
60
  model = DebertaClassifier(
61
  n_classes=CONFIG['OUTPUT_DIM'],
62
  model_name=CONFIG['MODEL_NAME'],
63
  dropout=CONFIG['DROPOUT']
64
  )
65
-
66
  # Load the trained PyTorch state dict
67
- # Ensure the file path is correct relative to the Space root directory
68
  state_dict = torch.load(MODEL_FILE, map_location=torch.device('cpu'))
69
  model.load_state_dict(state_dict)
70
  model.to(DEVICE)
@@ -77,26 +77,20 @@ def load_global_assets():
77
  print("Model and thresholds loaded successfully.")
78
  except Exception as e:
79
  print(f"Error loading model assets: {e}")
80
- # Use gr.Warning instead of gr.Error to allow the app to initialize but show a warning
81
  raise gr.Error(f"Deployment failed to load assets. Check file paths. Error: {e}")
 
82
  # Call the loading function once before defining the interface
83
  load_global_assets()
84
 
85
-
86
  # --- 3. Gradio Interface Function ---
87
  def classify_emotion(text: str) -> str:
88
- """
89
- Takes user text, runs inference, applies thresholds, and returns
90
- a formatted string of predicted emotions.
91
- """
92
  if not text.strip():
93
  return "Please enter a sentence to classify."
94
 
95
- # Check if the model failed to load during startup
96
  if model is None:
97
  return "Model failed to load during startup. Check the Space logs for errors."
98
 
99
- # Tokenize the input text
100
  inputs = tokenizer(
101
  text,
102
  return_tensors="pt",
@@ -104,46 +98,35 @@ def classify_emotion(text: str) -> str:
104
  padding='max_length',
105
  max_length=CONFIG['MAX_LEN']
106
  )
107
-
108
  input_ids = inputs['input_ids'].to(DEVICE)
109
  attention_mask = inputs['attention_mask'].to(DEVICE)
110
 
111
- # Get model outputs
112
  with torch.no_grad():
113
  logits = model(input_ids=input_ids, attention_mask=attention_mask)
114
 
115
- # Apply Sigmoid activation
116
  probabilities = torch.sigmoid(logits).squeeze(0).cpu().numpy()
117
-
118
- # Apply the custom label-specific thresholds
119
  predictions = probabilities > thresholds
120
 
121
- # Map predictions back to your emotion labels
122
  predicted_emotions = [
123
  f"**{LABEL_COLS[i]}** ({probabilities[i]:.2f} > {thresholds[i]:.2f})"
124
  for i, pred in enumerate(predictions) if pred
125
  ]
126
 
127
  if predicted_emotions:
128
- # Format the output as a list for the user
129
  output_list = "\n".join([f"- {e}" for e in predicted_emotions])
130
  return f"**Detected Emotions:**\n{output_list}"
131
  else:
132
  return "No emotions were detected above the optimal thresholds."
133
 
134
-
135
  # --- 4. Define and Launch Gradio Interface ---
136
- # Input component: Textbox
137
  text_input = gr.Textbox(
138
  lines=5,
139
  placeholder="Example: I was so furious when they broke my camera, but happy I had a backup.",
140
  label="Text Input"
141
  )
142
 
143
- # Output component: Textbox (set to display markdown for bold text and lists)
144
  text_output = gr.Markdown(label="Predicted Emotions")
145
 
146
- # Create the Gradio Interface
147
  gr.Interface(
148
  fn=classify_emotion,
149
  inputs=text_input,
 
17
  DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
18
 
19
  # --- CORRECTED FILE PATHS ---
 
20
  MODEL_FILE = "Deploy/models/best_deberta_0.8558.pt"
21
  THRESHOLD_FILE = "Deploy/models/optimal_thresholds_deberta.npy"
22
 
 
49
 
50
  print(f"Loading assets from {MODEL_FILE}...")
51
  try:
52
+ # Load slow tokenizer explicitly to avoid 'NoneType' endswith error
53
+ # Alternative: from transformers import DebertaV2Tokenizer
54
  tokenizer = AutoTokenizer.from_pretrained(
55
  CONFIG['MODEL_NAME'],
56
+ use_fast=False,
57
+ force_download=True, # force fresh download to avoid cache issues
58
+ local_files_only=False
59
+ )
60
+
61
  model = DebertaClassifier(
62
  n_classes=CONFIG['OUTPUT_DIM'],
63
  model_name=CONFIG['MODEL_NAME'],
64
  dropout=CONFIG['DROPOUT']
65
  )
66
+
67
  # Load the trained PyTorch state dict
 
68
  state_dict = torch.load(MODEL_FILE, map_location=torch.device('cpu'))
69
  model.load_state_dict(state_dict)
70
  model.to(DEVICE)
 
77
  print("Model and thresholds loaded successfully.")
78
  except Exception as e:
79
  print(f"Error loading model assets: {e}")
 
80
  raise gr.Error(f"Deployment failed to load assets. Check file paths. Error: {e}")
81
+
82
  # Call the loading function once before defining the interface
83
  load_global_assets()
84
 
 
85
  # --- 3. Gradio Interface Function ---
86
  def classify_emotion(text: str) -> str:
87
+ """Tokenizes input, runs model inference, applies thresholds, formats output."""
 
 
 
88
  if not text.strip():
89
  return "Please enter a sentence to classify."
90
 
 
91
  if model is None:
92
  return "Model failed to load during startup. Check the Space logs for errors."
93
 
 
94
  inputs = tokenizer(
95
  text,
96
  return_tensors="pt",
 
98
  padding='max_length',
99
  max_length=CONFIG['MAX_LEN']
100
  )
 
101
  input_ids = inputs['input_ids'].to(DEVICE)
102
  attention_mask = inputs['attention_mask'].to(DEVICE)
103
 
 
104
  with torch.no_grad():
105
  logits = model(input_ids=input_ids, attention_mask=attention_mask)
106
 
 
107
  probabilities = torch.sigmoid(logits).squeeze(0).cpu().numpy()
 
 
108
  predictions = probabilities > thresholds
109
 
 
110
  predicted_emotions = [
111
  f"**{LABEL_COLS[i]}** ({probabilities[i]:.2f} > {thresholds[i]:.2f})"
112
  for i, pred in enumerate(predictions) if pred
113
  ]
114
 
115
  if predicted_emotions:
 
116
  output_list = "\n".join([f"- {e}" for e in predicted_emotions])
117
  return f"**Detected Emotions:**\n{output_list}"
118
  else:
119
  return "No emotions were detected above the optimal thresholds."
120
 
 
121
  # --- 4. Define and Launch Gradio Interface ---
 
122
  text_input = gr.Textbox(
123
  lines=5,
124
  placeholder="Example: I was so furious when they broke my camera, but happy I had a backup.",
125
  label="Text Input"
126
  )
127
 
 
128
  text_output = gr.Markdown(label="Predicted Emotions")
129
 
 
130
  gr.Interface(
131
  fn=classify_emotion,
132
  inputs=text_input,