File size: 38,538 Bytes
a113cef
 
 
a8af1a7
 
 
 
47a7ca5
a113cef
18bb408
 
 
 
f5ec716
 
 
 
 
 
 
 
 
a113cef
 
 
a8af1a7
a113cef
 
47a7ca5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a82a162
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6301ef2
 
 
8f52fcd
6301ef2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f52fcd
 
6301ef2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a82a162
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47a7ca5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b40662a
47a7ca5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a113cef
a8af1a7
 
 
 
 
 
 
 
 
 
 
fcd3e1e
47a7ca5
a8af1a7
a113cef
fcd3e1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9959b2f
fcd3e1e
 
 
 
9959b2f
fcd3e1e
9959b2f
 
 
 
1f9fd23
9959b2f
fcd3e1e
 
1f9fd23
fcd3e1e
9959b2f
 
 
 
 
1f9fd23
 
 
 
fcd3e1e
9959b2f
1f9fd23
 
 
 
 
 
 
 
 
9959b2f
b40662a
9959b2f
b40662a
 
1f9fd23
 
 
 
 
 
 
b40662a
 
9959b2f
 
 
b40662a
1f9fd23
9959b2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcd3e1e
9959b2f
 
fcd3e1e
1f9fd23
 
 
 
 
 
fcd3e1e
9959b2f
 
 
1f9fd23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9959b2f
 
 
e0bc7e2
 
 
9959b2f
1f9fd23
 
 
 
 
9959b2f
fcd3e1e
18bb408
 
 
 
 
 
 
 
e8bb780
 
18bb408
 
 
 
 
 
 
3064620
fcd3e1e
47a7ca5
18bb408
47a7ca5
18bb408
 
e8bb780
18bb408
fcd3e1e
e8bb780
 
 
18bb408
fcd3e1e
18bb408
e8bb780
fcd3e1e
18bb408
fcd3e1e
e8bb780
 
fcd3e1e
18bb408
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8bb780
fcd3e1e
18bb408
 
 
 
 
 
e8bb780
18bb408
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8bb780
18bb408
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcd3e1e
 
 
 
 
6301ef2
 
 
 
 
47a7ca5
 
 
6301ef2
fcd3e1e
6301ef2
 
fcd3e1e
 
 
 
6301ef2
fcd3e1e
6301ef2
fcd3e1e
 
 
 
 
6301ef2
 
a82a162
fcd3e1e
47a7ca5
 
 
 
fcd3e1e
 
 
 
47a7ca5
fcd3e1e
6301ef2
 
fcd3e1e
 
 
 
47a7ca5
 
 
fcd3e1e
47a7ca5
 
fcd3e1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47a7ca5
 
 
 
 
 
 
 
 
fcd3e1e
 
 
 
47a7ca5
fcd3e1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47a7ca5
fcd3e1e
47a7ca5
fcd3e1e
 
 
6301ef2
fcd3e1e
6301ef2
fcd3e1e
47a7ca5
fcd3e1e
 
 
 
6301ef2
 
 
 
fcd3e1e
 
 
 
 
 
6301ef2
fcd3e1e
 
 
 
a113cef
47a7ca5
 
 
a113cef
cd40158
 
 
a113cef
 
cd40158
 
a113cef
 
cd40158
 
 
 
 
 
 
 
 
 
 
 
 
9959b2f
 
 
a113cef
a8af1a7
9959b2f
d53279a
9959b2f
cd40158
 
3064620
a113cef
cd40158
 
 
 
a8af1a7
 
cd40158
a8af1a7
 
 
cd40158
 
3064620
 
cd40158
3064620
cd40158
 
3064620
9959b2f
cd40158
3064620
 
cd40158
 
3064620
 
 
 
cd40158
3064620
 
 
fcd3e1e
cd40158
 
 
 
 
3064620
9959b2f
3064620
cd40158
 
 
 
3064620
 
 
cd40158
3064620
 
cd40158
3064620
cd40158
 
3064620
cd40158
 
3064620
 
 
fcd3e1e
 
cd40158
3064620
 
cd40158
 
 
 
 
3064620
a113cef
a8af1a7
 
3d04a49
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
import gradio as gr
import pandas as pd
from dataclasses import dataclass, field
from typing import List, Dict, Tuple, Union
import json
import os
from collections import OrderedDict
import re

import plotly.graph_objects as go
import plotly.express as px
# from plotly.subplots import make_subplots
# import math

def load_css(css_file_path):
    """Load CSS from a file."""
    with open(css_file_path, 'r') as f:
        return f.read()

# In the main code:
css = load_css('dashboard.css')

@dataclass
class ScorecardCategory:
    name: str
    questions: List[Dict[str, Union[str, List[str]]]]
    scores: Dict[str, int] = field(default_factory=dict)


def extract_category_number(category_name: str) -> int:
    """Extract the category number from the category name."""
    match = re.match(r'^(\d+)\.?\s*.*$', category_name)
    return int(match.group(1)) if match else float('inf')

def sort_categories(categories):
    """Sort categories by their numeric prefix."""
    return sorted(categories, key=extract_category_number)


# def load_scorecard_templates(directory):
#     templates = []
#     for filename in os.listdir(directory):
#         if filename.endswith('.json'):
#             with open(os.path.join(directory, filename), 'r') as file:
#                 data = json.load(file)
#                 templates.append(ScorecardCategory(
#                     name=data['name'],
#                     questions=data['questions']
#                 ))
#     return templates

def create_category_summary(category_data):
    """Create a summary section for a category"""
    # Calculate statistics
    total_sections = len(category_data)
    completed_sections = sum(1 for section in category_data.values() if section['status'] == 'Yes')
    na_sections = sum(1 for section in category_data.values() if section['status'] == 'N/A')
    
    # Calculate completion rates
    total_questions = 0
    completed_questions = 0
    evaluation_types = set()
    has_human_eval = False
    has_quantitative = False
    has_documentation = False
    
    for section in category_data.values():
        if section['status'] != 'N/A':
            questions = section.get('questions', {})
            total_questions += len(questions)
            completed_questions += sum(1 for q in questions.values() if q)
            
            # Check for evaluation types
            for question in questions.keys():
                if 'human' in question.lower():
                    has_human_eval = True
                if any(term in question.lower() for term in ['quantitative', 'metric', 'benchmark']):
                    has_quantitative = True
                if 'documentation' in question.lower():
                    has_documentation = True
    
    completion_rate = (completed_questions / total_questions * 100) if total_questions > 0 else 0
    
    # Create summary HTML
    html = "<div class='summary-card'>"
    html += "<div class='summary-title'>πŸ“Š Section Summary</div>"
    
    # Completion metrics
    html += "<div class='summary-section'>"
    html += "<div class='summary-subtitle'>πŸ“ˆ Completion Metrics</div>"
    html += f"<div class='metric-row'><span class='metric-label'>Overall Completion Rate:</span> <span class='metric-value'>{completion_rate:.1f}%</span></div>"
    html += f"<div class='metric-row'><span class='metric-label'>Sections Completed:</span> <span class='metric-value'>{completed_sections}/{total_sections}</span></div>"
    html += "</div>"
    
    # Evaluation Coverage
    html += "<div class='summary-section'>"
    html += "<div class='summary-subtitle'>🎯 Evaluation Coverage</div>"
    html += "<div class='coverage-grid'>"
    html += f"<div class='coverage-item {get_coverage_class(has_human_eval)}'>πŸ‘₯ Human Evaluation</div>"
    html += f"<div class='coverage-item {get_coverage_class(has_quantitative)}'>πŸ“Š Quantitative Analysis</div>"
    html += f"<div class='coverage-item {get_coverage_class(has_documentation)}'>πŸ“ Documentation</div>"
    html += "</div>"
    html += "</div>"
    
    # Status Breakdown
    html += "<div class='summary-section'>"
    html += "<div class='summary-subtitle'>πŸ“‹ Status Breakdown</div>"
    html += create_status_pills(category_data)
    html += "</div>"
    
    html += "</div>"
    return html

def create_overall_summary(model_data, selected_categories):
    """Create a comprehensive summary of all categories"""
    scores = model_data['scores']
    model_name = model_data['metadata']['Name']
    
    # Initialize counters
    total_sections = 0
    completed_sections = 0
    na_sections = 0
    total_questions = 0
    completed_questions = 0
    
    # Track evaluation types across all categories
    evaluation_types = {
        'human': 0,
        'quantitative': 0,
        'documentation': 0,
        'monitoring': 0,
        'transparency': 0
    }
    
    # Calculate completion rates for categories
    category_completion = {}
    
    # Process all categories
    for category, category_data in scores.items():
        if category not in selected_categories:
            continue  # Skip unselected categories
            
        category_questions = 0
        category_completed = 0
        category_na = 0
        total_sections_in_category = len(category_data)
        na_sections_in_category = sum(1 for section in category_data.values() if section['status'] == 'N/A')
        
        for section in category_data.values():
            total_sections += 1
            if section['status'] == 'Yes':
                completed_sections += 1
            elif section['status'] == 'N/A':
                na_sections += 1
                category_na += 1
                
            if section['status'] != 'N/A':
                questions = section.get('questions', {})
                section_total = len(questions)
                section_completed = sum(1 for q in questions.values() if q)
                
                total_questions += section_total
                completed_questions += section_completed
                category_questions += section_total
                category_completed += section_completed
                
                # Check for evaluation types
                for question in questions.keys():
                    if 'human' in question.lower():
                        evaluation_types['human'] += 1
                    if any(term in question.lower() for term in ['quantitative', 'metric', 'benchmark']):
                        evaluation_types['quantitative'] += 1
                    if 'documentation' in question.lower():
                        evaluation_types['documentation'] += 1
                    if 'monitoring' in question.lower():
                        evaluation_types['monitoring'] += 1
                    if 'transparency' in question.lower():
                        evaluation_types['transparency'] += 1
        
        # Store category information
        is_na = na_sections_in_category == total_sections_in_category
        completion_rate = (category_completed / category_questions * 100) if category_questions > 0 and not is_na else 0
        
        category_completion[category] = {
            'completion_rate': completion_rate,
            'is_na': is_na
        }
    
    # Create summary HTML
    html = "<div class='card overall-summary-card'>"
    html += f"<div class='card-title'>πŸ“Š {model_name} Social Impact Evaluation Summary</div>"    

    # Key metrics section
    html += "<div class='summary-grid'>"
    
    # Overall completion metrics
    html += "<div class='summary-section'>"
    html += "<div class='summary-subtitle'>πŸ“ˆ Overall Completion</div>"
    completion_rate = (completed_questions / total_questions * 100) if total_questions > 0 else 0
    html += f"<div class='metric-row'><span class='metric-label'>Overall Completion Rate:</span> <span class='metric-value'>{completion_rate:.1f}%</span></div>"
    html += f"<div class='metric-row'><span class='metric-label'>Sections Completed:</span> <span class='metric-value'>{completed_sections}/{total_sections}</span></div>"
    html += f"<div class='metric-row'><span class='metric-label'>Questions Completed:</span> <span class='metric-value'>{completed_questions}/{total_questions}</span></div>"
    html += "</div>"
    
    # Evaluation coverage
    html += "<div class='summary-section'>"
    html += "<div class='summary-subtitle'>🎯 Evaluation Types Coverage</div>"
    html += "<div class='coverage-grid'>"
    for eval_type, count in evaluation_types.items():
        icon = {
            'human': 'πŸ‘₯',
            'quantitative': 'πŸ“Š',
            'documentation': 'πŸ“',
            'monitoring': 'πŸ“‘',
            'transparency': 'πŸ”'
        }.get(eval_type, '❓')
        has_coverage = count > 0
        html += f"<div class='coverage-item {get_coverage_class(has_coverage)}'>{icon} {eval_type.title()}</div>"
    html += "</div>"
    html += "</div>"
    
    html += "</div>"  # End summary-grid
    
    # Category breakdown
    html += "<div class='summary-section'>"
    html += "<div class='summary-subtitle'>πŸ“‹ Category Completion Breakdown</div>"
    html += "<div class='category-completion-grid'>"
    
    # Sort and filter categories
    sorted_categories = [cat for cat in sort_categories(scores.keys()) if cat in selected_categories]
    
    for category in sorted_categories:
        info = category_completion[category]
        category_name = category.split('. ', 1)[1] if '. ' in category else category
        
        # Determine display text and style
        if info['is_na']:
            completion_text = "N/A"
            bar_width = "0"
            style_class = "na"
        else:
            completion_text = f"{info['completion_rate']:.1f}%"
            bar_width = f"{info['completion_rate']}"
            style_class = "active"
        
        html += f"""
        <div class='category-completion-item'>
            <div class='category-name'>{category_name}</div>
            <div class='completion-bar-container {style_class}'>
                <div class='completion-bar' style='width: {bar_width}%;'></div>
                <span class='completion-text'>{completion_text}</span>
            </div>
        </div>
        """
    
    html += "</div></div>"
    html += "</div>"  # End overall-summary-card
    return html

def get_coverage_class(has_feature):
    """Return CSS class based on feature presence"""
    return 'covered' if has_feature else 'not-covered'

def create_status_pills(category_data):
    """Create status pill indicators"""
    status_counts = {'Yes': 0, 'No': 0, 'N/A': 0}
    for section in category_data.values():
        status_counts[section['status']] += 1
    
    html = "<div class='status-pills'>"
    for status, count in status_counts.items():
        html += f"<div class='status-pill {status.lower()}'>{status}: {count}</div>"
    html += "</div>"
    return html

def get_modality_icon(modality):
    """Return an emoji icon for each modality type."""
    icons = {
        "Text-to-Text": "πŸ“",  # Memo icon for text-to-text
        "Text-to-Image": "🎨",  # Artist palette for text-to-image
        "Image-to-Text": "πŸ”",  # Magnifying glass for image-to-text
        "Image-to-Image": "πŸ–ΌοΈ",  # Frame for image-to-image
        "Audio": "🎡",  # Musical note for audio
        "Video": "🎬",  # Clapper board for video
        "Multimodal": "πŸ”„"  # Cycle arrows for multimodal
    }
    return icons.get(modality, "πŸ’«")  # Default icon if modality not found

def create_metadata_card(metadata):
    """Create a formatted HTML card for metadata."""
    html = "<div class='card metadata-card'>"
    html += "<div class='card-title'>AI System Information</div>"
    html += "<div class='metadata-content'>"
    
    # Handle special formatting for modalities
    modalities = metadata.get("Modalities", [])
    formatted_modalities = ""
    if modalities:
        formatted_modalities = " ".join(
            f"<span class='modality-badge'>{get_modality_icon(m)} {m}</span>"
            for m in modalities
        )
    
    # Order of metadata display (customize as needed)
    display_order = ["Name", "Provider", "Type", "URL"]
    
    # Display ordered metadata first
    for key in display_order:
        if key in metadata:
            value = metadata[key]
            if key == "URL":
                html += f"<div class='metadata-row'><span class='metadata-label'>{key}:</span> "
                html += f"<a href='{value}' target='_blank' class='metadata-link'>{value}</a></div>"
            else:
                html += f"<div class='metadata-row'><span class='metadata-label'>{key}:</span> <span class='metadata-value'>{value}</span></div>"
    
    # Add modalities if present
    if formatted_modalities:
        html += f"<div class='metadata-row'><span class='metadata-label'>Modalities:</span> <div class='modality-container'>{formatted_modalities}</div></div>"
    
    # Add any remaining metadata not in display_order
    for key, value in metadata.items():
        if key not in display_order and key != "Modalities":
            html += f"<div class='metadata-row'><span class='metadata-label'>{key}:</span> <span class='metadata-value'>{value}</span></div>"
    
    html += "</div></div>"
    return html


def load_models_from_json(directory):
    models = {}
    for filename in os.listdir(directory):
        if filename.endswith('.json'):
            with open(os.path.join(directory, filename), 'r') as file:
                model_data = json.load(file)
                model_name = model_data['metadata']['Name']
                models[model_name] = model_data
    
    return OrderedDict(sorted(models.items(), key=lambda x: x[0].lower()))

# Load templates and models
# scorecard_template = load_scorecard_templates('scorecard_templates')
models = load_models_from_json('model_data')

def create_source_html(sources):
    if not sources:
        return ""
    
    html = "<div class='sources-list'>"
    for source in sources:
        icon = source.get("type", "")
        detail = source.get("detail", "")
        name = source.get("name", detail)
        
        html += f"<div class='source-item'>{icon} "
        if detail.startswith("http"):
            html += f"<a href='{detail}' target='_blank'>{name}</a>"
        else:
            html += name
        html += "</div>"
    html += "</div>"
    return html

def create_leaderboard(selected_categories):
    scores = []
    for model, data in models.items():
        total_score = 0
        total_questions = 0
        score_by_category = {}
        
        # Calculate scores by category
        for category_name, category in data['scores'].items():
            category_score = 0
            category_total = 0
            all_na = True
            
            for section in category.values():
                if section['status'] != 'N/A':
                    all_na = False
                    questions = section.get('questions', {})
                    category_score += sum(1 for q in questions.values() if q)
                    category_total += len(questions)
            
            if category_total > 0:
                score_by_category[category_name] = (category_score / category_total) * 100
            elif all_na:
                score_by_category[category_name] = "N/A"
            total_score += category_score
            total_questions += category_total
        
        # Calculate overall score
        overall_all_na = all(
            all(section['status'] == 'N/A' for section in category.values())
            for category_name, category in data['scores'].items()
            if category_name in selected_categories
        )
        
        score_percentage = "N/A" if overall_all_na else (
            (total_score / total_questions * 100) if total_questions > 0 else 0
        )
        
        # Get model type and URL
        model_type = data['metadata'].get('Type', 'Unknown')
        model_url = data['metadata'].get('URL', '')
        
        # Get modalities and create badges
        modalities = data['metadata'].get('Modalities', [])
        modality_badges = " ".join(
            f"<span class='modality-badge'>{get_modality_icon(m)} {m}</span>"
            for m in modalities
        ) if modalities else "<span class='modality-badge'>πŸ’« Unknown</span>"
        
        # Create model name with HTML link if URL exists
        model_display = f'<a href="{model_url}" target="_blank">{model}</a>' if model_url else model
        
        # Create entry with numerical scores
        model_entry = {
            'AI System': model_display,
            'Modality': f"<div class='modality-container'>{modality_badges}</div>",
            'Overall Completion Rate': score_percentage
        }
        
        # Add selected category scores with emojis
        category_map = {
            '1. Bias, Stereotypes, and Representational Harms Evaluation': 'βš–οΈ Bias and Fairness',
            '2. Cultural Values and Sensitive Content Evaluation': '🌍 Cultural Values',
            '3. Disparate Performance Evaluation': 'πŸ“Š Disparate Performance',
            '4. Environmental Costs and Carbon Emissions Evaluation': '🌱 Environmental Impact',
            '5. Privacy and Data Protection Evaluation': 'πŸ”’ Privacy',
            '6. Financial Costs Evaluation': 'πŸ’° Financial Costs',
            '7. Data and Content Moderation Labor Evaluation': 'πŸ‘₯ Labor Practices'
        }
        
        for full_cat_name, display_name in category_map.items():
            if full_cat_name in selected_categories:
                score = score_by_category.get(full_cat_name, 0)
                model_entry[display_name] = score
        
        scores.append(model_entry)
    
    # Convert to DataFrame
    df = pd.DataFrame(scores)
    
    # Sort by Overall Completion Rate descending, putting N/A at the end
    df['_sort_value'] = df['Overall Completion Rate'].apply(
        lambda x: -float('inf') if x == "N/A" else float(x)
    )
    df = df.sort_values('_sort_value', ascending=False)
    df = df.drop('_sort_value', axis=1)
    
    # Add rank column based on current sort
    df.insert(0, 'Rank', range(1, len(df) + 1))
    
    # Get completion rate columns (Overall + category-specific)
    completion_rate_columns = ['Overall Completion Rate'] + [
        display_name for full_cat_name, display_name in category_map.items()
        if full_cat_name in selected_categories
    ]
    
    # Format non-completion rate columns
    df['Rank'] = df['Rank'].astype(str)
    
    # Identify and format highest values for completion rate columns
    for col in completion_rate_columns:
        if col in df.columns:
            # Filter out N/A values to find the maximum numerical value
            numeric_values = df[df[col] != "N/A"][col]
            if not numeric_values.empty:
                max_value = numeric_values.max()
                df[col] = df.apply(
                    lambda row: "N/A" if row[col] == "N/A"
                    else f"**{row[col]:.1f}%**" if row[col] == max_value 
                    else f"{row[col]:.1f}%", 
                    axis=1
                )
            else:
                df[col] = df[col].apply(lambda x: "N/A")
    
    return df

first_model = next(iter(models.values()))
category_choices = list(first_model['scores'].keys())

with gr.Column(visible=True) as leaderboard_tab:
    leaderboard_output = gr.DataFrame(
        value=create_leaderboard(category_choices),
        interactive=False,
        wrap=True,
        datatype=["markdown", "markdown", "markdown"] + ["markdown"] * (len(category_choices)+1)  # Support markdown in all columns
    )

def hex_to_rgba(hex_color, alpha):
    """Convert hex color to rgba string with given alpha value."""
    hex_color = hex_color.lstrip('#')
    r = int(hex_color[:2], 16)
    g = int(hex_color[2:4], 16)
    b = int(hex_color[4:], 16)
    return f'rgba({r},{g},{b},{alpha})'

def create_category_chart(selected_systems, selected_categories):
    if not selected_systems:
        fig = go.Figure()
        fig.add_annotation(
            text="Please select at least one AI system for comparison",
            xref="paper", yref="paper",
            x=0.5, y=0.5,
            showarrow=False
        )
        return fig
    
    selected_categories = sort_categories(selected_categories)
    BASE_SCORE = 5
    
    # Prepare all data first
    all_data = []
    for system_name in selected_systems:
        system_data = []
        for category in selected_categories:
            if category in models[system_name]['scores']:
                completed = 0
                total = 0
                category_name = category.split('.')[1].strip()
                
                all_na = True
                for section in models[system_name]['scores'][category].values():
                    if section['status'] != 'N/A':
                        all_na = False
                        questions = section.get('questions', {})
                        completed += sum(1 for q in questions.values() if q)
                        total += len(questions)
                
                if all_na:
                    score = BASE_SCORE
                    display_score = 0
                    status = 'N/A'
                elif total > 0:
                    raw_score = (completed / total) * 100
                    score = BASE_SCORE + (90 * raw_score / 100)
                    display_score = raw_score
                    status = 'Active'
                else:
                    score = BASE_SCORE
                    display_score = 0
                    status = 'Active'
                
                system_data.append({
                    'AI System': system_name,
                    'Category': category_name,
                    'Score': score,
                    'Display Score': display_score,
                    'Status': status,
                    'Original Score': f"{display_score:.1f}%",
                    'Completed': completed,
                    'Total': total
                })
        if system_data:
            # Add first point again to close the shape
            system_data.append(system_data[0].copy())
            all_data.extend(system_data)
    
    df = pd.DataFrame(all_data)
    
    if df.empty:
        fig = go.Figure()
        fig.add_annotation(
            text="No data available for the selected AI systems and categories",
            xref="paper", yref="paper",
            x=0.5, y=0.5,
            showarrow=False
        )
        return fig
    
    fig = go.Figure()
    
    # Define colors
    colors = [
        '#FF4B4B', '#4B7BFF', '#4BFF4B', '#FFD700', '#FF4BFF',
        '#4BFFFF', '#FF884B', '#884BFF', '#4BFF88', '#FFFF4B'
    ]
    
    # Calculate average scores for sorting
    system_scores = {
        system: df[df['AI System'] == system]['Score'].mean()
        for system in selected_systems
    }
    sorted_systems = sorted(selected_systems, 
                          key=lambda x: system_scores[x], 
                          reverse=True)
    
    # Plot each system
    for idx, system_name in enumerate(sorted_systems):
        system_df = df[df['AI System'] == system_name]
        
        # Get color for this system
        base_color = colors[idx % len(colors)]
        line_color = hex_to_rgba(base_color, 0.9)
        fill_color = hex_to_rgba(base_color, 0.15)
        hover_color = hex_to_rgba(base_color, 1.0)
        
        # First, add the complete shape with all points (including N/A)
        fig.add_trace(go.Scatterpolar(
            r=system_df['Score'].tolist(),
            theta=system_df['Category'].tolist(),
            name=system_name,
            fill='toself',
            line=dict(color=line_color),
            fillcolor=fill_color,
            hoverinfo='skip',  # Disable hover for the shape trace
            showlegend=True
        ))
        
        # Then add separate trace for hover information on non-N/A points
        non_na_df = system_df[system_df['Status'] != 'N/A']
        if not non_na_df.empty:
            fig.add_trace(go.Scatterpolar(
                r=non_na_df['Score'].tolist(),
                theta=non_na_df['Category'].tolist(),
                mode='markers',
                marker=dict(size=1, color='rgba(0,0,0,0)'),  # Nearly invisible markers
                customdata=list(zip(
                    non_na_df['Original Score'],
                    non_na_df['Status'],
                    non_na_df['Completed'],
                    non_na_df['Total']
                )),
                hovertemplate=(
                f"<span style='background-color: {hover_color}; color: white; padding: 10px; display: block'>" +
                "<b>%{theta}</b><br>" +
                f"AI System: {system_name}<br>" +
                "Score: %{customdata[0]}<br>" +
                "Status: %{customdata[1]}<br>" +
                "Evaluations completed: %{customdata[2]}/%{customdata[3]}" +
                "</span>" +
                "<extra></extra>"),
                showlegend=False
            ))
        
        # Finally add N/A markers
        na_df = system_df[system_df['Status'] == 'N/A']
        if not na_df.empty:
            fig.add_trace(go.Scatterpolar(
                r=na_df['Score'].tolist(),
                theta=na_df['Category'].tolist(),
                mode='markers+lines',
                line=dict(color='rgba(128, 128, 128, 0.3)', dash='dot'),
                marker=dict(color='rgba(128, 128, 128, 0.3)', size=8),
                customdata=list(zip(
                    na_df['Original Score'],
                    na_df['Status'],
                    na_df['Completed'],
                    na_df['Total']
                )),
                hovertemplate="<b>%{theta}</b><br>" +
                            f"AI System: {system_name}<br>" +
                            "Status: N/A<br>" +
                            "Evaluations completed: %{customdata[2]}/%{customdata[3]}<br>" +
                            "<extra></extra>",
                showlegend=False
            ))
    
    # Update layout
    fig.update_layout(
        polar=dict(
            radialaxis=dict(
                visible=True,
                range=[0, 100],
                ticksuffix='%',
                showline=True,
                linewidth=1,
                gridwidth=1,
                gridcolor='rgba(0,0,0,0.1)',
                ticktext=[f'{i}%' for i in range(0, 101, 20)],
                tickvals=list(range(0, 101, 20))
            ),
            angularaxis=dict(
                gridcolor='rgba(0,0,0,0.1)',
                linecolor='rgba(0,0,0,0.1)',
            )
        ),
        showlegend=True,
        title=dict(
            text='Category Completion Rates by AI System',
            x=0.5,
            xanchor='center'
        ),
        legend=dict(
            yanchor="top",
            y=1.2,
            xanchor="left",
            x=1.1
        ),
        margin=dict(t=100, b=100, l=100, r=100)
    )
    
    return fig

def update_detailed_scorecard(model, selected_categories):
    if not model:
            return [
                gr.update(value="Please select a model to view details.", visible=True),
                gr.update(visible=False),
                gr.update(visible=False)
            ]

    selected_categories = sort_categories(selected_categories)
    metadata_html = create_metadata_card(models[model]['metadata'])
    overall_summary_html = create_overall_summary(models[model], selected_categories)

    # Combine metadata and overall summary
    combined_header = metadata_html + overall_summary_html

    total_yes = 0
    total_no = 0
    total_na = 0
    has_non_na = False

    # Create category cards
    all_cards_content = "<div class='container'>"
    for category_name in selected_categories:
        if category_name in models[model]['scores']:
            category_data = models[model]['scores'][category_name]
            card_content = f"<div class='card'><div class='card-title'>{category_name}</div>"
            
            # Add category-specific summary at the top of each card
            card_content += create_category_summary(category_data)
            
            # Sort sections within each category
            sorted_sections = sorted(category_data.items(), 
                                  key=lambda x: float(re.match(r'^(\d+\.?\d*)', x[0]).group(1)))
            
            category_yes = 0
            category_no = 0
            category_na = 0
            
            for section, details in sorted_sections:
                status = details['status']
                if status != 'N/A':
                    has_non_na = True
                sources = details.get('sources', [])
                questions = details.get('questions', {})
                
                section_class = "section-na" if status == "N/A" else "section-active"
                status_class = status.lower()
                status_icon = "●" if status == "Yes" else "β—‹" if status == "N/A" else "Γ—"
                
                card_content += f"<div class='section {section_class}'>"
                card_content += f"<div class='section-header'><h3>{section}</h3>"
                card_content += f"<span class='status-badge {status_class}'>{status_icon} {status}</span></div>"
                
                if sources:
                    card_content += "<div class='sources-list'>"
                    for source in sources:
                        icon = source.get("type", "")
                        detail = source.get("detail", "")
                        name = source.get("name", detail)
                        
                        card_content += f"<div class='source-item'>{icon} "
                        if detail.startswith("http"):
                            card_content += f"<a href='{detail}' target='_blank'>{name}</a>"
                        else:
                            card_content += name
                        card_content += "</div>"
                    card_content += "</div>"
                
                if questions:
                    yes_count = sum(1 for v in questions.values() if v)
                    total_count = len(questions)
                    
                    card_content += "<details class='question-accordion'>"
                    if status == "N/A":
                        card_content += f"<summary>View {total_count} N/A items</summary>"
                    else:
                        card_content += f"<summary>View details ({yes_count}/{total_count} completed)</summary>"
                    
                    card_content += "<div class='questions'>"
                    for question, is_checked in questions.items():
                        if status == "N/A":
                            style_class = "na"
                            icon = "β—‹"
                            category_na += 1
                            total_na += 1
                        else:
                            if is_checked:
                                style_class = "checked"
                                icon = "βœ“"
                                category_yes += 1
                                total_yes += 1
                            else:
                                style_class = "unchecked"
                                icon = "βœ—"
                                category_no += 1
                                total_no += 1
                        
                        card_content += f"<div class='question-item {style_class}'>{icon} {question}</div>"
                    card_content += "</div></details>"
                
                card_content += "</div>"
            
            if category_yes + category_no > 0:
                category_score = category_yes / (category_yes + category_no) * 100
                card_content += f"<div class='category-score'>Completion Score Breakdown: {category_score:.2f}% Yes: {category_yes}, No: {category_no}, N/A: {category_na}</div>"
            elif category_na > 0:
                card_content += f"<div class='category-score'>Completion Score Breakdown: N/A (All {category_na} items not applicable)</div>"
            
            card_content += "</div>"
            all_cards_content += card_content

    all_cards_content += "</div>"
    
    # Create total score
    if not has_non_na:
        total_score_md = "<div class='total-score'>No applicable scores (all items N/A)</div>"
    elif total_yes + total_no > 0:
        total_score = total_yes / (total_yes + total_no) * 100
        total_score_md = f"<div class='total-score'>Total Score: {total_score:.2f}% (Yes: {total_yes}, No: {total_no}, N/A: {total_na})</div>"
    else:
        total_score_md = "<div class='total-score'>No applicable scores (all items N/A)</div>"
    
    return [
        gr.update(value=combined_header, visible=True),
        gr.update(value=all_cards_content, visible=True),
        gr.update(value=total_score_md, visible=True)
    ]


first_model = next(iter(models.values()))
category_choices = list(first_model['scores'].keys())

with gr.Blocks(css=css) as demo:
    gr.Markdown("# AI System Social Impact Dashboard")

    initial_df = create_leaderboard(category_choices)
    
    with gr.Row():
        tab_selection = gr.Radio(["Leaderboard", "Category Analysis", "Detailed Scorecard"], 
                               label="Select Tab", value="Leaderboard")
    
    with gr.Row():
        model_chooser = gr.Dropdown(choices=[""] + list(models.keys()),
                                  label="Select AI System for Details", 
                                  value="",
                                  interactive=True, visible=False)
        model_multi_chooser = gr.Dropdown(choices=list(models.keys()),
                                        label="Select AI Systems for Comparison",
                                        value=[],
                                        multiselect=True, 
                                        interactive=True, 
                                        visible=False,
                                        info="Select one or more AI Systems")
    
    # Category filter now visible for all tabs
    category_filter = gr.CheckboxGroup(choices=category_choices,
                                     label="Filter Categories", 
                                     value=category_choices)
    
    with gr.Column(visible=True) as leaderboard_tab:
        leaderboard_output = gr.DataFrame(
            value=initial_df,
            interactive=False,
            wrap=True,
            datatype=["markdown", "markdown", "markdown"] + ["markdown"] * (len(category_choices)+1)  # Support markdown in all columns
        )
    
    with gr.Column(visible=False) as category_analysis_tab:
        # Initialize with empty plot
        initial_plot = create_category_chart([], category_choices)
        category_chart = gr.Plot(value=initial_plot)
    
    with gr.Column(visible=False) as detailed_scorecard_tab:
        model_metadata = gr.HTML()
        all_category_cards = gr.HTML()
        total_score = gr.Markdown()

    def update_dashboard(tab, selected_models, selected_model, selected_categories):
        # Default visibility states
        component_states = {
            "leaderboard": False,
            "category_chart": False,
            "detailed_scorecard": False,
            "model_chooser": False,
            "model_multi_chooser": False
        }
        
        # Initialize outputs with None
        outputs = {
            "leaderboard": None,
            "category_chart": None,
            "model_metadata": None,
            "category_cards": None,
            "total_score": None
        }
        
        # Update visibility based on selected tab
        if tab == "Leaderboard":
            component_states["leaderboard"] = True
            outputs["leaderboard"] = create_leaderboard(selected_categories)
            
        elif tab == "Category Analysis":
            component_states["category_chart"] = True
            component_states["model_multi_chooser"] = True
            if selected_models:  # Only update chart if models are selected
                outputs["category_chart"] = create_category_chart(selected_models, selected_categories)
            
        elif tab == "Detailed Scorecard":
            component_states["detailed_scorecard"] = True
            component_states["model_chooser"] = True
            if selected_model:
                scorecard_updates = update_detailed_scorecard(selected_model, selected_categories)
                outputs["model_metadata"] = scorecard_updates[0]
                outputs["category_cards"] = scorecard_updates[1]
                outputs["total_score"] = scorecard_updates[2]
        
        # Return updates in the correct order
        return [
            gr.update(visible=component_states["leaderboard"]),
            gr.update(visible=component_states["category_chart"]),
            gr.update(visible=component_states["detailed_scorecard"]),
            gr.update(visible=component_states["model_chooser"]),
            gr.update(visible=component_states["model_multi_chooser"]),
            outputs["leaderboard"] if outputs["leaderboard"] is not None else gr.update(),
            outputs["category_chart"] if outputs["category_chart"] is not None else gr.update(),
            outputs["model_metadata"] if outputs["model_metadata"] is not None else gr.update(),
            outputs["category_cards"] if outputs["category_cards"] is not None else gr.update(),
            outputs["total_score"] if outputs["total_score"] is not None else gr.update()
        ]

    # Set up event handlers
    for component in [tab_selection, model_chooser, model_multi_chooser, category_filter]:
        component.change(
            fn=update_dashboard,
            inputs=[tab_selection, model_multi_chooser, model_chooser, category_filter],
            outputs=[leaderboard_tab, category_analysis_tab, detailed_scorecard_tab,
                    model_chooser, model_multi_chooser,
                    leaderboard_output, category_chart, model_metadata,
                    all_category_cards, total_score]
        )

# Launch the app
if __name__ == "__main__":
    demo.launch(ssr_mode=False)