Tomiwajin commited on
Commit
5dee0a5
·
verified ·
1 Parent(s): 713fdfd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -158
app.py CHANGED
@@ -6,10 +6,9 @@ import json
6
  import logging
7
  from typing import List, Dict, Any
8
  import os
9
- import traceback
10
 
11
- # Set up logging with more detailed output
12
- logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
13
  logger = logging.getLogger(__name__)
14
 
15
  # Global model variable
@@ -18,111 +17,44 @@ tokenizer = None
18
  classifier = None
19
 
20
  def load_model():
21
- """Load your trained SetFit model with detailed error handling"""
22
  global model, classifier
23
  try:
24
- logger.info("Starting model loading process...")
25
 
26
- model_name = "Tomiwajin/testClasifier"
27
- logger.info(f"Attempting to load model: {model_name}")
28
 
29
- # Check for HF token
30
- token = os.getenv("HF_TOKEN")
31
- if token:
32
- logger.info("HF_TOKEN found in environment")
33
- else:
34
- logger.warning("HF_TOKEN not found in environment - using default authentication")
35
-
36
- # Try different authentication methods
37
- auth_options = [
38
- {"use_auth_token": token} if token else {"use_auth_token": True},
39
- {"use_auth_token": True},
40
- {"use_auth_token": False},
41
- {} # No auth
42
- ]
43
 
44
- model_loaded = False
45
- last_error = None
46
 
47
- for i, auth_config in enumerate(auth_options):
48
- try:
49
- logger.info(f"Trying authentication option {i+1}: {auth_config}")
50
-
51
- model = SetFitModel.from_pretrained(
52
- model_name,
53
- **auth_config
54
- )
55
-
56
- # Test the model with a simple prediction
57
- test_text = "This is a test email about a job opportunity."
58
- test_prediction = model.predict([test_text])
59
- logger.info(f"Model test successful. Test prediction: {test_prediction}")
60
-
61
- model_loaded = True
62
- logger.info(f"Model {model_name} loaded successfully with auth option {i+1}!")
63
- break
64
-
65
- except Exception as e:
66
- last_error = e
67
- logger.warning(f"Auth option {i+1} failed: {str(e)}")
68
- continue
69
 
70
- if not model_loaded:
71
- raise last_error or Exception("All authentication methods failed")
72
-
73
  return True
74
-
75
  except Exception as e:
76
  logger.error(f"Error loading model: {e}")
77
- logger.error(f"Full traceback: {traceback.format_exc()}")
78
-
79
- # Additional debugging info
80
- logger.info("Environment check:")
81
- logger.info(f"Python version: {os.sys.version}")
82
- logger.info(f"Current working directory: {os.getcwd()}")
83
- logger.info(f"HF_HOME: {os.getenv('HF_HOME', 'Not set')}")
84
- logger.info(f"TRANSFORMERS_CACHE: {os.getenv('TRANSFORMERS_CACHE', 'Not set')}")
85
-
86
- # Check if it's a network/authentication issue
87
- if "401" in str(e) or "Unauthorized" in str(e):
88
- logger.error("Authentication error - check your HF_TOKEN or model permissions")
89
- elif "404" in str(e) or "not found" in str(e).lower():
90
- logger.error("Model not found - check if the model name is correct and publicly accessible")
91
- elif "timeout" in str(e).lower() or "connection" in str(e).lower():
92
- logger.error("Network error - check your internet connection")
93
-
94
  return False
95
 
96
  def classify_single_email(email_text: str) -> Dict[str, Any]:
97
- """Classify a single email with better error handling"""
98
  if not model:
99
- logger.warning("Model not loaded - returning dummy response")
100
- return {
101
- "label": "model_not_loaded",
102
- "score": 0.00,
103
- "success": True,
104
- "note": "Model failed to load - check logs for details"
105
- }
106
 
107
  try:
108
  # Clean and truncate text
109
  email_text = email_text.strip()[:5000] # Limit length
110
 
111
- if not email_text:
112
- return {"error": "Empty email text", "success": False}
113
-
114
- logger.debug(f"Classifying email: {email_text[:100]}...")
115
-
116
  # Get prediction using SetFit model directly
117
  predictions = model.predict([email_text])
118
- probabilities = model.predict_proba([email_text])[0] # Get probabilities for first sample
119
 
120
  # Get the predicted label and confidence
121
  predicted_label = predictions[0]
122
  confidence = max(probabilities) # Confidence is the max probability
123
 
124
- logger.debug(f"Prediction: {predicted_label}, Confidence: {confidence}")
125
-
126
  return {
127
  "label": str(predicted_label),
128
  "score": round(float(confidence), 4),
@@ -130,22 +62,16 @@ def classify_single_email(email_text: str) -> Dict[str, Any]:
130
  }
131
  except Exception as e:
132
  logger.error(f"Classification error: {e}")
133
- logger.error(f"Full traceback: {traceback.format_exc()}")
134
  return {"error": str(e), "success": False}
135
 
136
  def classify_batch_emails(emails: List[str]) -> List[Dict[str, Any]]:
137
- """Classify multiple emails with better error handling"""
138
  if not model:
139
- return [{"error": "Model not loaded", "success": False}] * len(emails)
140
 
141
  try:
142
  # Clean and truncate texts
143
- cleaned_emails = [email.strip()[:1000] for email in emails if email.strip()]
144
-
145
- if not cleaned_emails:
146
- return [{"error": "No valid emails provided", "success": False}]
147
-
148
- logger.debug(f"Batch classifying {len(cleaned_emails)} emails")
149
 
150
  # Get batch predictions
151
  predictions = model.predict(cleaned_emails)
@@ -162,24 +88,20 @@ def classify_batch_emails(emails: List[str]) -> List[Dict[str, Any]]:
162
  return results
163
  except Exception as e:
164
  logger.error(f"Batch classification error: {e}")
165
- logger.error(f"Full traceback: {traceback.format_exc()}")
166
  return [{"error": str(e), "success": False}] * len(emails)
167
 
168
  def gradio_classify(email_text: str) -> str:
169
- """Gradio interface function with better status reporting"""
170
  if not email_text.strip():
171
  return "Please enter some email text to classify."
172
 
173
  result = classify_single_email(email_text)
174
 
175
  if result.get("success"):
176
- status = "✅ Active" if model else "❌ Using Fallback"
177
  return f"""
178
  **Classification Result:**
179
- - **Model Status:** {status}
180
  - **Label:** {result['label']}
181
  - **Confidence:** {result['score']:.2%}
182
- {f"- **Note:** {result['note']}" if result.get('note') else ""}
183
  """
184
  else:
185
  return f"**Error:** {result.get('error', 'Unknown error')}"
@@ -203,39 +125,18 @@ def api_classify_batch(emails_json: str) -> str:
203
  except json.JSONDecodeError:
204
  return json.dumps({"error": "Invalid JSON format"})
205
  except Exception as e:
206
- logger.error(f"Batch API error: {e}")
207
  return json.dumps({"error": str(e)})
208
 
209
- def get_model_status() -> str:
210
- """Get detailed model status for debugging"""
211
- if model:
212
- try:
213
- # Test model functionality
214
- test_result = model.predict(["Test email"])
215
- return f"✅ Model loaded and functional (test prediction: {test_result})"
216
- except Exception as e:
217
- return f"⚠️ Model loaded but not functional: {e}"
218
- else:
219
- return "❌ Model not loaded"
220
-
221
- def reload_model():
222
- """Reload model function for debugging"""
223
- global model
224
- model = None # Reset model
225
- success = load_model()
226
- return f"Model reload {'successful' if success else 'failed'}: {get_model_status()}"
227
-
228
- # Load model on startup with detailed logging
229
- logger.info("="*50)
230
- logger.info("STARTING EMAIL CLASSIFIER APPLICATION")
231
- logger.info("="*50)
232
-
233
  model_loaded = load_model()
234
 
235
  if not model_loaded:
236
- logger.warning("Model failed to load - application will use dummy responses")
 
 
237
 
238
- # Create Gradio interface with enhanced debugging
239
  with gr.Blocks(title="Email Classifier", theme=gr.themes.Soft()) as demo:
240
  gr.Markdown("# 📧 Email Classification API")
241
  gr.Markdown("Classify emails as job-related or other categories using a trained SetFit model.")
@@ -245,7 +146,7 @@ with gr.Blocks(title="Email Classifier", theme=gr.themes.Soft()) as demo:
245
  with gr.Column():
246
  email_input = gr.Textbox(
247
  label="Email Content",
248
- placeholder="Paste your email content here (subject + body)...",
249
  lines=8,
250
  max_lines=20
251
  )
@@ -317,59 +218,36 @@ with gr.Blocks(title="Email Classifier", theme=gr.themes.Soft()) as demo:
317
  outputs=batch_output
318
  )
319
 
320
- with gr.Tab("Debug & Model Info"):
321
  gr.Markdown(f"""
322
- ### Model Status
323
- - **Initial Load Status:** {'✅ Loaded' if model_loaded else '❌ Failed to load'}
324
- - **Current Status:** Check below for real-time status
325
- """)
326
-
327
- with gr.Row():
328
- status_btn = gr.Button("Check Model Status")
329
- reload_btn = gr.Button("Reload Model", variant="secondary")
330
-
331
- status_output = gr.Textbox(label="Model Status", interactive=False)
332
-
333
- status_btn.click(
334
- fn=get_model_status,
335
- outputs=status_output
336
- )
337
-
338
- reload_btn.click(
339
- fn=reload_model,
340
- outputs=status_output
341
- )
342
-
343
- gr.Markdown(f"""
344
- ### Troubleshooting Steps
345
- 1. **Check the logs** in your console for detailed error messages
346
- 2. **Verify model name**: Is "Tomiwajin/testClasifier" correct?
347
- 3. **Check model access**: Is the model public or do you need authentication?
348
- 4. **HF Token**: Set your Hugging Face token as environment variable `HF_TOKEN`
349
- 5. **Network**: Ensure you have internet connectivity
350
- 6. **Dependencies**: Make sure `setfit` is installed: `pip install setfit`
351
-
352
  ### Model Information
 
353
  - **Model Type:** SetFit Email Classifier
354
- - **Model Name:** Tomiwajin/testClasifier
355
  - **Categories:** Job-related emails, Other emails
356
  - **API Base URL:** `https://tomiwajin-email-classifier.hf.space`
357
 
358
  ### Integration with Next.js
359
  ```javascript
360
  // Single email classification
361
- const response = await fetch('/api/classify', {{
362
  method: 'POST',
363
  headers: {{ 'Content-Type': 'application/json' }},
364
  body: JSON.stringify({{ email_text: emailContent }})
365
  }});
366
  const result = await response.json();
 
 
 
 
 
 
 
 
367
  ```
368
  """)
369
 
370
  # Launch the app with API endpoints
371
  if __name__ == "__main__":
372
- logger.info("Launching Gradio application...")
373
  demo.launch(
374
  server_name="0.0.0.0",
375
  server_port=7860,
 
6
  import logging
7
  from typing import List, Dict, Any
8
  import os
 
9
 
10
+ # Set up logging
11
+ logging.basicConfig(level=logging.INFO)
12
  logger = logging.getLogger(__name__)
13
 
14
  # Global model variable
 
17
  classifier = None
18
 
19
  def load_model():
20
+ """Load your trained SetFit model"""
21
  global model, classifier
22
  try:
 
23
 
24
+ model_name = "Tomiwajin/testClasifier"
 
25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
+ token = os.getenv("HF_TOKEN")
 
28
 
29
+ model = SetFitModel.from_pretrained(
30
+ model_name,
31
+ use_auth_token=token if token else False
32
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
+ # Create classifier directly from SetFit model
35
+ logger.info(f"Model {model_name} loaded successfully!")
 
36
  return True
 
37
  except Exception as e:
38
  logger.error(f"Error loading model: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  return False
40
 
41
  def classify_single_email(email_text: str) -> Dict[str, Any]:
42
+ """Classify a single email"""
43
  if not model:
44
+ return {"error": "Model not loaded"}
 
 
 
 
 
 
45
 
46
  try:
47
  # Clean and truncate text
48
  email_text = email_text.strip()[:5000] # Limit length
49
 
 
 
 
 
 
50
  # Get prediction using SetFit model directly
51
  predictions = model.predict([email_text])
52
+ probabilities = model.predict_proba([email_text])[0] # Get probabilities for first (and only) sample
53
 
54
  # Get the predicted label and confidence
55
  predicted_label = predictions[0]
56
  confidence = max(probabilities) # Confidence is the max probability
57
 
 
 
58
  return {
59
  "label": str(predicted_label),
60
  "score": round(float(confidence), 4),
 
62
  }
63
  except Exception as e:
64
  logger.error(f"Classification error: {e}")
 
65
  return {"error": str(e), "success": False}
66
 
67
  def classify_batch_emails(emails: List[str]) -> List[Dict[str, Any]]:
68
+ """Classify multiple emails"""
69
  if not model:
70
+ return [{"error": "Model not loaded"}] * len(emails)
71
 
72
  try:
73
  # Clean and truncate texts
74
+ cleaned_emails = [email.strip()[:1000] for email in emails]
 
 
 
 
 
75
 
76
  # Get batch predictions
77
  predictions = model.predict(cleaned_emails)
 
88
  return results
89
  except Exception as e:
90
  logger.error(f"Batch classification error: {e}")
 
91
  return [{"error": str(e), "success": False}] * len(emails)
92
 
93
  def gradio_classify(email_text: str) -> str:
94
+ """Gradio interface function"""
95
  if not email_text.strip():
96
  return "Please enter some email text to classify."
97
 
98
  result = classify_single_email(email_text)
99
 
100
  if result.get("success"):
 
101
  return f"""
102
  **Classification Result:**
 
103
  - **Label:** {result['label']}
104
  - **Confidence:** {result['score']:.2%}
 
105
  """
106
  else:
107
  return f"**Error:** {result.get('error', 'Unknown error')}"
 
125
  except json.JSONDecodeError:
126
  return json.dumps({"error": "Invalid JSON format"})
127
  except Exception as e:
 
128
  return json.dumps({"error": str(e)})
129
 
130
+ # Load model on startup
131
+ logger.info("Loading model...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  model_loaded = load_model()
133
 
134
  if not model_loaded:
135
+ logger.warning("Model failed to load - using dummy responses")
136
+ def classify_single_email(email_text: str):
137
+ return {"label": "model-load-failed", "score": 0.00, "success": False, "note": "Using dummy classifier"}
138
 
139
+ # Create Gradio interface
140
  with gr.Blocks(title="Email Classifier", theme=gr.themes.Soft()) as demo:
141
  gr.Markdown("# 📧 Email Classification API")
142
  gr.Markdown("Classify emails as job-related or other categories using a trained SetFit model.")
 
146
  with gr.Column():
147
  email_input = gr.Textbox(
148
  label="Email Content",
149
+ placeholder="Paste your email content here (body)...",
150
  lines=8,
151
  max_lines=20
152
  )
 
218
  outputs=batch_output
219
  )
220
 
221
+ with gr.Tab("Model Info"):
222
  gr.Markdown(f"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  ### Model Information
224
+ - **Status:** {'✅ Loaded' if model_loaded else '❌ Failed to load'}
225
  - **Model Type:** SetFit Email Classifier
 
226
  - **Categories:** Job-related emails, Other emails
227
  - **API Base URL:** `https://tomiwajin-email-classifier.hf.space`
228
 
229
  ### Integration with Next.js
230
  ```javascript
231
  // Single email classification
232
+ const response = await fetch('https://tomiwajin-email-classifier.hf.space/api/classify', {{
233
  method: 'POST',
234
  headers: {{ 'Content-Type': 'application/json' }},
235
  body: JSON.stringify({{ email_text: emailContent }})
236
  }});
237
  const result = await response.json();
238
+
239
+ // Batch classification
240
+ const batchResponse = await fetch('https:https://tomiwajin-email-classifier.hf.space/api/classify_batch', {{
241
+ method: 'POST',
242
+ headers: {{ 'Content-Type': 'application/json' }},
243
+ body: JSON.stringify(emailArray)
244
+ }});
245
+ const batchResults = await batchResponse.json();
246
  ```
247
  """)
248
 
249
  # Launch the app with API endpoints
250
  if __name__ == "__main__":
 
251
  demo.launch(
252
  server_name="0.0.0.0",
253
  server_port=7860,