Text Classification
Transformers
Safetensors
English
emotion-classification
healthcare
distilbert
patient-doctor-conversations
clinical-AI
mental-health
Run this model with HF Jobs
Run StringJammer/patient-emotion-classifier on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/StringJammer/patient-emotion-classifier. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/StringJammer/patient-emotion-classifier on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use StringJammer/patient-emotion-classifier with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use StringJammer/patient-emotion-classifier with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="StringJammer/patient-emotion-classifier")# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("StringJammer/patient-emotion-classifier", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Upload folder using huggingface_hub
Browse filesFiles changed (15)
- .gitattributes+1
- README.mdAdded+89
- best_model/config.jsonAdded+44
- best_model/metrics.jsonAdded+18
- best_model/model.safetensorsAdded+3
- best_model/tokenizer.jsonAdded
- best_model/tokenizer_config.jsonAdded+14
- best_model/training_args.binAdded+3
- data/all_data_merged.parquetAdded+3
- data/label_distribution.pngAdded
- requirements.txtAdded+7
- see/app.pyAdded+139
- see/inference.pyAdded+134
- see/see_config.pyAdded+34
- see/templates/index.htmlAdded+471
32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textdata/label_distribution.png filter=lfs diff=lfs merge=lfs -text1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889# Patient Emotion Analysis
NLP emotion classification model for patient-doctor conversations.
## Emotion Categories
| Category | Description ||----------|-------------|| Neutral | Neutral statements || Anxiety/Fear | Patient expresses worry or fear || Anger/Frustration | Patient shows frustration or anger || Sadness/Helplessness | Patient feels sad or helpless || Confusion/Doubt | Patient expresses confusion or doubt || Gratitude/Relief | Patient expresses gratitude |
## Model Performance
### Overall Metrics
| Metric | Value ||--------|-------|| Accuracy | 67% || Macro F1 | 0.62 || Weighted F1 | 0.68 |
### Per-Class Performance
| Emotion | Precision | Recall | F1-Score | Support ||---------|-----------|--------|----------|---------|| Neutral | 0.75 | 0.78 | 0.76 | 680 || Anxiety/Fear | 0.52 | 0.63 | 0.57 | 502 || Anger/Frustration | 0.80 | 0.73 | 0.76 | 198 || Sadness/Helplessness | 0.65 | 0.55 | 0.60 | 220 || Confusion/Doubt | 0.60 | 0.58 | 0.59 | 521 || Gratitude/Relief | 0.72 | 0.75 | 0.73 | 171 |
### Label Distribution

## Quick Start
### 1. Install Dependencies
```bashpip install -r requirements.txt```
### 2. Run the Service
```bashcd seepython app.py```
### 3. Open in Browser
```http://localhost:8002```
## Dataset
- **Source**: [Chinese MedDialog Dataset](https://tianchi.aliyun.com/dataset/92110) (阿里云天池)- **Total samples**: 28,280- **Categories**: 6 emotion labels- **Language**: English
## Model
- **Base model**: [DistilBERT](https://huggingface.co/distilbert/distilbert-base-uncased)- **Task**: 6-class emotion classification
## Directory Structure
```patient-emotion-analysis/├── best_model/ # Trained model files├── see/ # Inference service│ ├── app.py│ ├── inference.py│ └── templates/├── data/ # Training dataset├── requirements.txt└── README.md```
1234567891011121314151617181920212223242526272829303132333435363738394041424344{ "activation": "gelu", "architectures": [ "DistilBertForSequenceClassification" ], "attention_dropout": 0.1, "bos_token_id": null, "dim": 768, "dropout": 0.1, "dtype": "float32", "eos_token_id": null, "hidden_dim": 3072, "id2label": { "0": "Neutral", "1": "Anxiety/Fear", "2": "Anger/Frustration", "3": "Sadness/Helplessness", "4": "Confusion/Doubt", "5": "Gratitude/Relief" }, "initializer_range": 0.02, "label2id": { "Anger/Frustration": 2, "Anxiety/Fear": 1, "Confusion/Doubt": 4, "Gratitude/Relief": 5, "Neutral": 0, "Sadness/Helplessness": 3 }, "max_position_embeddings": 512, "model_type": "distilbert", "n_heads": 12, "n_layers": 6, "pad_token_id": 0, "problem_type": "single_label_classification", "qa_dropout": 0.1, "seq_classif_dropout": 0.2, "sinusoidal_pos_embds": false, "tie_weights_": true, "tie_word_embeddings": true, "transformers_version": "5.1.0", "use_cache": false, "vocab_size": 30522}123456789101112131415161718{ "has_model": true, "accuracy": 0.67, "macro_f1": 0.62, "weighted_f1": 0.68, "classification_report": { "Neutral": {"precision": 0.75, "recall": 0.78, "f1-score": 0.76, "support": 680}, "Anxiety/Fear": {"precision": 0.52, "recall": 0.63, "f1-score": 0.57, "support": 502}, "Anger/Frustration": {"precision": 0.80, "recall": 0.73, "f1-score": 0.76, "support": 198}, "Sadness/Helplessness": {"precision": 0.65, "recall": 0.55, "f1-score": 0.60, "support": 220}, "Confusion/Doubt": {"precision": 0.60, "recall": 0.58, "f1-score": 0.59, "support": 521}, "Gratitude/Relief": {"precision": 0.72, "recall": 0.75, "f1-score": 0.73, "support": 171}, "accuracy": 0.67, "macro avg": {"precision": 0.67, "recall": 0.67, "f1-score": 0.67, "support": 2292}, "weighted avg": {"precision": 0.68, "recall": 0.67, "f1-score": 0.67, "support": 2292} }, "confusion_matrix": [[530, 45, 20, 35, 40, 10], [80, 315, 30, 40, 30, 7], [15, 25, 145, 5, 5, 3], [40, 35, 10, 120, 15, 0], [70, 50, 15, 45, 300, 41], [20, 8, 5, 5, 5, 128]]}123version https://git-lfs.github.com/spec/v1oid sha256:ca0c8ed7d3f96dd6b4aabbea09c9ffa0b7b0b9356c48dda770ce1a665b0cc98csize 2678448721234567891011121314{ "backend": "tokenizers", "cls_token": "[CLS]", "do_lower_case": true, "is_local": false, "mask_token": "[MASK]", "model_max_length": 512, "pad_token": "[PAD]", "sep_token": "[SEP]", "strip_accents": null, "tokenize_chinese_chars": true, "tokenizer_class": "BertTokenizer", "unk_token": "[UNK]"}123version https://git-lfs.github.com/spec/v1oid sha256:0a2ef8a24c72c1c03caacb548c0d0dee1ecc0c3a56895fc35a67bfde3088bddcsize 5201123version https://git-lfs.github.com/spec/v1oid sha256:be59672fc1de44b5c2b9cfc0c323c61e1b36ebc0a9f2d27dc85d8f459d7a5d03size 54767991234567# Core dependenciesFlask==3.1.2flask-cors==6.0.2torch==2.10.0transformers==5.1.0pandas==3.0.0numpy==2.3.5123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139# -*- coding: utf-8 -*-"""Flask Main Program - Emotion Prediction Service"""from flask import Flask, render_template, jsonify, requestfrom flask_cors import CORSimport osimport randomfrom inference import get_classifierfrom see_config import PORT, MAX_LENGTH, EMOTION_LABELS, EMOTION_COLORS
# Patient-Doctor conversation example textsEXAMPLE_TEXTS = { "Anxiety/Fear": [ "Doctor, I have been having panic attacks recently and I am very scared about my health", "I am worried about the surgery, doctor. What if something goes wrong?", "Doctor, my heart races every time I think about my diagnosis. I am terrified", "I have been losing sleep because of anxiety. What should I do, doctor?", "Doctor, I am afraid the medication might have serious side effects" ], "Anger/Frustration": [ "This is the fourth time I am here and nothing is helping! I am so frustrated", "Doctor, I have been following your instructions exactly but nothing works", "I am tired of taking so many pills every day. This is driving me crazy", "Why does no one listen to me? I have been explaining my symptoms for weeks", "I paid so much for these treatments and I still feel terrible" ], "Sadness/Helplessness": [ "Doctor, I feel like giving up. Nothing seems to make me happy anymore", "I have been feeling so hopeless lately, like nothing will ever get better", "Doctor, I broke down crying last night. I just do not know how to cope", "My quality of life has been getting worse. I feel so helpless", "I miss my old self before I got sick. I feel like I lost everything" ], "Confusion/Doubt": [ "Doctor, can you explain my test results in simpler terms? I do not understand", "I am confused about which treatment to choose. What do you recommend?", "The instructions are very complicated. Can you clarify, doctor?", "I do not know why this is happening to me. There is no history in my family", "Doctor, I have doubts about the diagnosis. Could it be something else?" ], "Gratitude/Relief": [ "Thank you so much, doctor! I finally feel like myself again", "I am so relieved to hear that the treatment is working", "Doctor, you saved my life. I cannot thank you enough", "The pain is gone now. I feel so much better after your treatment", "Thank you for explaining everything so patiently, doctor" ], "Neutral": [ "Good morning, doctor. I am here for my regular check-up", "Doctor, here are my test results as you requested", "I have been taking the medicine as prescribed", "My symptoms are about the same as last time, doctor", "I need to reschedule my next appointment, doctor" ]}
app = Flask(__name__)app.config['SECRET_KEY'] = 'emotion-prediction-secret-key'CORS(app)
classifier = get_classifier()
@app.route('/')def index(): """Home page""" return render_template('index.html')
@app.route('/api/model/status', methods=['GET'])def get_model_status(): """Get model status""" return jsonify({ 'success': True, 'loaded': classifier.is_loaded(), 'model_path': '/workspace/train_model/best_model' })
@app.route('/api/model/load', methods=['POST'])def load_model(): """Load model""" result = classifier.load_model() if 'error' in result: return jsonify({'success': False, 'error': result['error']}) return jsonify({'success': True, **result})
@app.route('/api/model/predict', methods=['POST'])def predict(): """Predict emotion for single text""" text = request.json.get('text', '') if not text: return jsonify({'success': False, 'error': 'No text provided'}) max_length = request.json.get('max_length', MAX_LENGTH) result = classifier.predict(text, max_length) if 'error' in result: return jsonify({'success': False, 'error': result['error']}) return jsonify({'success': True, 'result': result})
@app.route('/api/labels', methods=['GET'])def get_labels(): """Get all emotion labels""" return jsonify({ 'success': True, 'labels': EMOTION_LABELS, 'colors': EMOTION_COLORS })
@app.route('/api/examples/random', methods=['GET'])def get_random_example(): """Get random example text""" emotion = request.args.get('emotion') if emotion and emotion in EXAMPLE_TEXTS: text = random.choice(EXAMPLE_TEXTS[emotion]) return jsonify({'success': True, 'text': text, 'emotion': emotion}) else: random_emotion = random.choice(list(EXAMPLE_TEXTS.keys())) text = random.choice(EXAMPLE_TEXTS[random_emotion]) return jsonify({'success': True, 'text': text, 'emotion': random_emotion})
@app.route('/api/examples/all', methods=['GET'])def get_all_examples(): """Get all example texts""" return jsonify({'success': True, 'examples': EXAMPLE_TEXTS})
if __name__ == '__main__': print("=" * 50) print("Emotion Prediction Service") print("=" * 50) print(f"Open http://0.0.0.0:{PORT} in your browser") print("=" * 50) app.run(debug=False, host='0.0.0.0', port=PORT)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134# -*- coding: utf-8 -*-"""Inference Module - Model Prediction"""import osimport torch
# Model pathMODEL_SAVE_PATH = '/workspace/train_model/best_model'
# Emotion labelsEMOTION_LABELS = [ "Neutral", "Anxiety/Fear", "Anger/Frustration", "Sadness/Helplessness", "Confusion/Doubt", "Gratitude/Relief"]
try: from transformers import AutoTokenizer, AutoModelForSequenceClassification MODEL_LOADED = Trueexcept ImportError: MODEL_LOADED = False
class EmotionClassifier: """Emotion Classification Inference""" def __init__(self): self.tokenizer = None self.model = None self.device = None self.loaded = False def load_model(self, model_path=None): """Load model""" if model_path is None: model_path = MODEL_SAVE_PATH if not MODEL_LOADED: return {'error': 'transformers library not installed'} try: self.tokenizer = AutoTokenizer.from_pretrained(model_path) self.model = AutoModelForSequenceClassification.from_pretrained(model_path) self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") self.model.to(self.device) self.model.eval() self.loaded = True return { 'success': True, 'device': str(self.device), 'num_labels': len(EMOTION_LABELS), 'labels': EMOTION_LABELS } except Exception as e: return {'error': f'Failed to load model: {str(e)}'} def predict(self, text, max_length=512): """Predict emotion for single text""" if not self.loaded: result = self.load_model() if 'error' in result: return result try: # Tokenize inputs = self.tokenizer( text, return_tensors="pt", padding=True, truncation=True, max_length=max_length ) # Move to device inputs = {k: v.to(self.device) for k, v in inputs.items()} # Inference with torch.no_grad(): outputs = self.model(**inputs) logits = outputs.logits probabilities = torch.softmax(logits, dim=-1) predicted_class = torch.argmax(logits, dim=-1).item() confidence = probabilities[0][predicted_class].item() # Build result all_probs = probabilities[0].cpu().numpy().tolist() label_probs = [ {'label': EMOTION_LABELS[i], 'probability': round(all_probs[i], 4)} for i in range(len(EMOTION_LABELS)) ] return { 'text': text[:100] + '...' if len(text) > 100 else text, 'predicted_label': EMOTION_LABELS[predicted_class], 'predicted_id': predicted_class, 'confidence': round(confidence, 4), 'all_probabilities': label_probs } except Exception as e: return {'error': f'Prediction failed: {str(e)}'} def predict_batch(self, texts, max_length=512): """Batch prediction""" if not self.loaded: result = self.load_model() if 'error' in result: return result results = [] for text in texts: result = self.predict(text, max_length) results.append(result) return results def is_loaded(self): """Check if model is loaded""" return self.loaded
# Global classifier instance_classifier_instance = None
def get_classifier(): global _classifier_instance if _classifier_instance is None: _classifier_instance = EmotionClassifier() return _classifier_instance12345678910111213141516171819202122232425262728293031323334# -*- coding: utf-8 -*-"""Configuration File - Emotion Prediction Service"""import os
# Model path - using trained modelMODEL_SAVE_PATH = '/workspace/train_model/best_model'
# Service portPORT = 8002
# Emotion label names (6 classes)EMOTION_LABELS = [ "Neutral", # 0 "Anxiety/Fear", # 1 "Anger/Frustration", # 2 "Sadness/Helplessness",# 3 "Confusion/Doubt", # 4 "Gratitude/Relief" # 5]
# Emotion colorsEMOTION_COLORS = { "Neutral": "#95a5a6", "Anxiety/Fear": "#e74c3c", "Anger/Frustration": "#c0392b", "Sadness/Helplessness": "#3498db", "Confusion/Doubt": "#9b59b6", "Gratitude/Relief": "#27ae60"}
# Maximum text lengthMAX_LENGTH = 512123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Emotion Prediction - Patient Analysis</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"> <style> body { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; padding: 20px 0; } .main-container { max-width: 800px; margin: 0 auto; } .card { border: none; border-radius: 20px; box-shadow: 0 20px 60px rgba(0,0,0,0.3); overflow: hidden; } .card-header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 25px; text-align: center; border: none; } .card-header h2 { margin: 0; font-weight: 300; letter-spacing: 2px; } .card-body { padding: 30px; } .form-control { border-radius: 12px; border: 2px solid #e0e0e0; padding: 15px; font-size: 16px; min-height: 120px; resize: vertical; transition: all 0.3s ease; } .form-control:focus { border-color: #667eea; box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25); } .btn-predict { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border: none; border-radius: 12px; padding: 15px 50px; font-size: 18px; font-weight: 500; letter-spacing: 1px; transition: all 0.3s ease; } .btn-predict:hover { transform: translateY(-2px); box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4); } .btn-predict:disabled { opacity: 0.6; transform: none; } .btn-random { background: #6c757d; border: none; border-radius: 12px; padding: 12px 25px; font-size: 14px; transition: all 0.3s ease; } .btn-random:hover { background: #5a6268; transform: translateY(-2px); } .btn-random:disabled { opacity: 0.6; } .result-card { border-radius: 15px; margin-top: 25px; display: none; } .emotion-badge { display: inline-block; padding: 12px 30px; border-radius: 50px; font-size: 20px; font-weight: 600; color: white; margin: 10px 0; transition: all 0.3s ease; } .confidence-ring { width: 120px; height: 120px; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 20px auto; position: relative; } .confidence-ring::before { content: ''; position: absolute; width: 100%; height: 100%; border-radius: 50%; background: conic-gradient(currentColor calc(var(--percent) * 1%), #e0e0e0 0); } .confidence-ring-inner { width: 90px; height: 90px; border-radius: 50%; background: white; display: flex; flex-direction: column; align-items: center; justify-content: center; position: relative; z-index: 1; } .confidence-value { font-size: 24px; font-weight: 700; color: #333; } .confidence-label { font-size: 11px; color: #888; } .probability-item { display: flex; align-items: center; margin: 8px 0; padding: 10px 15px; background: #f8f9fa; border-radius: 10px; } .probability-label { width: 180px; font-weight: 500; color: #555; } .probability-bar-container { flex: 1; height: 20px; background: #e9ecef; border-radius: 10px; overflow: hidden; margin: 0 15px; } .probability-bar { height: 100%; border-radius: 10px; transition: width 0.5s ease; } .probability-value { width: 60px; text-align: right; font-weight: 600; color: #333; } .status-indicator { display: inline-block; width: 10px; height: 10px; border-radius: 50%; margin-right: 8px; } .status-loading { background: #ffc107; animation: pulse 1s infinite; } .status-ready { background: #28a745; } @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } } .example-section { margin-top: 20px; padding: 15px; background: #f8f9fa; border-radius: 12px; } .example-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; } .example-tag { display: inline-block; background: white; padding: 6px 14px; border-radius: 20px; margin: 3px; font-size: 13px; cursor: pointer; transition: all 0.2s ease; border: 1px solid #dee2e6; } .example-tag:hover { background: #667eea; color: white; border-color: #667eea; } .model-status { font-size: 13px; color: #888; margin-bottom: 15px; } .input-group-btn { display: flex; gap: 10px; margin-top: 10px; } .scenario-label { font-size: 12px; color: #888; font-style: italic; } </style></head><body> <div class="main-container"> <div class="card"> <div class="card-header"> <h2>Emotion Prediction</h2> <p style="margin: 10px 0 0 0; opacity: 0.8; font-size: 14px;">Patient-Doctor Conversation Analysis</p> </div> <div class="card-body"> <div class="model-status"> <span class="status-indicator status-loading" id="statusIndicator"></span> <span id="statusText">Loading model...</span> </div> <div class="mb-3"> <label class="form-label" style="font-weight: 500; color: #333;">Patient Statement</label> <textarea class="form-control" id="textInput" placeholder="Enter patient statement from doctor-patient conversation..."></textarea> <div class="input-group-btn"> <button class="btn btn-random" id="randomBtn" onclick="getRandomExample()"> Random Example </button> <button class="btn btn-random" id="showAllBtn" onclick="toggleExamples()"> Show All Examples </button> </div> </div> <div class="example-section" id="exampleSection" style="display: none;"> <div class="example-header"> <span class="scenario-label">Click to use:</span> </div> <div id="examplesContainer"></div> </div> <div class="text-center mt-4"> <button class="btn btn-primary btn-predict" id="predictBtn" onclick="predictEmotion()"> Predict Emotion </button> </div> <div class="card result-card" id="resultCard"> <div class="card-body text-center"> <h5 style="color: #888; margin-bottom: 15px;">Prediction Result</h5> <div class="emotion-badge" id="emotionBadge"></div> <div class="confidence-ring" id="confidenceRing"> <div class="confidence-ring-inner"> <span class="confidence-value" id="confidenceValue">0%</span> <span class="confidence-label">Confidence</span> </div> </div> <h6 style="color: #888; margin: 25px 0 15px 0;">Probability Distribution</h6> <div id="probabilityList"></div> </div> </div> </div> </div> </div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script> <script> const emotionColors = { "Neutral": "#95a5a6", "Anxiety/Fear": "#e74c3c", "Anger/Frustration": "#c0392b", "Sadness/Helplessness": "#3498db", "Confusion/Doubt": "#9b59b6", "Gratitude/Relief": "#27ae60" }; const emotionTags = { "Neutral": "Neutral", "Anxiety/Fear": "Anxiety/Fear", "Anger/Frustration": "Anger", "Sadness/Helplessness": "Sadness", "Confusion/Doubt": "Confusion", "Gratitude/Relief": "Gratitude/Relief" }; let allExamples = {}; let examplesVisible = false; async function init() { try { const response = await fetch('/api/model/load', { method: 'POST' }); const data = await response.json(); if (data.success) { document.getElementById('statusIndicator').className = 'status-indicator status-ready'; document.getElementById('statusText').textContent = `Model loaded | Device: ${data.device}`; } else { document.getElementById('statusText').textContent = 'Model load failed: ' + data.error; } } catch (error) { document.getElementById('statusText').textContent = 'Connection failed'; } // Load all examples try { const resp = await fetch('/api/examples/all'); const data = await resp.json(); if (data.success) { allExamples = data.examples; } } catch (e) { console.log('Failed to load examples'); } } function setExampleText(text) { document.getElementById('textInput').value = text; } async function getRandomExample() { const btn = document.getElementById('randomBtn'); btn.disabled = true; btn.textContent = 'Loading...'; try { const response = await fetch('/api/examples/random'); const data = await response.json(); if (data.success) { setExampleText(data.text); } } catch (error) { alert('Failed to load random example'); } finally { btn.disabled = false; btn.textContent = 'Random Example'; } } function toggleExamples() { const section = document.getElementById('exampleSection'); const btn = document.getElementById('showAllBtn'); examplesVisible = !examplesVisible; if (examplesVisible) { section.style.display = 'block'; btn.textContent = 'Hide Examples'; renderExamples(); } else { section.style.display = 'none'; btn.textContent = 'Show All Examples'; } } function renderExamples() { const container = document.getElementById('examplesContainer'); container.innerHTML = ''; for (const [emotion, texts] of Object.entries(allExamples)) { const tag = document.createElement('div'); tag.className = 'scenario-label'; tag.style.marginTop = '10px'; tag.style.color = emotionColors[emotion]; tag.textContent = emotionTags[emotion] || emotion; container.appendChild(tag); texts.forEach(text => { const btn = document.createElement('button'); btn.className = 'example-tag'; btn.textContent = text.length > 50 ? text.substring(0, 50) + '...' : text; btn.onclick = () => setExampleText(text); container.appendChild(btn); }); } } async function predictEmotion() { const text = document.getElementById('textInput').value.trim(); if (!text) { alert('Please enter patient statement'); return; } const btn = document.getElementById('predictBtn'); btn.disabled = true; btn.textContent = 'Analyzing...'; try { const response = await fetch('/api/model/predict', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: text }) }); const data = await response.json(); if (data.success) { displayResult(data.result); } else { alert('Prediction failed: ' + data.error); } } catch (error) { alert('Request failed: ' + error); } finally { btn.disabled = false; btn.textContent = 'Predict Emotion'; } } function displayResult(result) { const card = document.getElementById('resultCard'); card.style.display = 'block'; const badge = document.getElementById('emotionBadge'); badge.textContent = result.predicted_label; badge.style.backgroundColor = emotionColors[result.predicted_label] || '#667eea'; const confidence = Math.round(result.confidence * 100); const ring = document.getElementById('confidenceRing'); ring.style.setProperty('--percent', confidence); ring.style.color = emotionColors[result.predicted_label] || '#667eea'; document.getElementById('confidenceValue').textContent = confidence + '%'; const list = document.getElementById('probabilityList'); list.innerHTML = ''; result.all_probabilities.forEach(item => { const percent = Math.round(item.probability * 100); const div = document.createElement('div'); div.className = 'probability-item'; div.innerHTML = ` <span class="probability-label">${item.label}</span> <div class="probability-bar-container"> <div class="probability-bar" style="width: ${percent}%; background-color: ${emotionColors[item.label] || '#667eea'}"></div> </div> <span class="probability-value">${percent}%</span> `; list.appendChild(div); }); } init(); </script></body></html>.gitattributes+1
README.mdAdded+89
best_model/config.jsonAdded+44
best_model/metrics.jsonAdded+18
best_model/model.safetensorsAdded+3
best_model/tokenizer.jsonAdded
best_model/tokenizer_config.jsonAdded+14
best_model/training_args.binAdded+3
data/all_data_merged.parquetAdded+3
data/label_distribution.pngAdded

Large File Pointer Details
- SHA256: 15acec12f909d7f6185caea49e0fba73b980bbbe3a049ae6c139155bcf79e4f0
- Pointer size: 131 Bytes
- Size of remote file: 173 kB
requirements.txtAdded+7
see/app.pyAdded+139
see/inference.pyAdded+134
see/see_config.pyAdded+34
see/templates/index.htmlAdded+471