KatenKyokotsu commited on
Commit
df65728
·
1 Parent(s): 6225a79

Update CCTA with modifiers

Browse files
Saved Models/dmis-lab_biobert-v1.1_modifier_20250406_160702/config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "BertForSequenceClassification"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.1,
6
+ "classifier_dropout": null,
7
+ "gradient_checkpointing": false,
8
+ "hidden_act": "gelu",
9
+ "hidden_dropout_prob": 0.1,
10
+ "hidden_size": 768,
11
+ "id2label": {
12
+ "0": "LABEL_0",
13
+ "1": "LABEL_1",
14
+ "2": "LABEL_2",
15
+ "3": "LABEL_3"
16
+ },
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 3072,
19
+ "label2id": {
20
+ "LABEL_0": 0,
21
+ "LABEL_1": 1,
22
+ "LABEL_2": 2,
23
+ "LABEL_3": 3
24
+ },
25
+ "layer_norm_eps": 1e-12,
26
+ "max_position_embeddings": 512,
27
+ "model_type": "bert",
28
+ "num_attention_heads": 12,
29
+ "num_hidden_layers": 12,
30
+ "pad_token_id": 0,
31
+ "position_embedding_type": "absolute",
32
+ "torch_dtype": "float32",
33
+ "transformers_version": "4.50.2",
34
+ "type_vocab_size": 2,
35
+ "use_cache": true,
36
+ "vocab_size": 28996
37
+ }
Saved Models/dmis-lab_biobert-v1.1_modifier_20250406_160702/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ea5d053305dc31cf10ce0f8c1ab58c67219cf2004758f065b6523e3fed44afb0
3
+ size 433276920
Saved Models/dmis-lab_biobert-v1.1_modifier_20250406_160702/special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "mask_token": "[MASK]",
4
+ "pad_token": "[PAD]",
5
+ "sep_token": "[SEP]",
6
+ "unk_token": "[UNK]"
7
+ }
Saved Models/dmis-lab_biobert-v1.1_modifier_20250406_160702/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
Saved Models/dmis-lab_biobert-v1.1_modifier_20250406_160702/tokenizer_config.json ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "100": {
12
+ "content": "[UNK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "101": {
20
+ "content": "[CLS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "102": {
28
+ "content": "[SEP]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "103": {
36
+ "content": "[MASK]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": true,
45
+ "cls_token": "[CLS]",
46
+ "do_basic_tokenize": true,
47
+ "do_lower_case": false,
48
+ "extra_special_tokens": {},
49
+ "mask_token": "[MASK]",
50
+ "model_max_length": 512,
51
+ "never_split": null,
52
+ "pad_token": "[PAD]",
53
+ "sep_token": "[SEP]",
54
+ "strip_accents": null,
55
+ "tokenize_chinese_chars": true,
56
+ "tokenizer_class": "BertTokenizer",
57
+ "unk_token": "[UNK]"
58
+ }
Saved Models/dmis-lab_biobert-v1.1_modifier_20250406_160702/training_info.json ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_name": "dmis-lab/biobert-v1.1",
3
+ "task": "modifier_classification_p1_p4",
4
+ "best_val_loss": 0.5308117792010307,
5
+ "class_weights": [
6
+ 0.43924689292907715,
7
+ 0.8257841467857361,
8
+ 1.1469224691390991,
9
+ 1.5880464315414429
10
+ ],
11
+ "epochs_trained": 9,
12
+ "modifier_mapping": {
13
+ "P1": 0,
14
+ "P2": 1,
15
+ "P3": 2,
16
+ "P4": 3
17
+ },
18
+ "reverse_modifier_mapping": {
19
+ "0": "P1",
20
+ "1": "P2",
21
+ "2": "P3",
22
+ "3": "P4"
23
+ },
24
+ "history": {
25
+ "train_loss": [
26
+ 1.4040802350411048,
27
+ 1.245903138930981,
28
+ 0.9595575538965372,
29
+ 0.6990365913281074,
30
+ 0.5699076125254998,
31
+ 0.30417203502013135,
32
+ 0.1468625211944947,
33
+ 0.0641340408116006,
34
+ 0.050150050584656686
35
+ ],
36
+ "val_loss": [
37
+ 1.378000835577647,
38
+ 1.062585473060608,
39
+ 0.7735106150309244,
40
+ 0.8551392455895742,
41
+ 0.6323925157388052,
42
+ 0.5308117792010307,
43
+ 0.6643671492735544,
44
+ 0.794399178121239,
45
+ 0.8435169272124767
46
+ ],
47
+ "val_metrics": [
48
+ {
49
+ "precision": 0.20891608391608393,
50
+ "recall": 0.25,
51
+ "f1": 0.20859950859950863
52
+ },
53
+ {
54
+ "precision": 0.5928768201495473,
55
+ "recall": 0.5454545454545454,
56
+ "f1": 0.49256718124642646
57
+ },
58
+ {
59
+ "precision": 0.6446280991735537,
60
+ "recall": 0.6590909090909091,
61
+ "f1": 0.6333207854946985
62
+ },
63
+ {
64
+ "precision": 0.7542748917748917,
65
+ "recall": 0.6136363636363636,
66
+ "f1": 0.6052548732102812
67
+ },
68
+ {
69
+ "precision": 0.8537687802393684,
70
+ "recall": 0.7954545454545454,
71
+ "f1": 0.7837417571342183
72
+ },
73
+ {
74
+ "precision": 0.8206959706959706,
75
+ "recall": 0.8181818181818182,
76
+ "f1": 0.8140201908217428
77
+ },
78
+ {
79
+ "precision": 0.8387445887445888,
80
+ "recall": 0.8181818181818182,
81
+ "f1": 0.8205594405594406
82
+ },
83
+ {
84
+ "precision": 0.8835227272727273,
85
+ "recall": 0.8409090909090909,
86
+ "f1": 0.8417967554331192
87
+ },
88
+ {
89
+ "precision": 0.8387445887445888,
90
+ "recall": 0.8181818181818182,
91
+ "f1": 0.8205594405594406
92
+ }
93
+ ]
94
+ }
95
+ }
Saved Models/dmis-lab_biobert-v1.1_modifier_20250406_160702/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
app.log ADDED
The diff for this file is too large to render. See raw diff
 
app.py CHANGED
@@ -23,6 +23,8 @@ import time
23
  from huggingface_hub import login
24
  import logging
25
  from functools import wraps
 
 
26
 
27
  # Configure logging
28
  logging.basicConfig(
@@ -47,6 +49,7 @@ client = OpenAI(
47
 
48
  # Model configuration
49
  MODEL_NAME = 'dmis-lab_biobert-v1.1_20250316_195322'
 
50
  OUTPUT_DIR = os.environ.get('CCTA_OUTPUT_DIR', 'Saved Models')
51
 
52
  # Set device
@@ -67,8 +70,16 @@ label_mapping = {
67
  }
68
  reverse_label_mapping = {v: k for k, v in label_mapping.items()}
69
 
 
 
 
 
 
 
 
 
70
  # Load model
71
- def load_model(model_name):
72
  try:
73
  # Direct path to model
74
  model_path = os.path.join(OUTPUT_DIR, model_name.replace("/", "_"))
@@ -78,9 +89,32 @@ def load_model(model_name):
78
 
79
  logger.info(f"Loading model from {model_path}")
80
  tokenizer = AutoTokenizer.from_pretrained(model_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  model = AutoModelForSequenceClassification.from_pretrained(
82
  model_path,
83
- num_labels=len(label_mapping)
84
  )
85
  model.to(device)
86
  model.eval()
@@ -89,12 +123,17 @@ def load_model(model_name):
89
  logger.error(f"Error loading model: {str(e)}")
90
  raise
91
 
92
- # Load model and tokenizer
93
  try:
94
- model, tokenizer = load_model(MODEL_NAME)
95
- logger.info("Model and tokenizer loaded successfully")
 
 
 
 
 
96
  except Exception as e:
97
- logger.error(f"Failed to load model: {str(e)}")
98
  raise
99
 
100
  # Create uploads directory if it doesn't exist
@@ -222,23 +261,51 @@ def predict_cadrads_score(report_json):
222
  combined_text = create_text_representation(report_json)
223
 
224
  with torch.no_grad():
225
- encoding = tokenizer(combined_text, truncation=True, padding='max_length', max_length=256, return_tensors='pt')
226
- input_ids = encoding['input_ids'].to(device)
227
- attention_mask = encoding['attention_mask'].to(device)
228
- outputs = model(input_ids, attention_mask=attention_mask)
229
- _, predicted = torch.max(outputs.logits, dim=1)
 
 
 
 
 
230
 
231
- pred_class = predicted.item()
232
- if pred_class in label_mapping:
233
- cadrads_score = label_mapping[pred_class]
234
  else:
235
- logger.warning(f"Predicted class {pred_class} not in label mapping")
236
  cadrads_score = "Unknown"
237
 
238
- return cadrads_score
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
  except Exception as e:
240
  logger.error(f"Error in prediction: {str(e)}")
241
- return "Error"
242
 
243
  # Load prompt template
244
  try:
@@ -323,19 +390,21 @@ def predict():
323
  return redirect(url_for('home'))
324
 
325
  # Predict CADRADS score
326
- cadrads_score = predict_cadrads_score(report_json)
327
 
328
  # Log prediction
329
- logger.info(f"Prediction for {file.filename}: CADRADS {cadrads_score}")
330
 
331
  # Add to history
332
  report_id = len(history) + 1
333
  history.append({
334
  'report_id': report_id,
335
  'prediction': cadrads_score,
 
336
  'text': report_text,
337
  'timestamp': time.strftime('%Y-%m-%d %H:%M:%S'),
338
- 'filename': file.filename
 
339
  })
340
 
341
  flash('Report processed successfully!', 'success')
@@ -359,8 +428,88 @@ def predict():
359
  @login_required
360
  def view_report(report_id):
361
  report = next((item for item in history if item["report_id"] == report_id), None)
 
 
 
 
 
 
 
 
362
  return render_template('view_report.html', report=report)
363
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
364
  @app.errorhandler(413)
365
  def too_large(e):
366
  flash('File is too large. Maximum size is 16MB.', 'error')
 
23
  from huggingface_hub import login
24
  import logging
25
  from functools import wraps
26
+ import requests
27
+ from safetensors.torch import save_file
28
 
29
  # Configure logging
30
  logging.basicConfig(
 
49
 
50
  # Model configuration
51
  MODEL_NAME = 'dmis-lab_biobert-v1.1_20250316_195322'
52
+ MODIFIER_MODEL_NAME = 'dmis-lab_biobert-v1.1_modifier_20250406_160702'
53
  OUTPUT_DIR = os.environ.get('CCTA_OUTPUT_DIR', 'Saved Models')
54
 
55
  # Set device
 
70
  }
71
  reverse_label_mapping = {v: k for k, v in label_mapping.items()}
72
 
73
+ # Modifier mapping
74
+ modifier_mapping = {
75
+ 0: "P1", # Mild plaque burden (CAC 0-99)
76
+ 1: "P2", # Moderate plaque burden (CAC 100-399)
77
+ 2: "P3", # Severe plaque burden (CAC 400-999)
78
+ 3: "P4" # Extensive plaque burden (CAC ≥1000)
79
+ }
80
+
81
  # Load model
82
+ def load_model(model_name, num_labels):
83
  try:
84
  # Direct path to model
85
  model_path = os.path.join(OUTPUT_DIR, model_name.replace("/", "_"))
 
89
 
90
  logger.info(f"Loading model from {model_path}")
91
  tokenizer = AutoTokenizer.from_pretrained(model_path)
92
+
93
+ # Check if safetensors version exists
94
+ safetensors_path = os.path.join(model_path, "model.safetensors")
95
+ pytorch_path = os.path.join(model_path, "pytorch_model.bin")
96
+
97
+ # If PyTorch model exists but safetensors doesn't, convert it
98
+ if os.path.exists(pytorch_path) and not os.path.exists(safetensors_path):
99
+ logger.info(f"Converting PyTorch model to safetensors format")
100
+
101
+ # Load the PyTorch model
102
+ temp_model = AutoModelForSequenceClassification.from_pretrained(
103
+ model_path,
104
+ num_labels=num_labels
105
+ )
106
+
107
+ # Extract state dict
108
+ state_dict = temp_model.state_dict()
109
+
110
+ # Save as safetensors
111
+ save_file(state_dict, safetensors_path)
112
+ logger.info(f"Model converted and saved to {safetensors_path}")
113
+
114
+ # Load the model (will use safetensors if available)
115
  model = AutoModelForSequenceClassification.from_pretrained(
116
  model_path,
117
+ num_labels=num_labels
118
  )
119
  model.to(device)
120
  model.eval()
 
123
  logger.error(f"Error loading model: {str(e)}")
124
  raise
125
 
126
+ # Load models and tokenizers
127
  try:
128
+ # Load classifier model for CADRADS score
129
+ classifier_model, classifier_tokenizer = load_model(MODEL_NAME, len(label_mapping))
130
+ logger.info("Classifier model and tokenizer loaded successfully")
131
+
132
+ # Load modifier model
133
+ modifier_model, modifier_tokenizer = load_model(MODIFIER_MODEL_NAME, len(modifier_mapping))
134
+ logger.info("Modifier model and tokenizer loaded successfully")
135
  except Exception as e:
136
+ logger.error(f"Failed to load models: {str(e)}")
137
  raise
138
 
139
  # Create uploads directory if it doesn't exist
 
261
  combined_text = create_text_representation(report_json)
262
 
263
  with torch.no_grad():
264
+ # Predict CADRADS score with classifier model
265
+ classifier_encoding = classifier_tokenizer(combined_text, truncation=True, padding='max_length', max_length=512, return_tensors='pt')
266
+ classifier_input_ids = classifier_encoding['input_ids'].to(device)
267
+ classifier_attention_mask = classifier_encoding['attention_mask'].to(device)
268
+ classifier_outputs = classifier_model(classifier_input_ids, attention_mask=classifier_attention_mask)
269
+
270
+ # Get CADRADS score (highest probability class)
271
+ classifier_probabilities = torch.nn.functional.softmax(classifier_outputs.logits, dim=1)
272
+ _, predicted_cadrads = torch.max(classifier_probabilities, dim=1)
273
+ cadrads_class = predicted_cadrads.item()
274
 
275
+ # Convert to label
276
+ if cadrads_class in label_mapping:
277
+ cadrads_score = label_mapping[cadrads_class]
278
  else:
279
+ logger.warning(f"Predicted CADRADS class {cadrads_class} not in label mapping")
280
  cadrads_score = "Unknown"
281
 
282
+ # If CADRADS score is 0 or N, don't use modifier
283
+ if cadrads_score == "0" or cadrads_score == "N":
284
+ logger.info(f"CADRADS score is {cadrads_score}, not displaying modifier")
285
+ return cadrads_score, "None"
286
+
287
+ # Only predict modifier if CADRADS score is not 0 or N
288
+ modifier_encoding = modifier_tokenizer(combined_text, truncation=True, padding='max_length', max_length=512, return_tensors='pt')
289
+ modifier_input_ids = modifier_encoding['input_ids'].to(device)
290
+ modifier_attention_mask = modifier_encoding['attention_mask'].to(device)
291
+ modifier_outputs = modifier_model(modifier_input_ids, attention_mask=modifier_attention_mask)
292
+
293
+ # Get modifier (highest probability class)
294
+ modifier_probabilities = torch.nn.functional.softmax(modifier_outputs.logits, dim=1)
295
+ _, predicted_modifier = torch.max(modifier_probabilities, dim=1)
296
+ modifier_class = predicted_modifier.item()
297
+
298
+ # Convert to label
299
+ if modifier_class in modifier_mapping:
300
+ modifier = modifier_mapping[modifier_class]
301
+ else:
302
+ logger.warning(f"Predicted modifier class {modifier_class} not in modifier mapping")
303
+ modifier = "None"
304
+
305
+ return cadrads_score, modifier
306
  except Exception as e:
307
  logger.error(f"Error in prediction: {str(e)}")
308
+ return "Error", "None"
309
 
310
  # Load prompt template
311
  try:
 
390
  return redirect(url_for('home'))
391
 
392
  # Predict CADRADS score
393
+ cadrads_score, modifier = predict_cadrads_score(report_json)
394
 
395
  # Log prediction
396
+ logger.info(f"Prediction for {file.filename}: CADRADS {cadrads_score}, Modifier {modifier}")
397
 
398
  # Add to history
399
  report_id = len(history) + 1
400
  history.append({
401
  'report_id': report_id,
402
  'prediction': cadrads_score,
403
+ 'modifier': modifier,
404
  'text': report_text,
405
  'timestamp': time.strftime('%Y-%m-%d %H:%M:%S'),
406
+ 'filename': file.filename,
407
+ 'json_output': report_json # Store the JSON output in the report history
408
  })
409
 
410
  flash('Report processed successfully!', 'success')
 
428
  @login_required
429
  def view_report(report_id):
430
  report = next((item for item in history if item["report_id"] == report_id), None)
431
+ if report:
432
+ if 'mesa_results' not in report:
433
+ report['mesa_results'] = None
434
+
435
+ # Make the JSON data available to the template for extracting calcium score
436
+ if 'json_output' in report:
437
+ report['json_data'] = report['json_output']
438
+
439
  return render_template('view_report.html', report=report)
440
 
441
+ @app.route('/calculate_mesa_score', methods=['POST'])
442
+ @login_required
443
+ def calculate_mesa_score():
444
+ try:
445
+ # Get form data from request
446
+ data = request.json
447
+ if not data:
448
+ return jsonify({"error": "No data provided"}), 400
449
+
450
+ # Validate required fields
451
+ required_fields = ['gender', 'age', 'ethnicity', 'diabetes', 'smoke',
452
+ 'fhhx', 'chol', 'hdl', 'sbp', 'lipid', 'htnmed']
453
+ for field in required_fields:
454
+ if field not in data:
455
+ return jsonify({"error": f"Missing required field: {field}"}), 400
456
+
457
+ # Prepare API request
458
+ api_endpoint = "https://www.mesa-nhlbi.org/MESACHDRiskCoronaryAge/api/score"
459
+
460
+ # Add CAC score if provided
461
+ cac_param = ""
462
+ if 'cac' in data and data['cac']:
463
+ cac_param = f"/{data['cac']}"
464
+ else:
465
+ cac_param = "/-9" # Default value for CAC if not provided
466
+
467
+ # Construct full URL with parameters
468
+ url = f"{api_endpoint}/{data['gender']}/{data['age']}/{data['ethnicity']}/{data['diabetes']}/{data['smoke']}/{data['fhhx']}/{data['chol']}/{data['hdl']}/{data['sbp']}/{data['lipid']}/{data['htnmed']}{cac_param}"
469
+
470
+ # Call MESA API
471
+ logger.info(f"Calling MESA API: {url}")
472
+ response = requests.get(url)
473
+
474
+ if response.status_code != 200:
475
+ logger.error(f"MESA API error: {response.status_code} - {response.text}")
476
+ return jsonify({"error": f"MESA API returned error: {response.status_code}"}), 500
477
+
478
+ # Process and return the results
479
+ result = response.json()
480
+ logger.info(f"MESA API result: {result}")
481
+
482
+ # Extract and format relevant data
483
+ formatted_result = {
484
+ 'cac_riskscore': result.get('cac_riskscore', '-'),
485
+ 'cac_coronary_age': result.get('cac_coronary_age', '-'),
486
+ 'cac_age_diff': result.get('cac_age_diff', '-'),
487
+ 'nocac_riskscore': result.get('nocac_riskscore', '-'),
488
+ 'nocac_coronary_age': result.get('nocac_coronary_age', '-'),
489
+ 'nocac_age_diff': result.get('nocac_age_diff', '-')
490
+ }
491
+
492
+ # Store the form values along with the MESA results in the report data
493
+ report_id = request.json.get('report_id')
494
+ if report_id:
495
+ for item in history:
496
+ if item['report_id'] == int(report_id):
497
+ # Save both the results and the form input values
498
+ item['mesa_results'] = formatted_result
499
+
500
+ # Create a copy of the form data without the report_id
501
+ form_data = {k: v for k, v in data.items() if k != 'report_id'}
502
+ item['mesa_form_data'] = form_data
503
+
504
+ logger.info(f"MESA results and form data stored for report {report_id}")
505
+ break
506
+
507
+ return jsonify(formatted_result)
508
+
509
+ except Exception as e:
510
+ logger.error(f"Error calculating MESA score: {str(e)}")
511
+ return jsonify({"error": str(e)}), 500
512
+
513
  @app.errorhandler(413)
514
  def too_large(e):
515
  flash('File is too large. Maximum size is 16MB.', 'error')
requirements.txt CHANGED
@@ -11,3 +11,5 @@ scikit-learn==1.4.0
11
  tqdm==4.66.1
12
  huggingface-hub>=0.23.2,<1.0
13
  pyarrow==15.0.0
 
 
 
11
  tqdm==4.66.1
12
  huggingface-hub>=0.23.2,<1.0
13
  pyarrow==15.0.0
14
+ requests==2.31.0
15
+ safetensors==0.4.3
static/styles.css CHANGED
@@ -213,13 +213,34 @@ body {
213
  }
214
 
215
  .history-score {
 
 
 
 
 
 
216
  font-weight: 700;
217
  padding: 5px 12px;
218
  border-radius: 20px;
219
  font-size: 0.9rem;
220
- background-color: var(--primary-light);
221
  color: white;
222
- margin-right: 15px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  }
224
 
225
  /* Report view styles */
@@ -295,4 +316,8 @@ body {
295
  display: flex;
296
  justify-content: flex-end;
297
  }
 
 
 
 
298
  }
 
213
  }
214
 
215
  .history-score {
216
+ display: flex;
217
+ align-items: center;
218
+ margin-right: 15px;
219
+ }
220
+
221
+ .cadrads-label {
222
  font-weight: 700;
223
  padding: 5px 12px;
224
  border-radius: 20px;
225
  font-size: 0.9rem;
 
226
  color: white;
227
+ display: inline-block;
228
+ }
229
+
230
+ /* Add styling for modifier badge */
231
+ .modifier-badge {
232
+ display: inline-block;
233
+ font-size: 0.9rem;
234
+ color: white;
235
+ padding: 5px 12px;
236
+ border-radius: 20px;
237
+ font-weight: 700;
238
+ margin-left: 6px;
239
+ }
240
+
241
+ /* Add simple styling for P1-P4 modifier badges */
242
+ span.modifier-badge:not([style*="background"]) {
243
+ background-color: var(--primary-color);
244
  }
245
 
246
  /* Report view styles */
 
316
  display: flex;
317
  justify-content: flex-end;
318
  }
319
+
320
+ .history-score {
321
+ margin-bottom: 10px;
322
+ }
323
  }
templates/index.html CHANGED
@@ -66,8 +66,8 @@
66
 
67
  <!-- Dashboard Header -->
68
  <div class="dashboard-header">
69
- <h1 class="dashboard-title">CAD-RADS Score Prediction</h1>
70
- <p class="dashboard-subtitle">Upload a clinical report document to get an AI-powered CAD-RADS score prediction</p>
71
  </div>
72
 
73
  <!-- Dashboard Content -->
@@ -168,7 +168,12 @@
168
  </div>
169
  <div class="d-flex align-items-center">
170
  <div class="history-score">
171
- CAD-RADS {{ report.prediction }}
 
 
 
 
 
172
  </div>
173
  <a href="{{ url_for('view_report', report_id=report.report_id) }}"
174
  class="btn btn-sm btn-outline-primary">
@@ -190,7 +195,7 @@
190
  <!-- CAD-RADS Reference Card -->
191
  <div class="card mt-4">
192
  <div class="card-header">
193
- <i class="fas fa-heart mr-2"></i> CAD-RADS Reference
194
  </div>
195
  <div class="card-body">
196
  <div class="table-responsive">
@@ -238,6 +243,48 @@
238
  </div>
239
  </div>
240
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241
  </div>
242
  </div>
243
  </div>
@@ -254,6 +301,40 @@
254
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
255
  <script>
256
  $(document).ready(function() {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
  // File upload handling
258
  const uploadZone = document.getElementById('uploadZone');
259
  const fileInput = document.getElementById('fileUpload');
 
66
 
67
  <!-- Dashboard Header -->
68
  <div class="dashboard-header">
69
+ <h1 class="dashboard-title">CAD-RADS Score and Modifier Prediction</h1>
70
+ <p class="dashboard-subtitle">Upload a clinical report document to get an AI-powered CAD-RADS score and modifier prediction</p>
71
  </div>
72
 
73
  <!-- Dashboard Content -->
 
168
  </div>
169
  <div class="d-flex align-items-center">
170
  <div class="history-score">
171
+ {% if report.modifier and report.modifier != "None" %}
172
+ <span class="cadrads-label">CAD-RADS {{ report.prediction }}</span>
173
+ <span class="modifier-badge">{{ report.modifier }}</span>
174
+ {% else %}
175
+ <span class="cadrads-label">CAD-RADS {{ report.prediction }}</span>
176
+ {% endif %}
177
  </div>
178
  <a href="{{ url_for('view_report', report_id=report.report_id) }}"
179
  class="btn btn-sm btn-outline-primary">
 
195
  <!-- CAD-RADS Reference Card -->
196
  <div class="card mt-4">
197
  <div class="card-header">
198
+ <i class="fas fa-heart mr-2"></i> CAD-RADS Reference with Modifiers
199
  </div>
200
  <div class="card-body">
201
  <div class="table-responsive">
 
243
  </div>
244
  </div>
245
  </div>
246
+
247
+ <!-- Coronary Plaque Classification Card -->
248
+ <div class="card mt-4">
249
+ <div class="card-header">
250
+ <i class="fas fa-layer-group mr-2"></i> Coronary Plaque Burden Classification
251
+ </div>
252
+ <div class="card-body">
253
+ <div class="table-responsive">
254
+ <table class="table table-bordered">
255
+ <thead class="bg-light">
256
+ <tr>
257
+ <th class="text-center">Modifier</th>
258
+ <th class="text-center">Overall amount of plaque</th>
259
+ <th class="text-center">CAC</th>
260
+ </tr>
261
+ </thead>
262
+ <tbody>
263
+ <tr>
264
+ <td width="15%" class="font-weight-bold text-center"><span class="badge badge-success">P1</span></td>
265
+ <td>Mild plaque burden</td>
266
+ <td>0-99</td>
267
+ </tr>
268
+ <tr class="bg-light">
269
+ <td class="font-weight-bold text-center"><span class="badge badge-info">P2</span></td>
270
+ <td>Moderate plaque burden</td>
271
+ <td>100-399</td>
272
+ </tr>
273
+ <tr>
274
+ <td class="font-weight-bold text-center"><span class="badge badge-warning">P3</span></td>
275
+ <td>Severe plaque burden</td>
276
+ <td>400-999</td>
277
+ </tr>
278
+ <tr class="bg-light">
279
+ <td class="font-weight-bold text-center"><span class="badge badge-danger">P4</span></td>
280
+ <td>Extensive plaque burden</td>
281
+ <td>≥1000</td>
282
+ </tr>
283
+ </tbody>
284
+ </table>
285
+ </div>
286
+ </div>
287
+ </div>
288
  </div>
289
  </div>
290
  </div>
 
301
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
302
  <script>
303
  $(document).ready(function() {
304
+ // Style the modifier badges based on their content
305
+ $('.modifier-badge').each(function() {
306
+ var badgeText = $(this).text().trim();
307
+ if (badgeText === 'P1') {
308
+ $(this).css('background-color', '#43a047'); // Success/green
309
+ } else if (badgeText === 'P2') {
310
+ $(this).css('background-color', '#039be5'); // Info/blue
311
+ } else if (badgeText === 'P3') {
312
+ $(this).css('background-color', '#ff9800'); // Warning/orange
313
+ } else if (badgeText === 'P4') {
314
+ $(this).css('background-color', '#e53935'); // Danger/red
315
+ }
316
+ });
317
+
318
+ // Add badge colors to CAD-RADS scores
319
+ $('.cadrads-label').each(function() {
320
+ var scoreText = $(this).text();
321
+ var score = scoreText.match(/\d+/);
322
+
323
+ if (score && score[0]) {
324
+ if (score[0] === '0') {
325
+ $(this).css('background-color', '#43a047'); // Success/green
326
+ } else if (score[0] === '1' || score[0] === '2') {
327
+ $(this).css('background-color', '#039be5'); // Info/blue
328
+ } else if (score[0] === '3') {
329
+ $(this).css('background-color', '#ff9800'); // Warning/orange
330
+ } else if (score[0] === '4' || score[0] === '5') {
331
+ $(this).css('background-color', '#e53935'); // Danger/red
332
+ }
333
+ } else if (scoreText.includes('N')) {
334
+ $(this).css('background-color', '#9e9e9e'); // Grey for N
335
+ }
336
+ });
337
+
338
  // File upload handling
339
  const uploadZone = document.getElementById('uploadZone');
340
  const fileInput = document.getElementById('fileUpload');
templates/view_report.html CHANGED
@@ -1,180 +1,986 @@
1
- <!DOCTYPE html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>Report Details - CCTA</title>
7
- <link rel="icon" type="image/x-icon" href="{{ url_for('static', filename='favicon.ico') }}">
8
- <!-- Google Fonts - Inter -->
9
- <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap">
10
- <!-- FontAwesome for icons -->
11
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
12
- <!-- Bootstrap CSS -->
13
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
14
- <!-- Custom CSS -->
15
- <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
16
- </head>
17
- <body>
18
- <!-- Navigation -->
19
- <nav class="navbar navbar-expand-lg navbar-light">
20
- <div class="container">
21
- <a class="navbar-brand d-flex align-items-center" href="{{ url_for('home') }}">
22
- <img src="{{ url_for('static', filename='logo.svg') }}" alt="CCTA Logo" height="40" class="mr-2">
23
- </a>
24
- <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarContent">
25
- <span class="navbar-toggler-icon"></span>
26
- </button>
27
- <div class="collapse navbar-collapse" id="navbarContent">
28
- <ul class="navbar-nav ml-auto">
29
- <li class="nav-item">
30
- <a class="nav-link" href="{{ url_for('home') }}">Dashboard</a>
31
- </li>
32
- <li class="nav-item">
33
- <a class="nav-link" href="{{ url_for('logout') }}">
34
- <i class="fas fa-sign-out-alt mr-1"></i> Logout
35
- </a>
36
- </li>
37
- </ul>
38
- </div>
39
- </div>
40
- </nav>
41
-
42
- <!-- Main Content -->
43
- <div class="container">
44
- <div class="dashboard-header d-flex align-items-center justify-content-between">
45
- <div>
46
- <h1 class="dashboard-title">Report Analysis</h1>
47
- <p class="dashboard-subtitle">
48
- <i class="far fa-file-alt mr-1"></i> {{ report.filename }}
49
- </p>
50
- </div>
51
- <a href="{{ url_for('home') }}" class="btn btn-outline-primary">
52
- <i class="fas fa-arrow-left mr-2"></i> Back to Dashboard
53
- </a>
54
- </div>
55
-
56
- <div class="row">
57
- <!-- Report Content Section -->
58
- <div class="col-lg-6">
59
- <div class="card">
60
- <div class="card-header d-flex justify-content-between align-items-center">
61
- <div><i class="fas fa-file-medical-alt mr-2"></i> Report Content</div>
62
- <span class="badge badge-light">
63
- <i class="far fa-calendar-alt mr-1"></i> {{ report.timestamp }}
64
- </span>
65
- </div>
66
- <div class="card-body">
67
- <div class="report-content">{{ report.text }}</div>
68
- </div>
69
- </div>
70
- </div>
71
-
72
- <!-- Analysis Results Section -->
73
- <div class="col-lg-6">
74
- <div class="card mb-4">
75
- <div class="card-header">
76
- <i class="fas fa-chart-pie mr-2"></i> Analysis Results
77
- </div>
78
- <div class="card-body text-center">
79
- <div class="mb-4">
80
- <div class="display-4 mb-2 font-weight-bold" style="color: #3f51b5;">
81
- CAD-RADS {{ report.prediction }}
82
- </div>
83
- <div class="text-muted small">Coronary Artery Disease Reporting and Data System Score</div>
84
- </div>
85
-
86
- <div class="row mt-4">
87
- <div class="col-12 text-center">
88
- <div class="progress mb-3" style="height: 10px;">
89
- {% if report.prediction == "0" %}
90
- <div class="progress-bar bg-success" role="progressbar" style="width: 16.6%"></div>
91
- {% elif report.prediction == "1" %}
92
- <div class="progress-bar bg-info" role="progressbar" style="width: 33.2%"></div>
93
- {% elif report.prediction == "2" %}
94
- <div class="progress-bar bg-info" role="progressbar" style="width: 49.8%"></div>
95
- {% elif report.prediction == "3" %}
96
- <div class="progress-bar bg-warning" role="progressbar" style="width: 66.4%"></div>
97
- {% elif report.prediction == "4" %}
98
- <div class="progress-bar bg-danger" role="progressbar" style="width: 83.0%"></div>
99
- {% elif report.prediction == "5" %}
100
- <div class="progress-bar bg-danger" role="progressbar" style="width: 100%"></div>
101
- {% elif report.prediction == "N" %}
102
- <div class="progress-bar bg-secondary" role="progressbar" style="width: 100%"></div>
103
- {% endif %}
104
- </div>
105
- <div class="d-flex justify-content-between small text-muted">
106
- <span>0 (Absence)</span>
107
- <span>3 (Moderate)</span>
108
- <span>5 (Occlusion)</span>
109
- </div>
110
- </div>
111
- </div>
112
-
113
- <hr class="my-4">
114
-
115
- </div>
116
- </div>
117
-
118
- <!-- Information Card -->
119
- <div class="card">
120
- <div class="card-header">
121
- <i class="fas fa-info-circle mr-2"></i> Interpretation Guide
122
- </div>
123
- <div class="card-body">
124
- {% if report.prediction == "0" %}
125
- <div class="alert alert-success" role="alert">
126
- <h5 class="alert-heading">CAD-RADS 0: Absence of CAD</h5>
127
- <p>0% stenosis. No plaque or stenosis, normal coronary arteries.</p>
128
- </div>
129
- {% elif report.prediction == "1" %}
130
- <div class="alert alert-info" role="alert">
131
- <h5 class="alert-heading">CAD-RADS 1: Minimal Non-obstructive CAD</h5>
132
- <p>1-24% stenosis. Plaque with minimal luminal narrowing.</p>
133
- </div>
134
- {% elif report.prediction == "2" %}
135
- <div class="alert alert-info" role="alert">
136
- <h5 class="alert-heading">CAD-RADS 2: Mild Non-obstructive CAD</h5>
137
- <p>25-49% stenosis. Plaque with mild luminal narrowing.</p>
138
- </div>
139
- {% elif report.prediction == "3" %}
140
- <div class="alert alert-warning" role="alert">
141
- <h5 class="alert-heading">CAD-RADS 3: Moderate Stenosis</h5>
142
- <p>50-69% stenosis. Plaque with moderate stenosis.</p>
143
- </div>
144
- {% elif report.prediction == "4" %}
145
- <div class="alert alert-danger" role="alert">
146
- <h5 class="alert-heading">CAD-RADS 4: Severe Stenosis</h5>
147
- <p>70-99% stenosis. Plaque with severe stenosis.</p>
148
- </div>
149
- {% elif report.prediction == "5" %}
150
- <div class="alert alert-danger" role="alert">
151
- <h5 class="alert-heading">CAD-RADS 5: Total Occlusion</h5>
152
- <p>100% stenosis. Total coronary occlusion.</p>
153
- </div>
154
- {% elif report.prediction == "N" %}
155
- <div class="alert alert-secondary" role="alert">
156
- <h5 class="alert-heading">CAD-RADS N: Non-diagnostic</h5>
157
- <p>Study cannot be fully evaluated due to image quality or other factors.</p>
158
- </div>
159
- {% endif %}
160
-
161
- <p class="mt-3 mb-1"><strong>Report ID:</strong> #{{ report.report_id }}</p>
162
- <p class="mb-1"><strong>Processed on:</strong> {{ report.timestamp }}</p>
163
- </div>
164
- </div>
165
- </div>
166
- </div>
167
- </div>
168
-
169
- <!-- Footer -->
170
- <footer class="bg-light mt-5 py-3">
171
- <div class="container text-center">
172
- <p class="text-muted mb-0">© 2024 - CCTA Project built by Sudharshan Balaji</p>
173
- </div>
174
- </footer>
175
-
176
- <!-- Scripts -->
177
- <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
178
- <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
179
- </body>
180
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Report Details - CCTA</title>
7
+ <link rel="icon" type="image/x-icon" href="{{ url_for('static', filename='favicon.ico') }}">
8
+ <!-- Google Fonts - Inter -->
9
+ <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap">
10
+ <!-- FontAwesome for icons -->
11
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
12
+ <!-- Bootstrap CSS -->
13
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
14
+ <!-- Custom CSS -->
15
+ <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
16
+ </head>
17
+ <body>
18
+ <!-- Navigation -->
19
+ <nav class="navbar navbar-expand-lg navbar-light">
20
+ <div class="container">
21
+ <a class="navbar-brand d-flex align-items-center" href="{{ url_for('home') }}">
22
+ <img src="{{ url_for('static', filename='logo.svg') }}" alt="CCTA Logo" height="40" class="mr-2">
23
+ </a>
24
+ <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarContent">
25
+ <span class="navbar-toggler-icon"></span>
26
+ </button>
27
+ <div class="collapse navbar-collapse" id="navbarContent">
28
+ <ul class="navbar-nav ml-auto">
29
+ <li class="nav-item">
30
+ <a class="nav-link" href="{{ url_for('home') }}">Dashboard</a>
31
+ </li>
32
+ <li class="nav-item">
33
+ <a class="nav-link" href="{{ url_for('logout') }}">
34
+ <i class="fas fa-sign-out-alt mr-1"></i> Logout
35
+ </a>
36
+ </li>
37
+ </ul>
38
+ </div>
39
+ </div>
40
+ </nav>
41
+
42
+ <!-- Main Content -->
43
+ <div class="container">
44
+ <div class="dashboard-header d-flex align-items-center justify-content-between">
45
+ <div>
46
+ <h1 class="dashboard-title">Report Analysis</h1>
47
+ <p class="dashboard-subtitle">
48
+ <i class="far fa-file-alt mr-1"></i> {{ report.filename }}
49
+ </p>
50
+ </div>
51
+ <a href="{{ url_for('home') }}" class="btn btn-outline-primary">
52
+ <i class="fas fa-arrow-left mr-2"></i> Back to Dashboard
53
+ </a>
54
+ </div>
55
+
56
+ <div class="row">
57
+ <!-- Report Content Section -->
58
+ <div class="col-lg-6">
59
+ <div class="card">
60
+ <div class="card-header d-flex justify-content-between align-items-center">
61
+ <div><i class="fas fa-file-medical-alt mr-2"></i> Report Content</div>
62
+ <span class="badge badge-light">
63
+ <i class="far fa-calendar-alt mr-1"></i> {{ report.timestamp }}
64
+ </span>
65
+ </div>
66
+ <div class="card-body">
67
+ <div class="report-content" style="max-height: 800px;">{{ report.text }}</div>
68
+ </div>
69
+ </div>
70
+ </div>
71
+
72
+ <!-- Analysis Results Section -->
73
+ <div class="col-lg-6">
74
+ <div class="card mb-4">
75
+ <div class="card-header">
76
+ <i class="fas fa-chart-pie mr-2"></i> Analysis Results
77
+ </div>
78
+ <div class="card-body text-center">
79
+ <div class="mb-4">
80
+ <div class="display-4 mb-2">
81
+ <span class="font-weight-bold" style="color: #3f51b5;">CAD-RADS {{ report.prediction }}</span>
82
+ {% if report.modifier and report.modifier != "None" %}
83
+ <span class="font-weight-bold modifier-text">{{ report.modifier }}</span>
84
+ {% endif %}
85
+ </div>
86
+ <div class="text-muted small">Coronary Artery Disease Reporting and Data System Score</div>
87
+ </div>
88
+
89
+ <div class="row mt-4">
90
+ <div class="col-12 text-center">
91
+ <div class="progress mb-3" style="height: 10px;">
92
+ {% if report.prediction == "0" %}
93
+ <div class="progress-bar bg-success" role="progressbar" style="width: 16.6%"></div>
94
+ {% elif report.prediction == "1" %}
95
+ <div class="progress-bar bg-info" role="progressbar" style="width: 33.2%"></div>
96
+ {% elif report.prediction == "2" %}
97
+ <div class="progress-bar bg-info" role="progressbar" style="width: 49.8%"></div>
98
+ {% elif report.prediction == "3" %}
99
+ <div class="progress-bar bg-warning" role="progressbar" style="width: 66.4%"></div>
100
+ {% elif report.prediction == "4" %}
101
+ <div class="progress-bar bg-danger" role="progressbar" style="width: 83.0%"></div>
102
+ {% elif report.prediction == "5" %}
103
+ <div class="progress-bar bg-danger" role="progressbar" style="width: 100%"></div>
104
+ {% elif report.prediction == "N" %}
105
+ <div class="progress-bar bg-secondary" role="progressbar" style="width: 100%"></div>
106
+ {% endif %}
107
+ </div>
108
+ <div class="d-flex justify-content-between small text-muted">
109
+ <span>0 (Absence)</span>
110
+ <span>3 (Moderate)</span>
111
+ <span>5 (Occlusion)</span>
112
+ </div>
113
+ </div>
114
+ </div>
115
+
116
+ {% if report.modifier and report.modifier != "None" %}
117
+ <div class="row mt-3">
118
+ <div class="col-12">
119
+ <div class="d-flex justify-content-between small text-muted mb-1">
120
+ <span>Plaque Burden</span>
121
+ <span class="font-weight-medium">{{ report.modifier }} -
122
+ {% if report.modifier == "P1" %}Mild (CAC 0-99)
123
+ {% elif report.modifier == "P2" %}Moderate (CAC 100-399)
124
+ {% elif report.modifier == "P3" %}Severe (CAC 400-999)
125
+ {% elif report.modifier == "P4" %}Extensive (CAC ≥1000)
126
+ {% endif %}
127
+ </span>
128
+ </div>
129
+ <div class="plaque-burden-indicator">
130
+ <div class="plaque-segments d-flex">
131
+ <div class="plaque-segment p1 {% if report.modifier == 'P1' %}active{% endif %}"></div>
132
+ <div class="plaque-segment p2 {% if report.modifier == 'P2' %}active{% endif %}"></div>
133
+ <div class="plaque-segment p3 {% if report.modifier == 'P3' %}active{% endif %}"></div>
134
+ <div class="plaque-segment p4 {% if report.modifier == 'P4' %}active{% endif %}"></div>
135
+ </div>
136
+ </div>
137
+ </div>
138
+ </div>
139
+ {% endif %}
140
+
141
+ <hr class="my-4">
142
+
143
+ </div>
144
+ </div>
145
+
146
+ <!-- Information Card -->
147
+ <div class="card">
148
+ <div class="card-header">
149
+ <i class="fas fa-info-circle mr-2"></i> Interpretation Guide
150
+ </div>
151
+ <div class="card-body">
152
+ {% if report.prediction == "0" %}
153
+ <div class="alert alert-success" role="alert" style="color: #000000;">
154
+ <h5 class="alert-heading" style="color: #000000;">CAD-RADS 0: Absence of CAD</h5>
155
+ <p>0% stenosis. No plaque or stenosis, normal coronary arteries.</p>
156
+ <hr style="border-color: #000000;">
157
+ <h6 class="font-weight-bold mb-2" style="color: #000000;">Management Considerations:</h6>
158
+ <ul class="mb-0">
159
+ <li>Reassurance</li>
160
+ <li>Consider non-atherosclerotic causes of symptoms</li>
161
+ </ul>
162
+ </div>
163
+ {% elif report.prediction == "1" %}
164
+ <div class="alert alert-info" role="alert" style="color: #000000;">
165
+ <h5 class="alert-heading" style="color: #000000;">CAD-RADS 1: Minimal Non-obstructive CAD</h5>
166
+ <p>1-24% stenosis. Plaque with minimal luminal narrowing.</p>
167
+ <hr style="border-color: #000000;">
168
+ <h6 class="font-weight-bold mb-2" style="color: #000000;">Management Considerations:</h6>
169
+ <ul class="mb-0">
170
+ <li>Consider non-atherosclerotic causes of symptoms</li>
171
+ {% if report.modifier == "P1" %}
172
+ <li>Consider risk factor modification and preventive pharmacotherapy</li>
173
+ {% elif report.modifier == "P2" %}
174
+ <li>Risk factor modification and preventive pharmacotherapy</li>
175
+ {% elif report.modifier == "P3" or report.modifier == "P4" %}
176
+ <li>Aggressive risk factor modification and preventive pharmacotherapy</li>
177
+ {% else %}
178
+ <li>Risk factor modification based on overall risk assessment</li>
179
+ {% endif %}
180
+ </ul>
181
+ </div>
182
+ {% elif report.prediction == "2" %}
183
+ <div class="alert alert-info" role="alert" style="color: #000000;">
184
+ <h5 class="alert-heading" style="color: #000000;">CAD-RADS 2: Mild Non-obstructive CAD</h5>
185
+ <p>25-49% stenosis. Plaque with mild luminal narrowing.</p>
186
+ <hr style="border-color: #000000;">
187
+ <h6 class="font-weight-bold mb-2" style="color: #000000;">Management Considerations:</h6>
188
+ <ul class="mb-0">
189
+ <li>Consider non-atherosclerotic causes of symptoms</li>
190
+ {% if report.modifier == "P1" or report.modifier == "P2" %}
191
+ <li>Risk factor modification and preventive pharmacotherapy</li>
192
+ {% elif report.modifier == "P3" or report.modifier == "P4" %}
193
+ <li>Aggressive risk factor modification and preventive pharmacotherapy</li>
194
+ {% else %}
195
+ <li>Risk factor modification based on overall risk assessment</li>
196
+ {% endif %}
197
+ </ul>
198
+ </div>
199
+ {% elif report.prediction == "3" %}
200
+ <div class="alert alert-warning" role="alert" style="color: #000000;">
201
+ <h5 class="alert-heading" style="color: #000000;">CAD-RADS 3: Moderate Stenosis</h5>
202
+ <p>50-69% stenosis. Plaque with moderate stenosis.</p>
203
+ <hr style="border-color: #000000;">
204
+ <h6 class="font-weight-bold mb-2" style="color: #000000;">Management Considerations:</h6>
205
+ <ul class="mb-0">
206
+ <li>Consider functional assessment</li>
207
+ <li>Aggressive risk factor modification and preventive pharmacotherapy</li>
208
+ <li>Other treatments (including anti-anginal therapy) should be considered per guideline directed care</li>
209
+ <li>When modifier I+, consider invasive coronary angiography (ICA), especially if frequent symptoms persist after guideline-directed medical therapy</li>
210
+ </ul>
211
+ </div>
212
+ {% elif report.prediction == "4" %}
213
+ <div class="alert alert-danger" role="alert" style="color: #000000;">
214
+ <h5 class="alert-heading" style="color: #000000;">CAD-RADS 4: Severe Stenosis</h5>
215
+ <p>70-99% stenosis. Plaque with severe stenosis.</p>
216
+ <hr style="border-color: #000000;">
217
+ <h6 class="font-weight-bold mb-2" style="color: #000000;">Management Considerations:</h6>
218
+ <ul class="mb-0">
219
+ <li>Consider invasive coronary angiography (ICA) or functional assessment</li>
220
+ <li>For left main ≥50% or 3-vessel obstructive disease (≥70%), ICA is recommended</li>
221
+ <li>Aggressive risk factor modification and preventive pharmacotherapy</li>
222
+ <li>Other treatments (including anti-anginal therapy and options of revascularization) should be considered per guideline directed care</li>
223
+ </ul>
224
+ </div>
225
+ {% elif report.prediction == "5" %}
226
+ <div class="alert alert-danger" role="alert" style="color: #000000;">
227
+ <h5 class="alert-heading" style="color: #000000;">CAD-RADS 5: Total Occlusion</h5>
228
+ <p>100% stenosis. Total coronary occlusion.</p>
229
+ <hr style="border-color: #000000;">
230
+ <h6 class="font-weight-bold mb-2" style="color: #000000;">Management Considerations:</h6>
231
+ <ul class="mb-0">
232
+ <li>Consider invasive coronary angiography (ICA), functional and/or viability assessment</li>
233
+ <li>Aggressive risk factor modification and preventive pharmacotherapy</li>
234
+ <li>Other treatments (including anti-anginal therapy and options of revascularization) should be considered per guideline directed care</li>
235
+ </ul>
236
+ </div>
237
+ {% elif report.prediction == "N" %}
238
+ <div class="alert alert-secondary" role="alert" style="color: #000000;">
239
+ <h5 class="alert-heading" style="color: #000000;">CAD-RADS N: Non-diagnostic</h5>
240
+ <p>Study cannot be fully evaluated due to image quality or other factors.</p>
241
+ <hr style="border-color: #000000;">
242
+ <h6 class="font-weight-bold mb-2" style="color: #000000;">Management Considerations:</h6>
243
+ <ul class="mb-0">
244
+ <li>Additional/alternative evaluation may be needed</li>
245
+ <li>Consider alternative imaging or functional testing</li>
246
+ </ul>
247
+ </div>
248
+ {% endif %}
249
+
250
+ {% if report.modifier and report.modifier != "None" %}
251
+ {% if report.prediction != "0" and report.prediction != "N" %}
252
+ {% if report.prediction == "1" or report.prediction == "2" %}
253
+ <div class="alert alert-info mt-3" role="alert" style="color: #000000;">
254
+ <h5 class="alert-heading" style="color: #000000;">Plaque Burden: {{ report.modifier }}</h5>
255
+ {% if report.modifier == "P1" %}
256
+ <p>Mild plaque burden. Coronary artery calcium score 0-99.</p>
257
+ {% elif report.modifier == "P2" %}
258
+ <p>Moderate plaque burden. Coronary artery calcium score 100-399.</p>
259
+ {% elif report.modifier == "P3" %}
260
+ <p>Severe plaque burden. Coronary artery calcium score 400-999.</p>
261
+ {% elif report.modifier == "P4" %}
262
+ <p>Extensive plaque burden. Coronary artery calcium score ≥1000.</p>
263
+ {% endif %}
264
+ </div>
265
+ {% elif report.prediction == "3" %}
266
+ <div class="alert alert-warning mt-3" role="alert" style="color: #000000;">
267
+ <h5 class="alert-heading" style="color: #000000;">Plaque Burden: {{ report.modifier }}</h5>
268
+ {% if report.modifier == "P1" %}
269
+ <p>Mild plaque burden. Coronary artery calcium score 0-99.</p>
270
+ {% elif report.modifier == "P2" %}
271
+ <p>Moderate plaque burden. Coronary artery calcium score 100-399.</p>
272
+ {% elif report.modifier == "P3" %}
273
+ <p>Severe plaque burden. Coronary artery calcium score 400-999.</p>
274
+ {% elif report.modifier == "P4" %}
275
+ <p>Extensive plaque burden. Coronary artery calcium score ≥1000.</p>
276
+ {% endif %}
277
+ </div>
278
+ {% elif report.prediction == "4" or report.prediction == "5" %}
279
+ <div class="alert alert-danger mt-3" role="alert" style="color: #000000;">
280
+ <h5 class="alert-heading" style="color: #000000;">Plaque Burden: {{ report.modifier }}</h5>
281
+ {% if report.modifier == "P1" %}
282
+ <p>Mild plaque burden. Coronary artery calcium score 0-99.</p>
283
+ {% elif report.modifier == "P2" %}
284
+ <p>Moderate plaque burden. Coronary artery calcium score 100-399.</p>
285
+ {% elif report.modifier == "P3" %}
286
+ <p>Severe plaque burden. Coronary artery calcium score 400-999.</p>
287
+ {% elif report.modifier == "P4" %}
288
+ <p>Extensive plaque burden. Coronary artery calcium score ≥1000.</p>
289
+ {% endif %}
290
+ </div>
291
+ {% endif %}
292
+ {% endif %}
293
+ {% endif %}
294
+
295
+ <p class="mt-3 mb-1"><strong>Report ID:</strong> #{{ report.report_id }}</p>
296
+ <p class="mb-1"><strong>Processed on:</strong> {{ report.timestamp }}</p>
297
+ </div>
298
+ </div>
299
+ </div>
300
+ </div>
301
+
302
+ <!-- MESA Score Calculator Card -->
303
+ <div class="row mt-4">
304
+ <div class="col-12">
305
+ <div class="card shadow-sm">
306
+ <div class="card-header bg-white d-flex align-items-center justify-content-between"
307
+ style="cursor: pointer;"
308
+ data-toggle="collapse"
309
+ data-target="#mesaCalculator"
310
+ aria-expanded="false"
311
+ aria-controls="mesaCalculator">
312
+ <div class="d-flex align-items-center flex-grow-1">
313
+ <i class="fas fa-calculator mr-2" style="color: #3f51b5;"></i>
314
+ <span class="font-weight-bold">MESA 10-Year CHD Risk Calculator</span>
315
+ <div id="mesaResultSummary" class="ml-3" style="display: none;">
316
+ <span class="badge badge-primary" id="cac_risk_badge"></span>
317
+ <span class="ml-2 text-muted small">|</span>
318
+ <span class="ml-2 small text-secondary" id="cac_age_summary"></span>
319
+ <span class="mx-2 text-muted small">•</span>
320
+ <span class="badge badge-secondary" id="nocac_risk_badge"></span>
321
+ <span class="ml-2 text-muted small">|</span>
322
+ <span class="ml-2 small text-secondary" id="nocac_age_summary"></span>
323
+ </div>
324
+ </div>
325
+ <i class="fas fa-chevron-down toggle-icon" id="toggleIcon"></i>
326
+ </div>
327
+
328
+ <div class="collapse" id="mesaCalculator">
329
+ <div class="card-body p-4">
330
+ <form id="mesaForm" class="mesa-form">
331
+ <div class="row">
332
+ <!-- First column -->
333
+ <div class="col-lg-4 col-md-6 mesa-column">
334
+ <div class="form-group mb-4">
335
+ <label class="font-weight-medium mb-2">1. Gender</label>
336
+ <div class="d-flex">
337
+ <div class="custom-control custom-radio custom-control-inline">
338
+ <input type="radio" id="genderMale" name="gender" class="custom-control-input" value="m" required>
339
+ <label class="custom-control-label" for="genderMale">Male</label>
340
+ </div>
341
+ <div class="custom-control custom-radio custom-control-inline">
342
+ <input type="radio" id="genderFemale" name="gender" class="custom-control-input" value="f">
343
+ <label class="custom-control-label" for="genderFemale">Female</label>
344
+ </div>
345
+ </div>
346
+ </div>
347
+
348
+ <div class="form-group mb-4">
349
+ <label for="age" class="font-weight-medium mb-2">2. Age (45-85 years)</label>
350
+ <div class="input-group">
351
+ <input type="number" class="form-control" id="age" name="age" min="45" max="85" required>
352
+ <div class="input-group-append">
353
+ <span class="input-group-text bg-light">Years</span>
354
+ </div>
355
+ </div>
356
+ </div>
357
+
358
+ <div class="form-group mb-4">
359
+ <label for="cac" class="font-weight-medium mb-2">3. Coronary Artery Calcification</label>
360
+ <div class="input-group">
361
+ <input type="number" class="form-control" id="cac" name="cac" min="0" placeholder="Enter score (if known)">
362
+ <div class="input-group-append">
363
+ <span class="input-group-text bg-light">Agatston</span>
364
+ </div>
365
+ </div>
366
+ <small class="text-muted mt-1">Leave empty if unknown</small>
367
+ </div>
368
+
369
+ <div class="form-group mb-4">
370
+ <label for="ethnicity" class="font-weight-medium mb-2">4. Race/Ethnicity</label>
371
+ <select class="custom-select" id="ethnicity" name="ethnicity" required>
372
+ <option value="">Choose One</option>
373
+ <option value="1">Caucasian</option>
374
+ <option value="2">Chinese</option>
375
+ <option value="3">African-American</option>
376
+ <option value="4">Hispanic</option>
377
+ </select>
378
+ </div>
379
+ </div>
380
+
381
+ <!-- Second column -->
382
+ <div class="col-lg-4 col-md-6 mesa-column">
383
+ <div class="form-group mb-4">
384
+ <label class="font-weight-medium mb-2">5. Diabetes</label>
385
+ <div class="d-flex">
386
+ <div class="custom-control custom-radio custom-control-inline">
387
+ <input type="radio" id="diabetesYes" name="diabetes" class="custom-control-input" value="1" required>
388
+ <label class="custom-control-label" for="diabetesYes">Yes</label>
389
+ </div>
390
+ <div class="custom-control custom-radio custom-control-inline">
391
+ <input type="radio" id="diabetesNo" name="diabetes" class="custom-control-input" value="0">
392
+ <label class="custom-control-label" for="diabetesNo">No</label>
393
+ </div>
394
+ </div>
395
+ </div>
396
+
397
+ <div class="form-group mb-4">
398
+ <label class="font-weight-medium mb-2">6. Currently Smoke</label>
399
+ <div class="d-flex">
400
+ <div class="custom-control custom-radio custom-control-inline">
401
+ <input type="radio" id="smokeYes" name="smoke" class="custom-control-input" value="1" required>
402
+ <label class="custom-control-label" for="smokeYes">Yes</label>
403
+ </div>
404
+ <div class="custom-control custom-radio custom-control-inline">
405
+ <input type="radio" id="smokeNo" name="smoke" class="custom-control-input" value="0">
406
+ <label class="custom-control-label" for="smokeNo">No</label>
407
+ </div>
408
+ </div>
409
+ </div>
410
+
411
+ <div class="form-group mb-4">
412
+ <label class="font-weight-medium mb-2">7. Family History of Heart Attack</label>
413
+ <small class="form-text text-muted d-block mb-2">(Parents, siblings, children)</small>
414
+ <div class="d-flex">
415
+ <div class="custom-control custom-radio custom-control-inline">
416
+ <input type="radio" id="fhhxYes" name="fhhx" class="custom-control-input" value="1" required>
417
+ <label class="custom-control-label" for="fhhxYes">Yes</label>
418
+ </div>
419
+ <div class="custom-control custom-radio custom-control-inline">
420
+ <input type="radio" id="fhhxNo" name="fhhx" class="custom-control-input" value="0">
421
+ <label class="custom-control-label" for="fhhxNo">No</label>
422
+ </div>
423
+ </div>
424
+ </div>
425
+
426
+ <div class="form-group mb-4">
427
+ <label for="totalCholesterol" class="font-weight-medium mb-2">8. Total Cholesterol</label>
428
+ <div class="input-group">
429
+ <input type="number" class="form-control" id="totalCholesterol" name="chol" min="0" required>
430
+ <div class="input-group-append">
431
+ <span class="input-group-text bg-light">mg/dL</span>
432
+ </div>
433
+ </div>
434
+ </div>
435
+ </div>
436
+
437
+ <!-- Third column -->
438
+ <div class="col-lg-4 col-md-6 mesa-column">
439
+ <div class="form-group mb-4">
440
+ <label for="hdlCholesterol" class="font-weight-medium mb-2">9. HDL Cholesterol</label>
441
+ <div class="input-group">
442
+ <input type="number" class="form-control" id="hdlCholesterol" name="hdl" min="0" required>
443
+ <div class="input-group-append">
444
+ <span class="input-group-text bg-light">mg/dL</span>
445
+ </div>
446
+ </div>
447
+ </div>
448
+
449
+ <div class="form-group mb-4">
450
+ <label for="systolicBP" class="font-weight-medium mb-2">10. Systolic Blood Pressure</label>
451
+ <div class="input-group">
452
+ <input type="number" class="form-control" id="systolicBP" name="sbp" min="0" required>
453
+ <div class="input-group-append">
454
+ <span class="input-group-text bg-light">mmHg</span>
455
+ </div>
456
+ </div>
457
+ </div>
458
+
459
+ <div class="form-group mb-4">
460
+ <label class="font-weight-medium mb-2">11. Lipid Lowering Medication</label>
461
+ <div class="d-flex">
462
+ <div class="custom-control custom-radio custom-control-inline">
463
+ <input type="radio" id="lipidYes" name="lipid" class="custom-control-input" value="1" required>
464
+ <label class="custom-control-label" for="lipidYes">Yes</label>
465
+ </div>
466
+ <div class="custom-control custom-radio custom-control-inline">
467
+ <input type="radio" id="lipidNo" name="lipid" class="custom-control-input" value="0">
468
+ <label class="custom-control-label" for="lipidNo">No</label>
469
+ </div>
470
+ </div>
471
+ </div>
472
+
473
+ <div class="form-group mb-4">
474
+ <label class="font-weight-medium mb-2">12. Hypertension Medication</label>
475
+ <div class="d-flex">
476
+ <div class="custom-control custom-radio custom-control-inline">
477
+ <input type="radio" id="htnmedYes" name="htnmed" class="custom-control-input" value="1" required>
478
+ <label class="custom-control-label" for="htnmedYes">Yes</label>
479
+ </div>
480
+ <div class="custom-control custom-radio custom-control-inline">
481
+ <input type="radio" id="htnmedNo" name="htnmed" class="custom-control-input" value="0">
482
+ <label class="custom-control-label" for="htnmedNo">No</label>
483
+ </div>
484
+ </div>
485
+ </div>
486
+ </div>
487
+ </div>
488
+
489
+ <div class="text-center mt-4">
490
+ <button type="submit" class="btn btn-primary px-5 py-2" id="calculateBtn">
491
+ <i class="fas fa-calculator mr-2"></i>Calculate 10-year CHD risk
492
+ </button>
493
+ <div id="resetBtnContainer" class="mt-3" style="display: none;">
494
+ <button type="button" class="btn btn-outline-secondary" id="resetBtn">
495
+ <i class="fas fa-redo-alt mr-2"></i>Reset Form
496
+ </button>
497
+ </div>
498
+ </div>
499
+ </form>
500
+
501
+ <div id="mesaResults" class="mt-4" style="display: none;">
502
+ <div class="text-center mb-3">
503
+ <h5 class="font-weight-bold" style="color: #3f51b5;">MESA Risk Assessment Results</h5>
504
+ <div class="small text-muted">Based on the Multi-Ethnic Study of Atherosclerosis risk model</div>
505
+ </div>
506
+
507
+ <div class="table-responsive">
508
+ <table class="table table-bordered">
509
+ <thead class="bg-light">
510
+ <tr>
511
+ <th class="font-weight-medium">Risk Assessment</th>
512
+ <th class="font-weight-medium text-center">10-Year CHD Event Risk</th>
513
+ <th class="font-weight-medium text-center">Coronary Age</th>
514
+ <th class="font-weight-medium text-center">Age Difference</th>
515
+ </tr>
516
+ </thead>
517
+ <tbody>
518
+ <tr>
519
+ <td><span class="font-weight-medium">With CAC Score</span></td>
520
+ <td class="text-center font-weight-bold" id="cac_risk" style="color: #3f51b5;">-</td>
521
+ <td class="text-center" id="cac_coronary_age">-</td>
522
+ <td class="text-center" id="cac_age_diff">-</td>
523
+ </tr>
524
+ <tr>
525
+ <td><span class="font-weight-medium">Without CAC Score</span></td>
526
+ <td class="text-center font-weight-bold" id="nocac_risk" style="color: #3f51b5;">-</td>
527
+ <td class="text-center" id="nocac_coronary_age">-</td>
528
+ <td class="text-center" id="nocac_age_diff">-</td>
529
+ </tr>
530
+ </tbody>
531
+ </table>
532
+ </div>
533
+
534
+ <div class="alert alert-light mt-3 small">
535
+ <i class="fas fa-info-circle mr-2"></i> CAC = Coronary Artery Calcium. Including CAC score often provides a more accurate risk assessment compared to traditional risk factors alone.
536
+ </div>
537
+ </div>
538
+ </div>
539
+ </div>
540
+ </div>
541
+ </div>
542
+ </div>
543
+ </div>
544
+
545
+ <!-- Footer -->
546
+ <footer class="bg-light mt-5 py-3">
547
+ <div class="container text-center">
548
+ <p class="text-muted mb-0">© 2024 - CCTA Project built by Sudharshan Balaji</p>
549
+ </div>
550
+ </footer>
551
+
552
+ <!-- Scripts -->
553
+ <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
554
+ <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
555
+
556
+ <!-- Initialize MESA results if they exist -->
557
+ {% if report.mesa_results %}
558
+ <script>
559
+ var mesaResults = {
560
+ cac_riskscore: "{{ report.mesa_results.cac_riskscore }}",
561
+ cac_coronary_age: "{{ report.mesa_results.cac_coronary_age }}",
562
+ cac_age_diff: "{{ report.mesa_results.cac_age_diff }}",
563
+ nocac_riskscore: "{{ report.mesa_results.nocac_riskscore }}",
564
+ nocac_coronary_age: "{{ report.mesa_results.nocac_coronary_age }}",
565
+ nocac_age_diff: "{{ report.mesa_results.nocac_age_diff }}"
566
+ };
567
+
568
+ {% if report.mesa_form_data %}
569
+ var mesaFormData = {
570
+ gender: "{{ report.mesa_form_data.gender }}",
571
+ age: "{{ report.mesa_form_data.age }}",
572
+ cac: "{{ report.mesa_form_data.cac }}",
573
+ ethnicity: "{{ report.mesa_form_data.ethnicity }}",
574
+ diabetes: "{{ report.mesa_form_data.diabetes }}",
575
+ smoke: "{{ report.mesa_form_data.smoke }}",
576
+ fhhx: "{{ report.mesa_form_data.fhhx }}",
577
+ chol: "{{ report.mesa_form_data.chol }}",
578
+ hdl: "{{ report.mesa_form_data.hdl }}",
579
+ sbp: "{{ report.mesa_form_data.sbp }}",
580
+ lipid: "{{ report.mesa_form_data.lipid }}",
581
+ htnmed: "{{ report.mesa_form_data.htnmed }}"
582
+ };
583
+ {% endif %}
584
+ </script>
585
+ {% endif %}
586
+
587
+ <!-- Extract calcium score from report JSON if available -->
588
+ {% if report.json_data and report.json_data.calcium_score %}
589
+ <script>
590
+ var reportCalciumScore = "{{ report.json_data.calcium_score }}";
591
+ console.log("Found calcium score in report: " + reportCalciumScore);
592
+ </script>
593
+ {% endif %}
594
+
595
+ <script>
596
+ $(document).ready(function() {
597
+ // Toggle icon rotation on collapse
598
+ $('#mesaCalculator').on('show.bs.collapse', function () {
599
+ $('#toggleIcon').removeClass('fa-chevron-down').addClass('fa-chevron-up');
600
+ });
601
+
602
+ $('#mesaCalculator').on('hide.bs.collapse', function () {
603
+ $('#toggleIcon').removeClass('fa-chevron-up').addClass('fa-chevron-down');
604
+ });
605
+
606
+ // Function to extract numeric value from calcium score text
607
+ function extractCalciumScore(scoreText) {
608
+ if (!scoreText) return null;
609
+
610
+ console.log("Extracting calcium score from: " + scoreText);
611
+
612
+ // Try to extract a number from the text (handle various formats)
613
+ const matches = scoreText.match(/(\d+(\.\d+)?)/);
614
+ if (matches && matches[1]) {
615
+ console.log("Extracted score: " + matches[1]);
616
+ return matches[1];
617
+ }
618
+
619
+ // Try to handle "zero" or text values
620
+ if (scoreText.toLowerCase().includes('zero') ||
621
+ scoreText.toLowerCase().includes('0') ||
622
+ scoreText.toLowerCase().includes('none')) {
623
+ console.log("Found zero score");
624
+ return "0";
625
+ }
626
+
627
+ console.log("No score found in text");
628
+ return null;
629
+ }
630
+
631
+ // Reset form function
632
+ function resetMesaForm() {
633
+ $('#mesaForm')[0].reset();
634
+ $('#mesaResults').hide();
635
+ $('#mesaResultSummary').hide();
636
+ $('#resetBtnContainer').hide();
637
+
638
+ // Re-populate calcium score from report if available
639
+ populateCalciumScore();
640
+ }
641
+
642
+ // Function to populate calcium score from report data
643
+ function populateCalciumScore() {
644
+ // Check if we have a calcium score from the report
645
+ if (typeof reportCalciumScore !== 'undefined') {
646
+ console.log("Attempting to populate calcium score field");
647
+ const scoreValue = extractCalciumScore(reportCalciumScore);
648
+ if (scoreValue) {
649
+ console.log("Setting CAC input value to: " + scoreValue);
650
+ $('#cac').val(scoreValue);
651
+ }
652
+ } else {
653
+ console.log("No calcium score found in report data");
654
+ }
655
+ }
656
+
657
+ // Reset button click handler
658
+ $('#resetBtn').on('click', function(e) {
659
+ e.preventDefault();
660
+ resetMesaForm();
661
+ });
662
+
663
+ // Fill form with saved values if they exist
664
+ if (typeof mesaFormData !== 'undefined') {
665
+ // Set the gender radio button
666
+ if (mesaFormData.gender === 'm') {
667
+ $('#genderMale').prop('checked', true);
668
+ } else if (mesaFormData.gender === 'f') {
669
+ $('#genderFemale').prop('checked', true);
670
+ }
671
+
672
+ // Set the age
673
+ $('#age').val(mesaFormData.age);
674
+
675
+ // Set CAC score if it exists
676
+ if (mesaFormData.cac && mesaFormData.cac !== '-9') {
677
+ $('#cac').val(mesaFormData.cac);
678
+ }
679
+
680
+ // Set ethnicity
681
+ $('#ethnicity').val(mesaFormData.ethnicity);
682
+
683
+ // Set diabetes
684
+ if (mesaFormData.diabetes === '1') {
685
+ $('#diabetesYes').prop('checked', true);
686
+ } else if (mesaFormData.diabetes === '0') {
687
+ $('#diabetesNo').prop('checked', true);
688
+ }
689
+
690
+ // Set smoke
691
+ if (mesaFormData.smoke === '1') {
692
+ $('#smokeYes').prop('checked', true);
693
+ } else if (mesaFormData.smoke === '0') {
694
+ $('#smokeNo').prop('checked', true);
695
+ }
696
+
697
+ // Set family history
698
+ if (mesaFormData.fhhx === '1') {
699
+ $('#fhhxYes').prop('checked', true);
700
+ } else if (mesaFormData.fhhx === '0') {
701
+ $('#fhhxNo').prop('checked', true);
702
+ }
703
+
704
+ // Set cholesterol values
705
+ $('#totalCholesterol').val(mesaFormData.chol);
706
+ $('#hdlCholesterol').val(mesaFormData.hdl);
707
+
708
+ // Set blood pressure
709
+ $('#systolicBP').val(mesaFormData.sbp);
710
+
711
+ // Set medications
712
+ if (mesaFormData.lipid === '1') {
713
+ $('#lipidYes').prop('checked', true);
714
+ } else if (mesaFormData.lipid === '0') {
715
+ $('#lipidNo').prop('checked', true);
716
+ }
717
+
718
+ if (mesaFormData.htnmed === '1') {
719
+ $('#htnmedYes').prop('checked', true);
720
+ } else if (mesaFormData.htnmed === '0') {
721
+ $('#htnmedNo').prop('checked', true);
722
+ }
723
+ } else {
724
+ // If no saved form data, populate calcium score if available
725
+ populateCalciumScore();
726
+ }
727
+
728
+ // Function to check if there are actual result values (not just dashes)
729
+ function hasActualResults(results) {
730
+ if (!results) return false;
731
+
732
+ // Check if any of the risk scores are actual values (not just "-" or empty)
733
+ return (results.cac_riskscore && results.cac_riskscore !== '-') ||
734
+ (results.nocac_riskscore && results.nocac_riskscore !== '-');
735
+ }
736
+
737
+ // Show results only if they've been calculated previously with actual values
738
+ if (typeof mesaResults !== 'undefined' && hasActualResults(mesaResults)) {
739
+ // Update results table
740
+ $('#cac_risk').text(mesaResults.cac_riskscore || '-');
741
+ $('#cac_coronary_age').text(mesaResults.cac_coronary_age || '-');
742
+ $('#cac_age_diff').text(mesaResults.cac_age_diff || '-');
743
+ $('#nocac_risk').text(mesaResults.nocac_riskscore || '-');
744
+ $('#nocac_coronary_age').text(mesaResults.nocac_coronary_age || '-');
745
+ $('#nocac_age_diff').text(mesaResults.nocac_age_diff || '-');
746
+
747
+ // Update summary badges in header for when collapsed
748
+ $('#cac_risk_badge').text('With CAC: ' + (mesaResults.cac_riskscore || '-'));
749
+ $('#nocac_risk_badge').text('Without CAC: ' + (mesaResults.nocac_riskscore || '-'));
750
+
751
+ // Add coronary age summary if available
752
+ if (mesaResults.cac_coronary_age && mesaResults.cac_coronary_age !== '-') {
753
+ $('#cac_age_summary').text('Coronary Age: ' + mesaResults.cac_coronary_age);
754
+ }
755
+
756
+ if (mesaResults.nocac_coronary_age && mesaResults.nocac_coronary_age !== '-') {
757
+ $('#nocac_age_summary').text('Coronary Age: ' + mesaResults.nocac_coronary_age);
758
+ }
759
+
760
+ // Show the results sections
761
+ $('#mesaResultSummary').show();
762
+ $('#mesaResults').show();
763
+ $('#resetBtnContainer').show();
764
+ } else {
765
+ // Hide results sections if no previous calculation
766
+ $('#mesaResults').hide();
767
+ $('#mesaResultSummary').hide();
768
+ $('#resetBtnContainer').hide();
769
+ }
770
+
771
+ $('#mesaForm').on('submit', function(e) {
772
+ e.preventDefault();
773
+
774
+ const formData = {};
775
+ $(this).serializeArray().forEach(item => {
776
+ formData[item.name] = item.value;
777
+ });
778
+
779
+ // Add report ID to the form data
780
+ formData.report_id = "{{ report.report_id }}";
781
+
782
+ // Show loading state
783
+ $('#calculateBtn').html('<span class="spinner-border spinner-border-sm mr-2" role="status" aria-hidden="true"></span>Calculating...').prop('disabled', true);
784
+ $('#resetBtn').prop('disabled', true);
785
+
786
+ $.ajax({
787
+ url: '/calculate_mesa_score',
788
+ type: 'POST',
789
+ contentType: 'application/json',
790
+ data: JSON.stringify(formData),
791
+ success: function(response) {
792
+ // Only show results if we have actual values (not just dashes)
793
+ if (response.cac_riskscore && response.cac_riskscore !== '-' ||
794
+ response.nocac_riskscore && response.nocac_riskscore !== '-') {
795
+
796
+ // Update results table
797
+ $('#cac_risk').text(response.cac_riskscore || '-');
798
+ $('#cac_coronary_age').text(response.cac_coronary_age || '-');
799
+ $('#cac_age_diff').text(response.cac_age_diff || '-');
800
+ $('#nocac_risk').text(response.nocac_riskscore || '-');
801
+ $('#nocac_coronary_age').text(response.nocac_coronary_age || '-');
802
+ $('#nocac_age_diff').text(response.nocac_age_diff || '-');
803
+
804
+ // Update summary badges in header for when collapsed
805
+ $('#cac_risk_badge').text('With CAC: ' + (response.cac_riskscore || '-'));
806
+ $('#nocac_risk_badge').text('Without CAC: ' + (response.nocac_riskscore || '-'));
807
+
808
+ // Add coronary age summary if available
809
+ if (response.cac_coronary_age && response.cac_coronary_age !== '-') {
810
+ $('#cac_age_summary').text('Coronary Age: ' + response.cac_coronary_age);
811
+ } else {
812
+ $('#cac_age_summary').text('');
813
+ }
814
+
815
+ if (response.nocac_coronary_age && response.nocac_coronary_age !== '-') {
816
+ $('#nocac_age_summary').text('Coronary Age: ' + response.nocac_coronary_age);
817
+ } else {
818
+ $('#nocac_age_summary').text('');
819
+ }
820
+
821
+ // Show results sections
822
+ $('#mesaResultSummary').show();
823
+ $('#mesaResults').show();
824
+ $('#resetBtnContainer').show();
825
+ } else {
826
+ alert('The calculation did not return valid results. Please check your inputs and try again.');
827
+ }
828
+
829
+ // Reset button
830
+ $('#calculateBtn').html('<i class="fas fa-calculator mr-2"></i>Calculate 10-year CHD risk').prop('disabled', false);
831
+ $('#resetBtn').prop('disabled', false);
832
+ },
833
+ error: function(error) {
834
+ alert('Error calculating MESA score: ' + (error.responseJSON?.error || 'Unknown error'));
835
+ $('#calculateBtn').html('<i class="fas fa-calculator mr-2"></i>Calculate 10-year CHD risk').prop('disabled', false);
836
+ $('#resetBtn').prop('disabled', false);
837
+ }
838
+ });
839
+ });
840
+
841
+ // Style the modifier text based on content
842
+ $('.modifier-text').each(function() {
843
+ var modifierText = $(this).text().trim();
844
+ if (modifierText === 'P1') {
845
+ $(this).css('background-color', '#43a047'); // Success/green
846
+ } else if (modifierText === 'P2') {
847
+ $(this).css('background-color', '#039be5'); // Info/blue
848
+ } else if (modifierText === 'P3') {
849
+ $(this).css('background-color', '#ff9800'); // Warning/orange
850
+ } else if (modifierText === 'P4') {
851
+ $(this).css('background-color', '#e53935'); // Danger/red
852
+ }
853
+ });
854
+ });
855
+ </script>
856
+
857
+ <style>
858
+ /* Custom styles for MESA calculator */
859
+ .font-weight-medium {
860
+ font-weight: 500;
861
+ }
862
+
863
+ .custom-control-input:checked ~ .custom-control-label::before {
864
+ border-color: #3f51b5;
865
+ background-color: #3f51b5;
866
+ }
867
+
868
+ .custom-select:focus, .form-control:focus {
869
+ border-color: #3f51b5;
870
+ box-shadow: 0 0 0 0.2rem rgba(63, 81, 181, 0.25);
871
+ }
872
+
873
+ .mesa-form label {
874
+ color: #333;
875
+ }
876
+
877
+ .input-group-text.bg-light {
878
+ background-color: #f8f9fa;
879
+ color: #6c757d;
880
+ border-color: #ced4da;
881
+ }
882
+
883
+ /* Column styling for MESA calculator */
884
+ .mesa-column {
885
+ padding: 0 1.25rem;
886
+ }
887
+
888
+ @media (min-width: 992px) {
889
+ .mesa-column:not(:first-child) {
890
+ border-left: 1px solid #e9ecef;
891
+ }
892
+
893
+ .mesa-column {
894
+ padding: 0.5rem 1.5rem;
895
+ }
896
+ }
897
+
898
+ /* Make form fields more consistent in height */
899
+ .mesa-form .input-group,
900
+ .mesa-form .custom-select {
901
+ height: 38px;
902
+ }
903
+
904
+ .mesa-form .form-control {
905
+ height: 38px;
906
+ padding: 0.375rem 0.75rem;
907
+ }
908
+
909
+ /* For collapsible card */
910
+ .toggle-icon {
911
+ transition: transform 0.3s;
912
+ }
913
+
914
+ .card-header[aria-expanded="true"] .toggle-icon {
915
+ transform: rotate(180deg);
916
+ }
917
+
918
+ #cac_risk_badge {
919
+ background-color: #3f51b5;
920
+ font-weight: 500;
921
+ padding: 5px 10px;
922
+ border-radius: 30px;
923
+ }
924
+
925
+ #nocac_risk_badge {
926
+ background-color: #6c757d;
927
+ font-weight: 500;
928
+ padding: 5px 10px;
929
+ border-radius: 30px;
930
+ }
931
+
932
+ /* Modifier styling */
933
+ .modifier-text {
934
+ margin-left: 15px;
935
+ border-radius: 8px;
936
+ padding: 0 10px;
937
+ font-size: 0.9em;
938
+ color: white;
939
+ display: inline-flex;
940
+ align-items: center;
941
+ vertical-align: middle;
942
+ position: relative;
943
+ top: -5px;
944
+ }
945
+
946
+ /* Plaque burden indicator */
947
+ .plaque-burden-indicator {
948
+ margin-top: 5px;
949
+ margin-bottom: 10px;
950
+ }
951
+
952
+ .plaque-segments {
953
+ height: 8px;
954
+ border-radius: 4px;
955
+ overflow: hidden;
956
+ }
957
+
958
+ .plaque-segment {
959
+ flex: 1;
960
+ height: 100%;
961
+ opacity: 0.2;
962
+ transition: opacity 0.3s;
963
+ }
964
+
965
+ .plaque-segment.active {
966
+ opacity: 1;
967
+ }
968
+
969
+ .plaque-segment.p1 {
970
+ background-color: #43a047;
971
+ }
972
+
973
+ .plaque-segment.p2 {
974
+ background-color: #039be5;
975
+ }
976
+
977
+ .plaque-segment.p3 {
978
+ background-color: #ff9800;
979
+ }
980
+
981
+ .plaque-segment.p4 {
982
+ background-color: #e53935;
983
+ }
984
+ </style>
985
+ </body>
986
+ </html>