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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
from transformers import pipeline, AutoTokenizer, AutoModelForSequenceClassification
|
| 4 |
+
from setfit import SetFitModel
|
| 5 |
+
import json
|
| 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
|
| 15 |
+
model = None
|
| 16 |
+
tokenizer = None
|
| 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/setfit_email_classifier"
|
| 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 True
|
| 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),
|
| 61 |
+
"success": True
|
| 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)
|
| 78 |
+
probabilities = model.predict_proba(cleaned_emails)
|
| 79 |
+
|
| 80 |
+
results = []
|
| 81 |
+
for i, (pred, probs) in enumerate(zip(predictions, probabilities)):
|
| 82 |
+
results.append({
|
| 83 |
+
"label": str(pred),
|
| 84 |
+
"score": round(float(max(probs)), 4),
|
| 85 |
+
"success": True
|
| 86 |
+
})
|
| 87 |
+
|
| 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')}"
|
| 108 |
+
|
| 109 |
+
def api_classify(email_text: str) -> Dict[str, Any]:
|
| 110 |
+
"""API endpoint function"""
|
| 111 |
+
return classify_single_email(email_text)
|
| 112 |
+
|
| 113 |
+
def api_classify_batch(emails_json: str) -> str:
|
| 114 |
+
"""Batch API endpoint function"""
|
| 115 |
+
try:
|
| 116 |
+
emails = json.loads(emails_json)
|
| 117 |
+
if not isinstance(emails, list):
|
| 118 |
+
return json.dumps({"error": "Input must be a JSON array of strings"})
|
| 119 |
+
|
| 120 |
+
if len(emails) > 100: # Limit batch size
|
| 121 |
+
return json.dumps({"error": "Maximum 100 emails per batch"})
|
| 122 |
+
|
| 123 |
+
results = classify_batch_emails(emails)
|
| 124 |
+
return json.dumps({"results": results}, indent=2)
|
| 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": "applied", "score": 0.95, "success": True, "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.")
|
| 143 |
+
|
| 144 |
+
with gr.Tab("Single Email Classification"):
|
| 145 |
+
with gr.Row():
|
| 146 |
+
with gr.Column():
|
| 147 |
+
email_input = gr.Textbox(
|
| 148 |
+
label="Email Content",
|
| 149 |
+
placeholder="Paste your email content here (subject + body)...",
|
| 150 |
+
lines=8,
|
| 151 |
+
max_lines=20
|
| 152 |
+
)
|
| 153 |
+
classify_btn = gr.Button("Classify Email", variant="primary")
|
| 154 |
+
|
| 155 |
+
with gr.Column():
|
| 156 |
+
result_output = gr.Markdown(label="Classification Result")
|
| 157 |
+
|
| 158 |
+
classify_btn.click(
|
| 159 |
+
fn=gradio_classify,
|
| 160 |
+
inputs=email_input,
|
| 161 |
+
outputs=result_output
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
with gr.Tab("API Endpoints"):
|
| 165 |
+
gr.Markdown("""
|
| 166 |
+
## API Usage
|
| 167 |
+
|
| 168 |
+
### Single Email Classification
|
| 169 |
+
**POST** `/api/classify`
|
| 170 |
+
```json
|
| 171 |
+
{
|
| 172 |
+
"email_text": "Your email content here..."
|
| 173 |
+
}
|
| 174 |
+
```
|
| 175 |
+
|
| 176 |
+
### Batch Email Classification
|
| 177 |
+
**POST** `/api/classify_batch`
|
| 178 |
+
```json
|
| 179 |
+
["Email 1 content...", "Email 2 content...", "Email 3 content..."]
|
| 180 |
+
```
|
| 181 |
+
|
| 182 |
+
### Example Response
|
| 183 |
+
```json
|
| 184 |
+
{
|
| 185 |
+
"label": "job",
|
| 186 |
+
"score": 0.9234,
|
| 187 |
+
"success": true
|
| 188 |
+
}
|
| 189 |
+
```
|
| 190 |
+
""")
|
| 191 |
+
|
| 192 |
+
with gr.Row():
|
| 193 |
+
with gr.Column():
|
| 194 |
+
gr.Markdown("### Test Single API")
|
| 195 |
+
api_input = gr.Textbox(label="Email Text", lines=4)
|
| 196 |
+
api_btn = gr.Button("Test API")
|
| 197 |
+
api_output = gr.JSON(label="API Response")
|
| 198 |
+
|
| 199 |
+
api_btn.click(
|
| 200 |
+
fn=api_classify,
|
| 201 |
+
inputs=api_input,
|
| 202 |
+
outputs=api_output
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
with gr.Column():
|
| 206 |
+
gr.Markdown("### Test Batch API")
|
| 207 |
+
batch_input = gr.Textbox(
|
| 208 |
+
label="JSON Array of Emails",
|
| 209 |
+
lines=6,
|
| 210 |
+
placeholder='["Email 1 content", "Email 2 content"]'
|
| 211 |
+
)
|
| 212 |
+
batch_btn = gr.Button("Test Batch API")
|
| 213 |
+
batch_output = gr.Code(label="Batch API Response", language="json")
|
| 214 |
+
|
| 215 |
+
batch_btn.click(
|
| 216 |
+
fn=api_classify_batch,
|
| 217 |
+
inputs=batch_input,
|
| 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,
|
| 254 |
+
show_api=True,
|
| 255 |
+
share=False
|
| 256 |
+
)
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio>=4.0.0
|
| 2 |
+
torch>=1.9.0
|
| 3 |
+
transformers>=4.21.0
|
| 4 |
+
setfit>=1.0.0
|
| 5 |
+
scikit-learn>=1.1.0
|
| 6 |
+
sentence-transformers>=2.2.0
|
| 7 |
+
datasets>=2.0.0
|