File size: 143,924 Bytes
9b1c753
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d9ca1f77",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Standard Library Imports\n",
    "import ast\n",
    "import json\n",
    "import re\n",
    "import subprocess\n",
    "import sys\n",
    "import warnings\n",
    "from collections import Counter, defaultdict\n",
    "from itertools import combinations\n",
    "from typing import Dict, List, Tuple, Optional\n",
    "\n",
    "# Data Science & Analysis\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "# Machine Learning & Deep Learning\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "from torch.utils.data import Dataset, DataLoader\n",
    "\n",
    "# Transformers & NLP\n",
    "from transformers import BertModel, BertConfig, BertTokenizer\n",
    "\n",
    "# Scikit-learn\n",
    "from sklearn.isotonic import IsotonicRegression\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.metrics import brier_score_loss, log_loss\n",
    "from sklearn.model_selection import StratifiedKFold, train_test_split\n",
    "from sklearn.preprocessing import LabelEncoder\n",
    "\n",
    "# Visualization\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "# Scientific Computing\n",
    "from scipy import stats\n",
    "from scipy.special import softmax\n",
    "from scipy.optimize import minimize_scalar\n",
    "\n",
    "# Set display options\n",
    "pd.set_option('display.max_columns', None)\n",
    "pd.set_option('display.width', None)\n",
    "warnings.filterwarnings('ignore')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ac2dde52",
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv('dataset/CUAD_v1/master_clauses.csv')\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "014db8f8",
   "metadata": {},
   "outputs": [],
   "source": [
    "row = df.iloc[0]\n",
    "for col, val in row.items():\n",
    "    print(f\"{col}: {val}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0147582e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# DETAILED DATASET STRUCTURE ANALYSIS\n",
    "print(\"=== UNDERSTANDING CUAD DATASET FORMAT ===\")\n",
    "print(f\"Dataset shape: {df.shape}\")\n",
    "print(f\"Column names: {df.columns.tolist()}\")\n",
    "\n",
    "print(\"\\n=== EXAMINING FIRST ROW STRUCTURE ===\")\n",
    "first_row = df.iloc[0]\n",
    "print(\"Columns and their types:\")\n",
    "for col in df.columns:\n",
    "    print(f\"  {col}: {type(first_row[col])} - {str(first_row[col])[:100]}...\")\n",
    "\n",
    "print(\"\\n=== UNDERSTANDING THE DATA FORMAT ===\")\n",
    "# Check if this is the JSON format converted to CSV or direct clause data\n",
    "print(\"Sample of non-null values in first few columns:\")\n",
    "for col in df.columns[:5]:\n",
    "    non_null_count = df[col].notna().sum()\n",
    "    print(f\"  {col}: {non_null_count} non-null values out of {len(df)}\")\n",
    "\n",
    "print(\"\\n=== CHECKING FOR CLAUSE TEXT PATTERNS ===\")\n",
    "# Look for text patterns that might indicate clauses\n",
    "text_columns = []\n",
    "for col in df.columns:\n",
    "    if df[col].dtype == 'object':  # String columns\n",
    "        sample_values = df[col].dropna().head(3).tolist()\n",
    "        if any(len(str(val)) > 50 for val in sample_values):  # Likely text content\n",
    "            text_columns.append(col)\n",
    "\n",
    "print(f\"Potential text columns: {text_columns}\")\n",
    "\n",
    "print(\"\\n=== SAMPLE DATA FROM KEY COLUMNS ===\")\n",
    "for col in text_columns[:3]:  # Show first 3 text columns\n",
    "    print(f\"Column '{col}':\")\n",
    "    sample_text = df[col].dropna().iloc[0] if not df[col].dropna().empty else \"No data\"\n",
    "    print(f\"Sample: {str(sample_text)[:200]}...\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "26ef3eed",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Convert CUAD's contract-based format to clause-based format for analysis\n",
    "print(\"=== CONVERTING CUAD FORMAT TO CLAUSE-BASED ANALYSIS ===\")\n",
    "\n",
    "# Extract clause data from CUAD format\n",
    "clause_data = []\n",
    "\n",
    "# Get all category columns (excluding 'Filename' and 'Answer' columns)\n",
    "category_columns = [col for col in df.columns if col != 'Filename' and not col.endswith('-Answer')]\n",
    "\n",
    "print(f\"Found {len(category_columns)} legal categories in CUAD:\")\n",
    "for i, category in enumerate(category_columns[:10], 1):\n",
    "    print(f\"{i:2d}. {category}\")\n",
    "if len(category_columns) > 10:\n",
    "    print(\"...\")\n",
    "    print(f\"{len(category_columns)}. {category_columns[-1]}\")\n",
    "\n",
    "# Process each contract and extract clauses\n",
    "for idx, row in df.iterrows():\n",
    "    filename = row['Filename']\n",
    "    \n",
    "    for category in category_columns:\n",
    "        answer_col = category + '-Answer'\n",
    "        \n",
    "        if answer_col in df.columns:\n",
    "            clause_text = row[answer_col]\n",
    "            \n",
    "            # Only process non-empty clauses\n",
    "            if pd.notna(clause_text) and clause_text and clause_text.strip():\n",
    "                # Handle list format in answers (some clauses are stored as lists)\n",
    "                if isinstance(clause_text, str) and clause_text.startswith('[') and clause_text.endswith(']'):\n",
    "                    # Parse list format\n",
    "                    try:\n",
    "                        import ast\n",
    "                        clause_list = ast.literal_eval(clause_text)\n",
    "                        if isinstance(clause_list, list):\n",
    "                            for clause in clause_list:\n",
    "                                if clause and clause.strip():\n",
    "                                    clause_data.append({\n",
    "                                        'Filename': filename,\n",
    "                                        'Category': category,\n",
    "                                        'Text': clause.strip(),\n",
    "                                        'Source': 'CUAD'\n",
    "                                    })\n",
    "                    except:\n",
    "                        # If parsing fails, treat as regular text\n",
    "                        clause_data.append({\n",
    "                            'Filename': filename,\n",
    "                            'Category': category,\n",
    "                            'Text': clause_text.strip(),\n",
    "                            'Source': 'CUAD'\n",
    "                        })\n",
    "                else:\n",
    "                    # Regular text clause\n",
    "                    clause_data.append({\n",
    "                        'Filename': filename,\n",
    "                        'Category': category,\n",
    "                        'Text': clause_text.strip(),\n",
    "                        'Source': 'CUAD'\n",
    "                    })\n",
    "\n",
    "# Create DataFrame from extracted clauses\n",
    "clause_df = pd.DataFrame(clause_data)\n",
    "\n",
    "print(f\"\\n=== CLAUSE EXTRACTION RESULTS ===\")\n",
    "print(f\"Total contracts processed: {len(df)}\")\n",
    "print(f\"Total clauses extracted: {len(clause_df)}\")\n",
    "print(f\"Categories with clauses: {clause_df['Category'].nunique()}\")\n",
    "\n",
    "# Show distribution of clauses per category\n",
    "print(f\"\\n=== TOP 10 CATEGORIES BY CLAUSE COUNT ===\")\n",
    "category_counts = clause_df['Category'].value_counts()\n",
    "for category, count in category_counts.head(10).items():\n",
    "    print(f\"{category}: {count} clauses\")\n",
    "\n",
    "# Update our working dataframe\n",
    "df_clauses = clause_df.copy()\n",
    "\n",
    "print(f\"Data preparation complete!\")\n",
    "print(f\"Working with {len(df_clauses)} clauses from {len(category_columns)} legal categories\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "83d263ad",
   "metadata": {},
   "source": [
    "# Contract Risk Analysis Pipeline - 3 Month Implementation Plan\n",
    "\n",
    "## Project Overview\n",
    "Building an automated contract risk analysis system using LLMs with calibrated risk scoring, following the modernized risk-o-meter framework.\n",
    "\n",
    "### 3-Month Timeline:\n",
    "- **Month 1**: Data exploration, risk taxonomy, baseline implementation\n",
    "- **Month 2**: Model development, fine-tuning, risk classification\n",
    "- **Month 3**: Calibration, evaluation, deployment pipeline\n",
    "\n",
    "### Key Components:\n",
    "1. **Risk Taxonomy Development** - Map CUAD categories to risk types\n",
    "2. **Clause Extraction** - Legal-BERT fine-tuning  \n",
    "3. **Risk Classification** - Multi-task learning for risk categories\n",
    "4. **Risk Scoring** - Calibrated confidence with uncertainty quantification\n",
    "5. **Evaluation Framework** - Comprehensive metrics and comparison\n",
    "\n",
    "Let's start with comprehensive data exploration..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "762b3c1e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Dataset Structure Analysis\n",
    "print(\"=== CUAD Dataset Overview ===\")\n",
    "print(f\"Dataset shape: {df.shape}\")\n",
    "print(f\"Number of contracts: {len(df)}\")\n",
    "print(f\"Number of categories: {(len(df.columns) - 1) // 2}\")  # Excluding filename column, each category has context + answer\n",
    "\n",
    "# Get column names\n",
    "columns = df.columns.tolist()\n",
    "print(f\"\\nTotal columns: {len(columns)}\")\n",
    "print(f\"First few columns: {columns[:10]}\")\n",
    "\n",
    "# Identify category pattern (context + answer pairs)\n",
    "categories = []\n",
    "for col in columns[1:]:  # Skip filename column\n",
    "    if not col.endswith('-Answer'):\n",
    "        category_name = col\n",
    "        categories.append(category_name)\n",
    "\n",
    "print(f\"\\nIdentified {len(categories)} categories:\")\n",
    "for i, cat in enumerate(categories[:10], 1):\n",
    "    print(f\"{i:2d}. {cat}\")\n",
    "print(\"...\")\n",
    "print(f\"{len(categories)}. {categories[-1]}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "187281de",
   "metadata": {},
   "source": [
    "## Step 1: Risk Taxonomy Development\n",
    "\n",
    "Create enhanced risk taxonomy mapping CUAD categories to business risk types"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a45f0dfe",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Build comprehensive risk taxonomy for contract analysis\n",
    "# Map CUAD categories to business-relevant risk types\n",
    "\n",
    "RISK_TAXONOMY = {\n",
    "    'LIABILITY_RISK': {\n",
    "        'categories': ['Liability Cap', 'Liquidated Damages', 'Uncapped Liability', 'Cap On Liability'],\n",
    "        'description': 'Financial liability and damage exposure risks',\n",
    "        'severity_factors': ['liability_amount', 'uncapped_exposure', 'liquidated_damages']\n",
    "    },\n",
    "    \n",
    "    'INDEMNITY_RISK': {\n",
    "        'categories': ['Indemnification'],\n",
    "        'description': 'Indemnification obligations and responsibilities',\n",
    "        'severity_factors': ['indemnity_scope', 'third_party_claims', 'defense_obligations']\n",
    "    },\n",
    "    \n",
    "    'TERMINATION_RISK': {\n",
    "        'categories': ['Termination For Convenience', 'Renewal Term', 'Post-Termination Services'],\n",
    "        'description': 'Contract termination conditions and consequences',\n",
    "        'severity_factors': ['termination_ease', 'notice_period', 'termination_penalties']\n",
    "    },\n",
    "    \n",
    "    'CONFIDENTIALITY_RISK': {\n",
    "        'categories': ['Confidentiality', 'Non-Compete'],\n",
    "        'description': 'Information security and competitive restrictions',\n",
    "        'severity_factors': ['confidentiality_scope', 'information_sensitivity', 'restriction_duration']\n",
    "    },\n",
    "    \n",
    "    'OPERATIONAL_RISK': {\n",
    "        'categories': ['Most Favored Nation', 'Volume Restriction', 'Exclusivity', 'Minimum Commitment'],\n",
    "        'description': 'Business operations and performance requirements',\n",
    "        'severity_factors': ['exclusivity_scope', 'performance_requirements', 'operational_constraints']\n",
    "    },\n",
    "    \n",
    "    'IP_RISK': {\n",
    "        'categories': ['License Grant', 'Intellectual Property Ownership', 'Joint IP Ownership'],\n",
    "        'description': 'Intellectual property rights and licensing risks',\n",
    "        'severity_factors': ['ip_scope', 'ownership_clarity', 'licensing_restrictions']\n",
    "    },\n",
    "    \n",
    "    'COMPLIANCE_RISK': {\n",
    "        'categories': ['Governing Law', 'Anti-Assignment', 'Change Of Control'],\n",
    "        'description': 'Legal compliance and regulatory requirements',\n",
    "        'severity_factors': ['regulatory_complexity', 'compliance_burden', 'legal_jurisdiction']\n",
    "    }\n",
    "}\n",
    "\n",
    "# Create category mapping\n",
    "category_to_risk_type = {}\n",
    "for risk_type, details in RISK_TAXONOMY.items():\n",
    "    for category in details['categories']:\n",
    "        category_to_risk_type[category] = risk_type\n",
    "\n",
    "print(\"=== ENHANCED RISK TAXONOMY ===\")\n",
    "print(f\"Total risk types: {len(RISK_TAXONOMY)}\")\n",
    "print(f\"Mapped categories: {len(category_to_risk_type)}\")\n",
    "\n",
    "for risk_type, details in RISK_TAXONOMY.items():\n",
    "    print(f\"\\n{risk_type}:\")\n",
    "    print(f\"  Description: {details['description']}\")\n",
    "    print(f\"  Categories ({len(details['categories'])}): {', '.join(details['categories'])}\")\n",
    "    print(f\"  Severity factors: {', '.join(details['severity_factors'])}\")\n",
    "\n",
    "# Analyze coverage of CUAD categories\n",
    "mapped_categories = set(category_to_risk_type.keys())\n",
    "all_categories = set(categories)\n",
    "unmapped_categories = all_categories - mapped_categories\n",
    "\n",
    "coverage_percentage = (len(mapped_categories) / len(all_categories)) * 100\n",
    "\n",
    "print(f\"\\n=== COVERAGE ANALYSIS ===\")\n",
    "print(f\"Total CUAD categories: {len(all_categories)}\")\n",
    "print(f\"Mapped to risk types: {len(mapped_categories)} ({coverage_percentage:.1f}%)\")\n",
    "print(f\"Unmapped categories: {len(unmapped_categories)}\")\n",
    "\n",
    "if unmapped_categories:\n",
    "    print(f\"\\nUnmapped categories: {sorted(unmapped_categories)}\")\n",
    "\n",
    "# Analyze risk distribution in our dataset\n",
    "print(f\"\\n=== RISK DISTRIBUTION IN DATASET ===\")\n",
    "risk_distribution = {}\n",
    "clause_risk_mapping = {}\n",
    "\n",
    "for _, clause in df_clauses.iterrows():\n",
    "    category = clause['Category']\n",
    "    if category in category_to_risk_type:\n",
    "        risk_type = category_to_risk_type[category]\n",
    "        risk_distribution[risk_type] = risk_distribution.get(risk_type, 0) + 1\n",
    "        clause_risk_mapping[clause.name] = risk_type\n",
    "\n",
    "# Create visualization of risk distribution\n",
    "fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 12))\n",
    "fig.suptitle('Contract Risk Analysis - Risk Type Distribution', fontsize=16, fontweight='bold')\n",
    "\n",
    "# Overall risk distribution pie chart\n",
    "risk_types = list(risk_distribution.keys())\n",
    "risk_counts = list(risk_distribution.values())\n",
    "\n",
    "ax1.pie(risk_counts, labels=[rt.replace('_', ' ').title() for rt in risk_types], \n",
    "        autopct='%1.1f%%', startangle=90)\n",
    "ax1.set_title('Overall Risk Type Distribution', fontsize=12, fontweight='bold')\n",
    "\n",
    "# Risk type frequency bar chart\n",
    "ax2.bar(range(len(risk_types)), risk_counts, color='skyblue')\n",
    "ax2.set_xlabel('Risk Types')\n",
    "ax2.set_ylabel('Number of Clauses')\n",
    "ax2.set_title('Risk Type Frequency', fontsize=12, fontweight='bold')\n",
    "ax2.set_xticks(range(len(risk_types)))\n",
    "ax2.set_xticklabels([rt.replace('_', ' ').title() for rt in risk_types], rotation=45, ha='right')\n",
    "\n",
    "# Individual risk type breakdowns\n",
    "for i, (risk_type, details) in enumerate(RISK_TAXONOMY.items()):\n",
    "    if i < 2:  # Only show first 2 detailed breakdowns\n",
    "        ax = ax3 if i == 0 else ax4\n",
    "        \n",
    "        # Get category counts for this risk type\n",
    "        category_counts = []\n",
    "        for category in details['categories']:\n",
    "            if category in df_clauses['Category'].values:\n",
    "                count = len(df_clauses[df_clauses['Category'] == category])\n",
    "                category_counts.append(count)\n",
    "            else:\n",
    "                category_counts.append(0)\n",
    "        \n",
    "        if sum(category_counts) > 0:\n",
    "            ax = ax3 if i == 0 else ax4\n",
    "        else:\n",
    "            continue\n",
    "        ax.pie(category_counts, labels=details['categories'], autopct='%1.1f%%', startangle=90)\n",
    "        ax.set_title(f'{risk_type.replace(\"_\", \" \").title()}', fontsize=12)\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()\n",
    "\n",
    "print(\"\\n=== RISK DISTRIBUTION ANALYSIS ===\")\n",
    "print(f\"Total risk types: {len(risk_distribution)}\")\n",
    "for risk_type, count in sorted(risk_distribution.items(), key=lambda x: x[1], reverse=True):\n",
    "    percentage = (count / len(df_clauses)) * 100\n",
    "    print(f\"{risk_type}: {count} clauses ({percentage:.1f}%)\")\n",
    "\n",
    "# Analyze co-occurrence of risks within contracts\n",
    "risk_cooccurrence = {}\n",
    "for filename in df_clauses['Filename'].unique():\n",
    "    contract_clauses = df_clauses[df_clauses['Filename'] == filename]\n",
    "    risks_in_contract = set()\n",
    "    \n",
    "    for _, clause in contract_clauses.iterrows():\n",
    "        if clause['Category'] in category_to_risk_type:\n",
    "            risks_in_contract.add(category_to_risk_type[clause['Category']])\n",
    "    \n",
    "    # Count co-occurrence\n",
    "    risks = list(risks_in_contract)\n",
    "    for i in range(len(risks)):\n",
    "        for j in range(i+1, len(risks)):\n",
    "            pair = tuple(sorted([risks[i], risks[j]]))\n",
    "            risk_cooccurrence[pair] = risk_cooccurrence.get(pair, 0) + 1\n",
    "\n",
    "print(\"\\n=== RISK CO-OCCURRENCE ANALYSIS ===\")\n",
    "print(\"Top 10 risk pairs that appear together in contracts:\")\n",
    "for pair, count in sorted(risk_cooccurrence.items(), key=lambda x: x[1], reverse=True)[:10]:\n",
    "    percentage = (count / len(df_clauses['Filename'].unique())) * 100\n",
    "    print(f\"{pair[0]} & {pair[1]}: {count} contracts ({percentage:.1f}%)\")\n",
    "\n",
    "print(f\"Risk Taxonomy Analysis Complete!\")\n",
    "print(f\"Ready for baseline risk scoring implementation...\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d723c3ab",
   "metadata": {},
   "source": [
    "## Step 2: Clause Distribution Analysis\n",
    "\n",
    "Analyze how clauses are distributed across risk categories"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "17fc56d8",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "plt.style.use('seaborn-v0_8')\n",
    "\n",
    "# Analyze distribution of clauses per risk type\n",
    "risk_distribution = {}\n",
    "for category in df_clauses['Category'].unique():\n",
    "    if category in category_to_risk_type:\n",
    "        risk_type = category_to_risk_type[category]\n",
    "        if risk_type not in risk_distribution:\n",
    "            risk_distribution[risk_type] = 0\n",
    "        risk_distribution[risk_type] += df_clauses[df_clauses['Category'] == category].shape[0]\n",
    "\n",
    "# Create visualizations\n",
    "fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 12))\n",
    "\n",
    "# 1. Risk type distribution\n",
    "risk_types = list(risk_distribution.keys())\n",
    "risk_counts = list(risk_distribution.values())\n",
    "\n",
    "ax1.bar(range(len(risk_types)), risk_counts, color='skyblue')\n",
    "ax1.set_title('Clause Distribution Across Risk Types', fontsize=14, fontweight='bold')\n",
    "ax1.set_xlabel('Risk Type')\n",
    "ax1.set_ylabel('Number of Clauses')\n",
    "ax1.set_xticks(range(len(risk_types)))\n",
    "ax1.set_xticklabels([rt.replace('_', ' ').title() for rt in risk_types], rotation=45, ha='right')\n",
    "\n",
    "# 2. Category distribution within each risk type\n",
    "for i, (risk_type, details) in enumerate(RISK_TAXONOMY.items()):\n",
    "    category_counts = []\n",
    "    for category in details['categories']:\n",
    "        if category in df_clauses['Category'].values:\n",
    "            count = df_clauses[df_clauses['Category'] == category].shape[0]\n",
    "            category_counts.append(count)\n",
    "        else:\n",
    "            category_counts.append(0)\n",
    "    \n",
    "    if i < 4:  # Show first 4 risk types\n",
    "        ax = ax2 if i < 2 else ax3 if i == 2 else ax4\n",
    "        if i == 0:\n",
    "            ax = ax2\n",
    "        elif i == 1:\n",
    "            ax = ax3\n",
    "        elif i == 2:\n",
    "            ax = ax4\n",
    "        else:\n",
    "            continue\n",
    "            \n",
    "        ax.pie(category_counts, labels=details['categories'], autopct='%1.1f%%', startangle=90)\n",
    "        ax.set_title(f'{risk_type.replace(\"_\", \" \").title()}', fontsize=12)\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()\n",
    "\n",
    "print(\"\\n=== RISK DISTRIBUTION ANALYSIS ===\")\n",
    "print(f\"Total risk types: {len(risk_distribution)}\")\n",
    "for risk_type, count in sorted(risk_distribution.items(), key=lambda x: x[1], reverse=True):\n",
    "    percentage = (count / len(df_clauses)) * 100\n",
    "    print(f\"{risk_type}: {count} clauses ({percentage:.1f}%)\")\n",
    "\n",
    "# Analyze co-occurrence of risks within contracts\n",
    "risk_cooccurrence = {}\n",
    "for filename in df_clauses['Filename'].unique():\n",
    "    contract_clauses = df_clauses[df_clauses['Filename'] == filename]\n",
    "    risks_in_contract = set()\n",
    "    \n",
    "    for _, clause in contract_clauses.iterrows():\n",
    "        if clause['Category'] in category_to_risk_type:\n",
    "            risks_in_contract.add(category_to_risk_type[clause['Category']])\n",
    "    \n",
    "    # Count co-occurrence\n",
    "    risks = list(risks_in_contract)\n",
    "    for i in range(len(risks)):\n",
    "        for j in range(i+1, len(risks)):\n",
    "            pair = tuple(sorted([risks[i], risks[j]]))\n",
    "            risk_cooccurrence[pair] = risk_cooccurrence.get(pair, 0) + 1\n",
    "\n",
    "print(\"\\n=== RISK CO-OCCURRENCE ANALYSIS ===\")\n",
    "print(\"Top 10 risk pairs that appear together in contracts:\")\n",
    "for pair, count in sorted(risk_cooccurrence.items(), key=lambda x: x[1], reverse=True)[:10]:\n",
    "    percentage = (count / len(df_clauses['Filename'].unique())) * 100\n",
    "    print(f\"{pair[0]} & {pair[1]}: {count} contracts ({percentage:.1f}%)\")\n",
    "\n",
    "print(f\"Risk Taxonomy Analysis Complete!\")\n",
    "print(f\"Ready for baseline risk scoring implementation...\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4d4795d3",
   "metadata": {},
   "source": [
    "# ๐Ÿš€ 9-WEEK IMPLEMENTATION ROADMAP\n",
    "*Updated Progress Status as of Implementation*\n",
    "\n",
    "## ๐Ÿ“… **WEEKS 1-3: Foundation & Data Pipeline** \n",
    "\n",
    "### **Week 1: Dataset Deep Dive & Risk Taxonomy Enhancement**\n",
    "- **โœ… COMPLETED**: CUAD dataset exploration and structure analysis  \n",
    "- **โœ… COMPLETED**: Risk taxonomy development (7 risk categories)\n",
    "- **โœ… COMPLETED**: Enhanced risk taxonomy mapping (95.2% coverage, 40/42 categories)\n",
    "- **โœ… COMPLETED**: Baseline keyword-based risk scoring (all 7 categories)\n",
    "- **โœ… COMPLETED**: Contract complexity analysis and risk pattern identification\n",
    "- **โœ… COMPLETED**: High-risk contract identification and co-occurrence analysis\n",
    "\n",
    "### **Week 2: Data Pipeline & Advanced Preprocessing**\n",
    "- **โœ… COMPLETED**: Advanced contract data pipeline with Legal-BERT preparation\n",
    "- **โœ… COMPLETED**: Legal entity extraction and clause complexity scoring\n",
    "- **โœ… COMPLETED**: Text cleaning and normalization for BERT input\n",
    "- **โœ… COMPLETED**: Stratified cross-validation strategy (contract-level splits)\n",
    "- **โœ… COMPLETED**: Multi-task dataset preparation (classification + regression)\n",
    "\n",
    "### **Week 3: Legal-BERT Architecture & Training Setup**\n",
    "- **โœ… COMPLETED**: Legal-BERT multi-task architecture design\n",
    "- **โœ… COMPLETED**: Model configuration and training infrastructure\n",
    "- **โœ… COMPLETED**: Custom dataset classes and data loaders\n",
    "- **โœ… COMPLETED**: Multi-task loss functions (classification + severity + importance)\n",
    "- **โœ… COMPLETED**: Calibration framework implementation (5 methods)\n",
    "\n",
    "---\n",
    "\n",
    "## ๐Ÿง  **WEEKS 4-6: Model Development & Training**\n",
    "\n",
    "### **Week 4-5: Legal-BERT Implementation & Training**\n",
    "- **๐Ÿ“‹ TODO**: Execute actual model training on CUAD dataset\n",
    "- **๐Ÿ“‹ TODO**: Hyperparameter optimization and validation\n",
    "- **๐Ÿ“‹ TODO**: Model performance evaluation and metrics analysis\n",
    "- **๐Ÿ“‹ TODO**: Attention mechanism analysis for clause importance\n",
    "- **๐Ÿ“‹ TODO**: Transfer learning experiments from legal domain models\n",
    "\n",
    "### **Week 6: Advanced Model Features & Optimization**\n",
    "- **๐Ÿ“‹ TODO**: Hierarchical risk modeling (clause โ†’ contract level aggregation)\n",
    "- **๐Ÿ“‹ TODO**: Risk dependency modeling and interaction analysis\n",
    "- **๐Ÿ“‹ TODO**: Model ensemble strategies for improved robustness\n",
    "- **๐Ÿ“‹ TODO**: Cross-contract risk correlation analysis\n",
    "\n",
    "---\n",
    "\n",
    "## ๐ŸŽฏ **WEEKS 7-9: Calibration, Evaluation & Finalization**\n",
    "\n",
    "### **Week 7: Model Calibration & Uncertainty Quantification**\n",
    "- **โœ… FRAMEWORK READY**: Temperature scaling, Platt scaling, Isotonic regression\n",
    "- **โœ… FRAMEWORK READY**: Monte Carlo dropout uncertainty estimation\n",
    "- **โœ… FRAMEWORK READY**: Ensemble calibration methods\n",
    "- **๐Ÿ“‹ TODO**: Apply calibration to trained Legal-BERT model\n",
    "- **๐Ÿ“‹ TODO**: Evaluate calibration quality (ECE, MCE, Brier Score)\n",
    "\n",
    "### **Week 8: Comprehensive Evaluation & Analysis**\n",
    "- **๐Ÿ“‹ TODO**: Baseline vs Legal-BERT performance comparison\n",
    "- **๐Ÿ“‹ TODO**: Error analysis and failure case identification\n",
    "- **๐Ÿ“‹ TODO**: Risk score interpretation and explainability features\n",
    "- **๐Ÿ“‹ TODO**: Statistical significance testing of improvements\n",
    "\n",
    "### **Week 9: Documentation & Deployment**\n",
    "- **๐Ÿ“‹ TODO**: Implementation report and technical documentation\n",
    "- **๐Ÿ“‹ TODO**: Performance analysis and result visualization\n",
    "- **๐Ÿ“‹ TODO**: Deployment pipeline and inference optimization\n",
    "- **๐Ÿ“‹ TODO**: Future enhancement recommendations\n",
    "\n",
    "---\n",
    "\n",
    "## ๐Ÿ—๏ธ **CURRENT IMPLEMENTATION STATUS**\n",
    "\n",
    "### **โœ… Infrastructure Complete (100%)**\n",
    "```\n",
    "๐Ÿ“Š Data Pipeline โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” 100%\n",
    "๐Ÿง  Model Architecture โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” 100%  \n",
    "โš–๏ธ Calibration Framework โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” 100%\n",
    "๐Ÿ”„ Cross-Validation โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” 100%\n",
    "```\n",
    "\n",
    "### **๐Ÿ”„ In Progress**\n",
    "```\n",
    "๐Ÿ‹๏ธ Model Training โ”โ”โ”โ”โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘ 40%\n",
    "๐Ÿ“ˆ Evaluation Pipeline โ”โ”โ”โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘ 30%\n",
    "๐Ÿ“ Documentation โ”โ”โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘โ–‘ 20%\n",
    "```\n",
    "\n",
    "### **๐Ÿ“‹ Next Priority Tasks**\n",
    "1. **Execute Legal-BERT training** on processed CUAD dataset\n",
    "2. **Validate model performance** across all risk categories  \n",
    "3. **Apply calibration methods** to improve confidence estimation\n",
    "4. **Comprehensive evaluation** against baseline methods\n",
    "\n",
    "---\n",
    "\n",
    "## ๐Ÿ“Š **CURRENT ACHIEVEMENTS** \n",
    "\n",
    "### **Data & Preprocessing**\n",
    "- **19,598 clauses** from 510 contracts processed\n",
    "- **95.2% category coverage** (40/42 CUAD categories mapped)\n",
    "- **7 risk types** with enhanced taxonomy\n",
    "- **Contract-level data splits** preventing leakage\n",
    "- **Multi-task labels** for classification and regression\n",
    "\n",
    "### **Model Architecture**\n",
    "- **Legal-BERT multi-task** design complete\n",
    "- **3 prediction heads**: risk classification, severity, importance\n",
    "- **Calibration-ready** architecture with uncertainty quantification\n",
    "- **Attention analysis** capabilities for interpretability\n",
    "\n",
    "### **Calibration Framework**\n",
    "- **5 calibration methods** implemented and tested\n",
    "- **ECE/MCE evaluation** metrics ready\n",
    "- **Legal-specific considerations** for high-stakes decisions\n",
    "- **Regression calibration** for severity/importance scores\n",
    "\n",
    "---\n",
    "\n",
    "## ๐ŸŽฏ **SUCCESS METRICS TRACKING**\n",
    "\n",
    "### **Current Achievements โœ…**\n",
    "- **Data Coverage**: 95.2% (target: >80%) โœ…\n",
    "- **Risk Taxonomy**: 7 comprehensive categories โœ…  \n",
    "- **Architecture**: Multi-task Legal-BERT ready โœ…\n",
    "- **Calibration**: Framework implemented โœ…\n",
    "\n",
    "### **Next Milestones ๐ŸŽฏ**\n",
    "- **Model Accuracy**: Target >75% on risk classification\n",
    "- **Calibration Quality**: ECE <0.08, Brier Score <0.20\n",
    "- **F1-Score**: >0.70 weighted average across risk types\n",
    "- **Training Time**: <4 hours for full fine-tuning\n",
    "\n",
    "---\n",
    "\n",
    "## ๐Ÿ’ก **IMMEDIATE NEXT ACTIONS**\n",
    "\n",
    "### **Week 4 Priority Tasks**\n",
    "1. **๐Ÿ‹๏ธ Start Legal-BERT Training**: Execute training pipeline on full dataset\n",
    "2. **๐Ÿ“Š Monitor Training**: Track loss curves and validation metrics\n",
    "3. **๐Ÿ”ง Hyperparameter Tuning**: Optimize learning rate, batch size, epochs\n",
    "4. **๐Ÿ“ˆ Baseline Comparison**: Evaluate against enhanced keyword scorer\n",
    "\n",
    "### **Implementation Notes**\n",
    "- **Environment**: All dependencies consolidated and ready\n",
    "- **Data**: Preprocessed and split for training\n",
    "- **Code**: Clean, documented, and modular structure\n",
    "- **Framework**: Calibration and evaluation systems in place\n",
    "\n",
    "**๐Ÿš€ Ready to execute model training and move to Week 4-6 implementation phase!**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "56ee82a4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# IMMEDIATE NEXT STEPS: Package Installation & Environment Setup\n",
    "# Run this cell to install required packages for Legal-BERT and advanced analytics\n",
    "\n",
    "def install_package(package):\n",
    "    \"\"\"Install package using pip\"\"\"\n",
    "    try:\n",
    "        subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", package])\n",
    "        print(f\"Successfully installed {package}\")\n",
    "    except subprocess.CalledProcessError as e:\n",
    "        print(f\"Failed to install {package}: {e}\")\n",
    "\n",
    "# Essential packages for Legal-BERT and contract analysis\n",
    "REQUIRED_PACKAGES = [\n",
    "    \"transformers==4.35.0\",\n",
    "    \"torch>=1.13.0\",\n",
    "    \"scikit-learn>=1.3.0\",\n",
    "    \"matplotlib>=3.6.0\",\n",
    "    \"seaborn>=0.12.0\",\n",
    "    \"plotly>=5.17.0\",\n",
    "    \"spacy>=3.7.0\",\n",
    "    \"nltk>=3.8.0\",\n",
    "    \"datasets>=2.14.0\",\n",
    "    \"accelerate>=0.24.0\",\n",
    "    \"tensorboard>=2.14.0\",\n",
    "    \"wandb>=0.15.0\",\n",
    "    \"calibration-library\",\n",
    "    \"shap>=0.42.0\",\n",
    "    \"lime>=0.2.0\"\n",
    "]\n",
    "\n",
    "print(\"=== INSTALLING REQUIRED PACKAGES ===\")\n",
    "print(\"This may take a few minutes...\")\n",
    "\n",
    "for package in REQUIRED_PACKAGES:\n",
    "    install_package(package)\n",
    "\n",
    "print(\"\\n=== DOWNLOAD SPACY MODEL ===\")\n",
    "try:\n",
    "    subprocess.check_call([sys.executable, \"-m\", \"spacy\", \"download\", \"en_core_web_sm\"])\n",
    "    print(\"Successfully downloaded spaCy English model\")\n",
    "except:\n",
    "    print(\"spaCy model download failed - will install later\")\n",
    "\n",
    "print(\"\\n=== ENVIRONMENT SETUP COMPLETE ===\")\n",
    "print(\"Ready to start Legal-BERT implementation!\")\n",
    "\n",
    "# Next development priorities\n",
    "IMMEDIATE_TASKS = {\n",
    "    \"HIGH_PRIORITY\": [\n",
    "        \"Run clause distribution analysis (execute cell above)\",\n",
    "        \"Test baseline risk scorer on more contract samples\",\n",
    "        \"Implement Legal-BERT tokenization pipeline\",\n",
    "        \"Create train/validation/test data splits\"\n",
    "    ],\n",
    "    \n",
    "    \"MEDIUM_PRIORITY\": [\n",
    "        \"Develop contract-level risk aggregation\",\n",
    "        \"Implement attention visualization for clause importance\",\n",
    "        \"Create risk score calibration validation\",\n",
    "        \"Build evaluation pipeline with expert annotations\"\n",
    "    ],\n",
    "    \n",
    "    \"RESEARCH_FOCUS\": [\n",
    "        \"Multi-task learning architecture design\",\n",
    "        \"Uncertainty quantification implementation\",\n",
    "        \"Temporal risk pattern analysis\",\n",
    "        \"Cross-contract risk correlation modeling\"\n",
    "    ]\n",
    "}\n",
    "\n",
    "print(\"\\n=== IMMEDIATE DEVELOPMENT PRIORITIES ===\")\n",
    "for priority, tasks in IMMEDIATE_TASKS.items():\n",
    "    print(f\"\\n{priority}:\")\n",
    "    for i, task in enumerate(tasks, 1):\n",
    "        print(f\"  {i}. {task}\")\n",
    "\n",
    "print(\"\\n\" + \"=\"*60)\n",
    "print(\"READY TO START 3-MONTH IMPLEMENTATION!\")\n",
    "print(\"Next: Execute the cells above to run analysis pipeline\")\n",
    "print(\"=\"*60)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b8bb09d7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# TASK 1: COMPLETE CUAD DATASET DEEP ANALYSIS\n",
    "# Analyze contract complexity patterns and unmapped categories\n",
    "\n",
    "print(\"=== WEEK 1 TASK 1: COMPREHENSIVE DATASET ANALYSIS ===\")\n",
    "\n",
    "# 1. Analyze unmapped categories and their potential risk mappings\n",
    "unmapped_categories = [cat for cat in category_columns if cat not in category_to_risk_type]\n",
    "print(f\"\\n=== UNMAPPED CATEGORIES ANALYSIS ===\")\n",
    "print(f\"Total unmapped: {len(unmapped_categories)}\")\n",
    "\n",
    "for category in unmapped_categories:\n",
    "    if category in df_clauses['Category'].values:\n",
    "        count = df_clauses[df_clauses['Category'] == category].shape[0]\n",
    "        print(f\"{category}: {count} clauses\")\n",
    "\n",
    "# 2. Contract complexity analysis\n",
    "print(f\"\\n=== CONTRACT COMPLEXITY ANALYSIS ===\")\n",
    "\n",
    "# Calculate clauses per contract\n",
    "contract_stats = df_clauses.groupby('Filename').agg({\n",
    "    'Category': 'count',\n",
    "    'Text': lambda x: sum(len(text.split()) for text in x)  # Total words\n",
    "}).rename(columns={'Category': 'num_clauses', 'Text': 'total_words'})\n",
    "\n",
    "contract_stats['avg_words_per_clause'] = contract_stats['total_words'] / contract_stats['num_clauses']\n",
    "\n",
    "print(f\"Contract complexity statistics:\")\n",
    "print(f\"Average clauses per contract: {contract_stats['num_clauses'].mean():.1f}\")\n",
    "print(f\"Average words per contract: {contract_stats['total_words'].mean():.1f}\")\n",
    "print(f\"Average words per clause: {contract_stats['avg_words_per_clause'].mean():.1f}\")\n",
    "\n",
    "# 3. Risk category co-occurrence analysis\n",
    "print(f\"\\n=== RISK CATEGORY CO-OCCURRENCE ANALYSIS ===\")\n",
    "\n",
    "# Create contract-risk matrix\n",
    "contract_risk_matrix = {}\n",
    "for filename in df_clauses['Filename'].unique():\n",
    "    contract_clauses = df_clauses[df_clauses['Filename'] == filename]\n",
    "    risk_types_in_contract = set()\n",
    "    \n",
    "    for _, clause in contract_clauses.iterrows():\n",
    "        if clause['Category'] in category_to_risk_type:\n",
    "            risk_types_in_contract.add(category_to_risk_type[clause['Category']])\n",
    "    \n",
    "    contract_risk_matrix[filename] = list(risk_types_in_contract)\n",
    "\n",
    "# Calculate risk co-occurrence\n",
    "risk_cooccurrence = {}\n",
    "all_risk_types = list(RISK_TAXONOMY.keys())\n",
    "\n",
    "for r1, r2 in combinations(all_risk_types, 2):\n",
    "    cooccur_count = 0\n",
    "    for risks in contract_risk_matrix.values():\n",
    "        if r1 in risks and r2 in risks:\n",
    "            cooccur_count += 1\n",
    "    risk_cooccurrence[(r1, r2)] = cooccur_count\n",
    "\n",
    "print(\"Risk type co-occurrence in contracts:\")\n",
    "for (r1, r2), count in sorted(risk_cooccurrence.items(), key=lambda x: x[1], reverse=True):\n",
    "    percentage = (count / len(contract_risk_matrix)) * 100\n",
    "    print(f\"  {r1.replace('_', ' ')} + {r2.replace('_', ' ')}: {count} contracts ({percentage:.1f}%)\")\n",
    "\n",
    "# 4. High-risk contract identification\n",
    "print(f\"\\n=== HIGH-RISK CONTRACT PATTERNS ===\")\n",
    "\n",
    "# Define risk scoring for contracts\n",
    "contract_risk_scores = {}\n",
    "for filename, risks in contract_risk_matrix.items():\n",
    "    # Simple scoring: number of unique risk types present\n",
    "    risk_score = len(risks)\n",
    "    contract_risk_scores[filename] = risk_score\n",
    "\n",
    "# Identify high-risk contracts (top 10%)\n",
    "high_risk_threshold = np.percentile(list(contract_risk_scores.values()), 90)\n",
    "high_risk_contracts = {k: v for k, v in contract_risk_scores.items() if v >= high_risk_threshold}\n",
    "\n",
    "print(f\"High-risk contract analysis (top 10%, threshold: {high_risk_threshold} risk types):\")\n",
    "print(f\"High-risk contracts: {len(high_risk_contracts)}\")\n",
    "print(f\"Average risk types in high-risk contracts: {np.mean(list(high_risk_contracts.values())):.1f}\")\n",
    "\n",
    "# Show examples of high-risk contracts\n",
    "print(f\"Top 5 highest-risk contracts:\")\n",
    "for i, (filename, score) in enumerate(sorted(high_risk_contracts.items(), key=lambda x: x[1], reverse=True)[:5], 1):\n",
    "    risks_present = contract_risk_matrix[filename]\n",
    "    print(f\"  {i}. {filename}\")\n",
    "    print(f\"     Risk types ({score}): {', '.join([r.replace('_', ' ') for r in risks_present])}\")\n",
    "\n",
    "print(f\"Task 1 Complete: CUAD Dataset Deep Analysis\")\n",
    "print(f\"Key insights:\")\n",
    "print(f\"- {len(unmapped_categories)} categories need risk mapping\")\n",
    "print(f\"- Average {contract_stats['num_clauses'].mean():.1f} clauses per contract\")\n",
    "print(f\"- {len(high_risk_contracts)} contracts identified as high-risk\")\n",
    "print(f\"- Most common risk combination: {max(risk_cooccurrence.items(), key=lambda x: x[1])}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "667d9248",
   "metadata": {},
   "outputs": [],
   "source": [
    "# TASK 2: ENHANCE RISK TAXONOMY MAPPING\n",
    "# Map remaining 14 unmapped CUAD categories to appropriate risk types\n",
    "\n",
    "print(\"\\n\" + \"=\"*60)\n",
    "print(\"=== WEEK 1 TASK 2: ENHANCED RISK TAXONOMY MAPPING ===\")\n",
    "\n",
    "# Analyze unmapped categories with their clause examples to determine appropriate mappings\n",
    "unmapped_with_examples = {}\n",
    "for category in unmapped_categories:\n",
    "    if category in df_clauses['Category'].values:\n",
    "        category_clauses = df_clauses[df_clauses['Category'] == category]\n",
    "        count = len(category_clauses)\n",
    "        # Get a sample clause for analysis\n",
    "        sample_clause = category_clauses['Text'].iloc[0] if count > 0 else \"No sample available\"\n",
    "        unmapped_with_examples[category] = {\n",
    "            'count': count,\n",
    "            'sample': sample_clause[:200] + \"...\" if len(sample_clause) > 200 else sample_clause\n",
    "        }\n",
    "\n",
    "print(f\"Detailed analysis of unmapped categories:\")\n",
    "for category, details in unmapped_with_examples.items():\n",
    "    print(f\"{category} ({details['count']} clauses):\")\n",
    "    print(f\"Sample: {details['sample']}\")\n",
    "\n",
    "# Enhanced risk taxonomy with additional mappings based on analysis\n",
    "ENHANCED_RISK_TAXONOMY = RISK_TAXONOMY.copy()\n",
    "\n",
    "# Add new mappings based on legal domain knowledge and clause analysis\n",
    "NEW_CATEGORY_MAPPINGS = {\n",
    "    # Business Information and Parties\n",
    "    'Document Name': 'METADATA',  # Not a risk category, but contract metadata\n",
    "    'Parties': 'METADATA',       # Contract metadata\n",
    "    'Agreement Date': 'METADATA', # Contract metadata\n",
    "    'Effective Date': 'METADATA', # Contract metadata\n",
    "    \n",
    "    # Financial and Revenue \n",
    "    'Revenue/Profit Sharing': 'LIABILITY_RISK',  # Financial exposure\n",
    "    'Price Restrictions': 'OPERATIONAL_RISK',   # Business constraints\n",
    "    \n",
    "    # Licensing and IP (additional)\n",
    "    'Affiliate License-Licensor': 'IP_RISK',\n",
    "    'Affiliate License-Licensee': 'IP_RISK', \n",
    "    'Unlimited/All-You-Can-Eat-License': 'IP_RISK',\n",
    "    \n",
    "    # Competitive and Business Restrictions\n",
    "    'Competitive Restriction Exception': 'OPERATIONAL_RISK',\n",
    "    'Rofr/Rofo/Rofn': 'OPERATIONAL_RISK',  # Right of first refusal/offer/negotiation\n",
    "    \n",
    "    # Warranty and Quality\n",
    "    'Warranty Duration': 'LIABILITY_RISK',  # Warranty exposure\n",
    "}\n",
    "\n",
    "# Create new category mapping that includes both original and new mappings\n",
    "enhanced_category_to_risk_type = category_to_risk_type.copy()\n",
    "enhanced_category_to_risk_type.update(NEW_CATEGORY_MAPPINGS)\n",
    "\n",
    "# Filter out metadata categories from risk analysis\n",
    "METADATA_CATEGORIES = ['Document Name', 'Parties', 'Agreement Date', 'Effective Date']\n",
    "risk_categories_only = {k: v for k, v in enhanced_category_to_risk_type.items() \n",
    "                       if v != 'METADATA'}\n",
    "\n",
    "print(f\"=== ENHANCED RISK TAXONOMY RESULTS ===\")\n",
    "print(f\"Original mapped categories: {len(category_to_risk_type)}\")\n",
    "print(f\"New category mappings: {len(NEW_CATEGORY_MAPPINGS)}\")\n",
    "print(f\"Enhanced mapped categories: {len(enhanced_category_to_risk_type)}\")\n",
    "print(f\"Risk categories (excluding metadata): {len(risk_categories_only)}\")\n",
    "\n",
    "# Recalculate coverage with enhanced taxonomy\n",
    "enhanced_mapped_categories = set(enhanced_category_to_risk_type.keys())\n",
    "enhanced_coverage = (len(enhanced_mapped_categories) / len(all_categories)) * 100\n",
    "\n",
    "print(f\"=== ENHANCED COVERAGE ANALYSIS ===\")\n",
    "print(f\"Enhanced coverage: {len(enhanced_mapped_categories)}/{len(all_categories)} ({enhanced_coverage:.1f}%)\")\n",
    "print(f\"Improvement: +{enhanced_coverage - coverage_percentage:.1f} percentage points\")\n",
    "\n",
    "# Show new mappings\n",
    "print(f\"\\n=== NEW CATEGORY MAPPINGS ===\")\n",
    "for category, risk_type in NEW_CATEGORY_MAPPINGS.items():\n",
    "    if category in df_clauses['Category'].values:\n",
    "        count = len(df_clauses[df_clauses['Category'] == category])\n",
    "        print(f\"{category} โ†’ {risk_type} ({count} clauses)\")\n",
    "\n",
    "# Update our working taxonomy\n",
    "enhanced_risk_taxonomy = enhanced_category_to_risk_type\n",
    "\n",
    "# Analyze enhanced risk distribution\n",
    "print(f\"\\n=== ENHANCED RISK DISTRIBUTION ===\")\n",
    "enhanced_risk_distribution = {}\n",
    "for _, clause in df_clauses.iterrows():\n",
    "    category = clause['Category']\n",
    "    if category in risk_categories_only:  # Exclude metadata\n",
    "        risk_type = risk_categories_only[category]\n",
    "        enhanced_risk_distribution[risk_type] = enhanced_risk_distribution.get(risk_type, 0) + 1\n",
    "\n",
    "for risk_type, count in sorted(enhanced_risk_distribution.items(), key=lambda x: x[1], reverse=True):\n",
    "    percentage = (count / len(df_clauses)) * 100\n",
    "    print(f\"{risk_type}: {count} clauses ({percentage:.1f}%)\")\n",
    "\n",
    "# Create baseline risk scorer with enhanced taxonomy\n",
    "class EnhancedBaselineRiskScorer:\n",
    "    \"\"\"Enhanced baseline risk scoring using keyword-based approach with taxonomy\"\"\"\n",
    "    \n",
    "    def __init__(self):\n",
    "        # Enhanced risk keywords based on legal domain knowledge\n",
    "        self.risk_keywords = {\n",
    "            'LIABILITY_RISK': [\n",
    "                'liable', 'liability', 'damages', 'loss', 'harm', 'injury', 'compensation',\n",
    "                'indemnify', 'indemnification', 'liquidated damages', 'cap', 'limit',\n",
    "                'uncapped', 'unlimited liability', 'consequential damages'\n",
    "            ],\n",
    "            'INDEMNITY_RISK': [\n",
    "                'indemnify', 'indemnification', 'hold harmless', 'defend', 'third party',\n",
    "                'claims', 'suits', 'proceedings', 'defense obligations'\n",
    "            ],\n",
    "            'TERMINATION_RISK': [\n",
    "                'terminate', 'termination', 'expire', 'breach', 'default', 'convenience',\n",
    "                'cause', 'notice', 'wind down', 'post-termination', 'survival'\n",
    "            ],\n",
    "            'CONFIDENTIALITY_RISK': [\n",
    "                'confidential', 'confidentiality', 'proprietary', 'trade secret',\n",
    "                'non-disclosure', 'nda', 'disclose', 'information', 'compete', 'non-compete'\n",
    "            ],\n",
    "            'OPERATIONAL_RISK': [\n",
    "                'exclusive', 'exclusivity', 'performance', 'minimum', 'commitment',\n",
    "                'volume', 'restriction', 'obligation', 'requirement', 'compliance'\n",
    "            ],\n",
    "            'IP_RISK': [\n",
    "                'intellectual property', 'patent', 'copyright', 'trademark', 'license',\n",
    "                'ownership', 'rights', 'infringement', 'joint', 'derivative'\n",
    "            ],\n",
    "            'COMPLIANCE_RISK': [\n",
    "                'governing law', 'jurisdiction', 'regulatory', 'compliance', 'assign',\n",
    "                'assignment', 'control', 'change of control', 'authority'\n",
    "            ]\n",
    "        }\n",
    "    \n",
    "    def score_clause(self, clause_text: str, category: str) -> dict:\n",
    "        \"\"\"Score a clause for risk level\"\"\"\n",
    "        if not isinstance(clause_text, str):\n",
    "            return {'risk_score': 0, 'risk_type': 'UNKNOWN', 'keywords_found': []}\n",
    "        \n",
    "        text_lower = clause_text.lower()\n",
    "        \n",
    "        # Get risk type from enhanced taxonomy\n",
    "        risk_type = enhanced_risk_taxonomy.get(category, 'UNKNOWN')\n",
    "        if risk_type == 'METADATA':\n",
    "            return {'risk_score': 0, 'risk_type': 'METADATA', 'keywords_found': []}\n",
    "        \n",
    "        # Find keywords for this risk type\n",
    "        keywords_found = []\n",
    "        if risk_type in self.risk_keywords:\n",
    "            for keyword in self.risk_keywords[risk_type]:\n",
    "                if keyword in text_lower:\n",
    "                    keywords_found.append(keyword)\n",
    "        \n",
    "        # Calculate risk score (0-10)\n",
    "        base_score = len(keywords_found) * 1.5  # Keywords contribute to score\n",
    "        length_factor = min(len(clause_text.split()) / 50, 2)  # Longer clauses may be riskier\n",
    "        \n",
    "        risk_score = min(base_score + length_factor, 10)\n",
    "        \n",
    "        return {\n",
    "            'risk_score': round(risk_score, 2),\n",
    "            'risk_type': risk_type,\n",
    "            'keywords_found': keywords_found\n",
    "        }\n",
    "\n",
    "# Test enhanced baseline scorer\n",
    "print(f\"\\n=== TESTING ENHANCED BASELINE RISK SCORER ===\")\n",
    "enhanced_scorer = EnhancedBaselineRiskScorer()\n",
    "\n",
    "# Test on sample clauses from each risk type\n",
    "test_results = []\n",
    "for risk_type in enhanced_risk_distribution.keys():\n",
    "    # Find a clause for this risk type\n",
    "    risk_clauses = df_clauses[df_clauses['Category'].map(\n",
    "        lambda x: enhanced_risk_taxonomy.get(x, 'UNKNOWN') == risk_type\n",
    "    )]\n",
    "    \n",
    "    if len(risk_clauses) > 0:\n",
    "        sample_clause = risk_clauses.iloc[0]\n",
    "        score_result = enhanced_scorer.score_clause(sample_clause['Text'], sample_clause['Category'])\n",
    "        \n",
    "        test_results.append({\n",
    "            'risk_type': risk_type,\n",
    "            'category': sample_clause['Category'],\n",
    "            'score': score_result['risk_score'],\n",
    "            'keywords': len(score_result['keywords_found'])\n",
    "        })\n",
    "        \n",
    "        print(f\"{risk_type}:\")\n",
    "        print(f\"Category: {sample_clause['Category']}\")\n",
    "        print(f\"Risk Score: {score_result['risk_score']}/10\")\n",
    "        print(f\"Keywords Found: {score_result['keywords_found'][:5]}\")  # Show first 5\n",
    "\n",
    "print(f\"Task 2 Complete: Enhanced Risk Taxonomy Mapping\")\n",
    "print(f\"Coverage improved to {enhanced_coverage:.1f}% ({len(enhanced_mapped_categories)} categories)\")\n",
    "print(f\"Enhanced baseline scorer ready for all {len(enhanced_risk_distribution)} risk types!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3319ab4d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# TASK 3: ENHANCED BASELINE RISK SCORING\n",
    "# Expand keyword-based risk detection to all 7 risk categories with legal domain expertise\n",
    "\n",
    "from collections import defaultdict\n",
    "\n",
    "print(\"\\n\" + \"=\"*60)\n",
    "print(\"=== WEEK 1 TASK 3: ENHANCED BASELINE RISK SCORING ===\")\n",
    "\n",
    "# Enhanced risk keywords based on legal expertise and CUAD analysis\n",
    "ENHANCED_RISK_KEYWORDS = {\n",
    "    'LIABILITY_RISK': {\n",
    "        'high': [\n",
    "            'unlimited liability', 'uncapped liability', 'joint and several liability',\n",
    "            'liquidated damages', 'punitive damages', 'unlimited damages',\n",
    "            'no limitation of liability', 'no cap on liability', 'full liability'\n",
    "        ],\n",
    "        'medium': [\n",
    "            'liability cap', 'limitation of liability', 'consequential damages',\n",
    "            'indirect damages', 'liability limit', 'maximum liability',\n",
    "            'aggregate liability', 'total liability shall not exceed'\n",
    "        ],\n",
    "        'low': [\n",
    "            'liability limitation', 'damages exclusion', 'insurance coverage',\n",
    "            'liability insurance', 'limited liability', 'no liability for',\n",
    "            'excluding liability', 'liability waiver'\n",
    "        ]\n",
    "    },\n",
    "    \n",
    "    'INDEMNITY_RISK': {\n",
    "        'high': [\n",
    "            'indemnify and hold harmless', 'full indemnification', 'unlimited indemnity',\n",
    "            'broad indemnification', 'indemnify against all claims', 'defend and indemnify'\n",
    "        ],\n",
    "        'medium': [\n",
    "            'indemnification', 'hold harmless', 'mutual indemnification',\n",
    "            'indemnify against', 'third party claims', 'indemnity obligations'\n",
    "        ],\n",
    "        'low': [\n",
    "            'limited indemnification', 'specific indemnity', 'indemnity exclusion',\n",
    "            'no indemnification', 'indemnity waiver'\n",
    "        ]\n",
    "    },\n",
    "    \n",
    "    'TERMINATION_RISK': {\n",
    "        'high': [\n",
    "            'immediate termination', 'termination without cause', 'no notice termination',\n",
    "            'terminate at will', 'termination without reason', 'instant termination'\n",
    "        ],\n",
    "        'medium': [\n",
    "            '30 days notice', 'convenience termination', 'material breach',\n",
    "            'termination for convenience', 'written notice', 'notice period'\n",
    "        ],\n",
    "        'low': [\n",
    "            '90 days notice', 'cure period', 'mutual termination',\n",
    "            'opportunity to cure', 'remedy period', 'termination by mutual consent'\n",
    "        ]\n",
    "    },\n",
    "    \n",
    "    'CONFIDENTIALITY_RISK': {\n",
    "        'high': [\n",
    "            'perpetual confidentiality', 'unlimited confidentiality', 'broad confidentiality',\n",
    "            'all information confidential', 'strict confidentiality', 'non-disclosure'\n",
    "        ],\n",
    "        'medium': [\n",
    "            'confidential information', 'proprietary information', 'confidentiality obligations',\n",
    "            'confidentiality agreement', 'confidential data', 'trade secrets'\n",
    "        ],\n",
    "        'low': [\n",
    "            'limited confidentiality', 'specific confidentiality', 'confidentiality exceptions',\n",
    "            'publicly available information', 'confidentiality exclusions'\n",
    "        ]\n",
    "    },\n",
    "    \n",
    "    'OPERATIONAL_RISK': {\n",
    "        'high': [\n",
    "            'exclusive dealing', 'non-compete', 'minimum purchase requirement',\n",
    "            'volume restriction', 'exclusivity requirement', 'sole supplier',\n",
    "            'exclusive supplier', 'dedicated resources', 'exclusive relationship'\n",
    "        ],\n",
    "        'medium': [\n",
    "            'preferred supplier', 'exclusivity period', 'minimum commitment',\n",
    "            'volume commitment', 'preferred vendor', 'preferential terms',\n",
    "            'first right of refusal', 'most favored nation'\n",
    "        ],\n",
    "        'low': [\n",
    "            'best efforts', 'reasonable efforts', 'commercially reasonable efforts',\n",
    "            'good faith efforts', 'diligent efforts', 'reasonable commercial efforts'\n",
    "        ]\n",
    "    },\n",
    "    \n",
    "    'IP_RISK': {\n",
    "        'high': [\n",
    "            'ip assignment', 'intellectual property assignment', 'work for hire',\n",
    "            'perpetual license', 'irrevocable license', 'unlimited license',\n",
    "            'exclusive license', 'all rights assigned', 'ownership transfer'\n",
    "        ],\n",
    "        'medium': [\n",
    "            'joint ownership', 'limited license', 'royalty-free license',\n",
    "            'non-exclusive license', 'license grant', 'ip license',\n",
    "            'intellectual property license', 'usage rights'\n",
    "        ],\n",
    "        'low': [\n",
    "            'license back', 'defensive patent license', 'fair use',\n",
    "            'limited use license', 'specific use license', 'restricted license'\n",
    "        ]\n",
    "    },\n",
    "    \n",
    "    'COMPLIANCE_RISK': {\n",
    "        'high': [\n",
    "            'audit rights', 'unlimited audit rights', 'comprehensive audit',\n",
    "            'full audit access', 'regulatory compliance', 'compliance monitoring',\n",
    "            'audit at any time', 'detailed audit rights'\n",
    "        ],\n",
    "        'medium': [\n",
    "            'periodic audit', 'reasonable audit', 'audit with notice',\n",
    "            'compliance review', 'audit procedures', 'limited audit rights'\n",
    "        ],\n",
    "        'low': [\n",
    "            'self-audit', 'audit limitations', 'audit restrictions',\n",
    "            'no audit rights', 'audit exclusions'\n",
    "        ]\n",
    "    }\n",
    "}\n",
    "\n",
    "# Enhanced baseline risk scorer with improved capabilities\n",
    "class EnhancedBaselineRiskScorer:\n",
    "    def __init__(self, risk_keywords):\n",
    "        self.risk_keywords = risk_keywords\n",
    "        self.risk_weights = {'high': 3, 'medium': 2, 'low': 1}\n",
    "        \n",
    "    def calculate_keyword_score(self, text, risk_type):\n",
    "        \"\"\"Enhanced keyword scoring with phrase matching and context awareness\"\"\"\n",
    "        if risk_type not in self.risk_keywords:\n",
    "            return {'score': 0.0, 'matches': {}, 'raw_score': 0}\n",
    "            \n",
    "        text_lower = text.lower()\n",
    "        total_score = 0\n",
    "        keyword_matches = defaultdict(list)\n",
    "        \n",
    "        for severity, keywords in self.risk_keywords[risk_type].items():\n",
    "            for keyword in keywords:\n",
    "                # Count occurrences of keyword/phrase\n",
    "                occurrences = text_lower.count(keyword.lower())\n",
    "                if occurrences > 0:\n",
    "                    weight = self.risk_weights[severity]\n",
    "                    # Add score for each occurrence (but cap at 2x for repeated phrases)\n",
    "                    score_multiplier = min(occurrences, 2)\n",
    "                    total_score += weight * score_multiplier\n",
    "                    keyword_matches[severity].append(f\"{keyword} ({occurrences}x)\")\n",
    "        \n",
    "        # Normalize score (0-10 scale) with improved calculation\n",
    "        max_possible = 0\n",
    "        for severity, keywords in self.risk_keywords[risk_type].items():\n",
    "            max_possible += len(keywords) * self.risk_weights[severity] * 2  # Max 2x per keyword\n",
    "        \n",
    "        normalized_score = min(10, (total_score / max_possible) * 10) if max_possible > 0 else 0\n",
    "        \n",
    "        return {\n",
    "            'score': round(normalized_score, 2),\n",
    "            'matches': dict(keyword_matches),\n",
    "            'raw_score': total_score\n",
    "        }\n",
    "    \n",
    "    def analyze_contract_risk(self, contract_text):\n",
    "        \"\"\"Analyze overall contract risk with enhanced scoring\"\"\"\n",
    "        risk_scores = {}\n",
    "        \n",
    "        for risk_type in self.risk_keywords.keys():\n",
    "            risk_scores[risk_type] = self.calculate_keyword_score(contract_text, risk_type)\n",
    "        \n",
    "        # Calculate weighted overall score (operational and liability risks weighted higher)\n",
    "        risk_type_weights = {\n",
    "            'LIABILITY_RISK': 1.5,\n",
    "            'OPERATIONAL_RISK': 1.3,\n",
    "            'IP_RISK': 1.2,\n",
    "            'TERMINATION_RISK': 1.1,\n",
    "            'COMPLIANCE_RISK': 1.0,\n",
    "            'INDEMNITY_RISK': 1.0,\n",
    "            'CONFIDENTIALITY_RISK': 0.9\n",
    "        }\n",
    "        \n",
    "        weighted_sum = 0\n",
    "        total_weights = 0\n",
    "        \n",
    "        for risk_type, score_data in risk_scores.items():\n",
    "            weight = risk_type_weights.get(risk_type, 1.0)\n",
    "            weighted_sum += score_data['score'] * weight\n",
    "            total_weights += weight\n",
    "        \n",
    "        overall_score = weighted_sum / total_weights if total_weights > 0 else 0\n",
    "        \n",
    "        return {\n",
    "            'overall_risk_score': round(overall_score, 2),\n",
    "            'individual_risks': risk_scores,\n",
    "            'risk_level': self.categorize_risk_level(overall_score),\n",
    "            'highest_risk_category': max(risk_scores.items(), key=lambda x: x[1]['score'])\n",
    "        }\n",
    "    \n",
    "    def categorize_risk_level(self, score):\n",
    "        \"\"\"Enhanced risk level categorization\"\"\"\n",
    "        if score >= 7:\n",
    "            return 'CRITICAL'\n",
    "        elif score >= 5:\n",
    "            return 'HIGH'\n",
    "        elif score >= 3:\n",
    "            return 'MEDIUM'\n",
    "        else:\n",
    "            return 'LOW'\n",
    "\n",
    "# Initialize enhanced baseline scorer\n",
    "enhanced_baseline_scorer = EnhancedBaselineRiskScorer(ENHANCED_RISK_KEYWORDS)\n",
    "\n",
    "print(f\"Enhanced baseline risk scorer initialized:\")\n",
    "print(f\"  Risk categories: {len(ENHANCED_RISK_KEYWORDS)}\")\n",
    "total_keywords = sum(len(keywords['high']) + len(keywords['medium']) + len(keywords['low']) \n",
    "                    for keywords in ENHANCED_RISK_KEYWORDS.values())\n",
    "print(f\"  Total keywords: {total_keywords}\")\n",
    "\n",
    "# Test enhanced scoring on sample clauses from each risk category\n",
    "print(f\"\\n=== ENHANCED BASELINE TESTING ===\")\n",
    "\n",
    "# Test one clause from each mapped risk category\n",
    "test_results = []\n",
    "for risk_type in ENHANCED_RISK_KEYWORDS.keys():\n",
    "    # Find a clause of this risk type\n",
    "    for category in ENHANCED_RISK_TAXONOMY[risk_type]['categories']:\n",
    "        if category in df_clauses['Category'].values:\n",
    "            sample_clause = df_clauses[df_clauses['Category'] == category].iloc[0]\n",
    "            risk_analysis = enhanced_baseline_scorer.calculate_keyword_score(\n",
    "                sample_clause['Text'], risk_type\n",
    "            )\n",
    "            \n",
    "            test_results.append({\n",
    "                'risk_type': risk_type,\n",
    "                'category': category,\n",
    "                'score': risk_analysis['score'],\n",
    "                'matches': len([m for matches in risk_analysis['matches'].values() for m in matches]),\n",
    "                'text_preview': sample_clause['Text'][:100] + \"...\"\n",
    "            })\n",
    "            break\n",
    "\n",
    "# Display test results\n",
    "for result in test_results:\n",
    "    print(f\"{result['risk_type']}:\")\n",
    "    print(f\"Category: {result['category']}\")\n",
    "    print(f\"Score: {result['score']}/10\")\n",
    "    print(f\"Keyword matches: {result['matches']}\")\n",
    "    print(f\"Text: {result['text_preview']}\")\n",
    "\n",
    "# Test contract-level risk scoring\n",
    "print(f\"\\n=== CONTRACT-LEVEL RISK ANALYSIS SAMPLE ===\")\n",
    "sample_contract = df_clauses[df_clauses['Filename'] == df_clauses['Filename'].iloc[0]]\n",
    "contract_text = \" \".join(sample_contract['Text'].tolist())\n",
    "\n",
    "contract_risk = enhanced_baseline_scorer.analyze_contract_risk(contract_text)\n",
    "print(f\"Contract: {sample_contract['Filename'].iloc[0]}\")\n",
    "print(f\"Overall Risk Score: {contract_risk['overall_risk_score']}/10\")\n",
    "print(f\"Risk Level: {contract_risk['risk_level']}\")\n",
    "print(f\"Highest Risk Category: {contract_risk['highest_risk_category'][0]} ({contract_risk['highest_risk_category'][1]['score']}/10)\")\n",
    "\n",
    "print(f\"Task 3 Complete: Enhanced Baseline Risk Scoring\")\n",
    "print(f\"All 7 risk categories now supported with {total_keywords} domain-specific keywords\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ab92b85b",
   "metadata": {},
   "source": [
    "# ๐ŸŽ‰ WEEK 1 COMPLETION SUMMARY & NEXT STEPS\n",
    "\n",
    "## โœ… **WEEK 1 ACHIEVEMENTS**\n",
    "\n",
    "### **COMPLETED TASKS:**\n",
    "1. **โœ… Complete CUAD Dataset Deep Analysis**\n",
    "   - Processed 19,598 clauses from 510 contracts across 42 categories\n",
    "   - Identified contract complexity patterns and high-risk contract characteristics\n",
    "   - Analyzed risk category co-occurrence patterns\n",
    "\n",
    "2. **โœ… Enhanced Risk Taxonomy Mapping** \n",
    "   - **Coverage improved from 68.9% to 95.2%** (40/42 categories mapped)\n",
    "   - Added METADATA category for contract information\n",
    "   - Mapped additional categories: Revenue/Profit Sharing, Price Restrictions, etc.\n",
    "\n",
    "3. **โœ… Enhanced Baseline Risk Scoring**\n",
    "   - Expanded from 4 to **7 risk categories** with **142 domain-specific keywords**\n",
    "   - Implemented phrase matching and context-aware scoring\n",
    "   - Added weighted contract-level risk aggregation\n",
    "\n",
    "### **KEY INSIGHTS DISCOVERED:**\n",
    "- **Risk Distribution**: Operational Risk (20.8%) > IP Risk (13.0%) > Liability Risk (10.4%)\n",
    "- **Contract Complexity**: Average 38.4 clauses per contract, 6,247 words per contract\n",
    "- **High-Risk Patterns**: 51 contracts identified as high-risk (top 10%)\n",
    "- **Co-occurrence**: Operational + IP risks appear together in 65% of contracts\n",
    "\n",
    "---\n",
    "\n",
    "## ๐Ÿ“‹ **DETAILED IMPLEMENTATION PLAN FOR WEEKS 2-9**\n",
    "\n",
    "### **WEEK 2: DATA PIPELINE & PREPROCESSING**\n",
    "\n",
    "#### **Priority Tasks:**\n",
    "1. **Data Pipeline Development**\n",
    "   - Implement clause segmentation and boundary detection\n",
    "   - Build legal entity extraction (parties, dates, amounts)\n",
    "   - Create contract metadata processing pipeline\n",
    "\n",
    "2. **Cross-validation Strategy**  \n",
    "   - Stratified splits ensuring balanced risk representation\n",
    "   - Contract-level splits to avoid data leakage\n",
    "   - Validation framework for risk scoring evaluation\n",
    "\n",
    "#### **Code Focus:**\n",
    "```python\n",
    "# Week 2 Implementation Areas:\n",
    "- Clause boundary detection using legal patterns\n",
    "- Named entity recognition for contract elements  \n",
    "- Train/validation/test splits with stratification\n",
    "- Data augmentation for imbalanced categories\n",
    "```\n",
    "\n",
    "---\n",
    "\n",
    "### **WEEK 3: CONTRACT-LEVEL RISK AGGREGATION**\n",
    "\n",
    "#### **Priority Tasks:**\n",
    "1. **Contract-Level Risk Scoring**\n",
    "   - Implement hierarchical risk aggregation (clause โ†’ contract)\n",
    "   - Weight clauses by importance and context\n",
    "   - Develop contract complexity scoring\n",
    "\n",
    "2. **Risk Pattern Analysis**\n",
    "   - Identify risk interaction patterns\n",
    "   - Build risk dependency models\n",
    "   - Create contract risk profiles\n",
    "\n",
    "---\n",
    "\n",
    "### **WEEKS 4-5: LEGAL-BERT IMPLEMENTATION**\n",
    "\n",
    "#### **Priority Tasks:**\n",
    "1. **Model Infrastructure Setup**\n",
    "   - Legal-BERT fine-tuning pipeline with HuggingFace\n",
    "   - Multi-task learning architecture design\n",
    "   - Training data preparation and tokenization\n",
    "\n",
    "2. **Multi-task Head Implementation**\n",
    "   - Risk type classification (7 classes)\n",
    "   - Risk severity regression (0-10 scale) \n",
    "   - Clause importance scoring\n",
    "\n",
    "#### **Technical Architecture:**\n",
    "```python\n",
    "# Legal-BERT Multi-task Model:\n",
    "Legal-BERT Encoder (768 dim)\n",
    "โ”œโ”€โ”€ Risk Classification Head (7 classes)\n",
    "โ”œโ”€โ”€ Severity Regression Head (continuous 0-10)\n",
    "โ””โ”€โ”€ Clause Importance Head (attention weights)\n",
    "```\n",
    "\n",
    "---\n",
    "\n",
    "### **WEEK 6: MODEL OPTIMIZATION & ENSEMBLE**\n",
    "\n",
    "#### **Priority Tasks:**\n",
    "1. **Model Enhancement**\n",
    "   - Attention mechanism analysis for interpretability\n",
    "   - Hyperparameter optimization and model selection\n",
    "   - Ensemble strategies for improved performance\n",
    "\n",
    "2. **Transfer Learning Experiments**\n",
    "   - Domain adaptation techniques\n",
    "   - Few-shot learning for rare risk categories\n",
    "\n",
    "---\n",
    "\n",
    "### **WEEKS 7-8: CALIBRATION & EVALUATION**\n",
    "\n",
    "#### **Priority Tasks:**\n",
    "1. **Model Calibration** (Framework already implemented โœ…)\n",
    "   - Temperature scaling integration with Legal-BERT\n",
    "   - Uncertainty quantification with Monte Carlo dropout\n",
    "   - Conformal prediction intervals\n",
    "\n",
    "2. **Comprehensive Evaluation**\n",
    "   - Baseline vs Legal-BERT performance comparison\n",
    "   - Expert correlation analysis\n",
    "   - Error analysis and failure case identification\n",
    "\n",
    "---\n",
    "\n",
    "### **WEEK 9: FINALIZATION & DOCUMENTATION**\n",
    "\n",
    "#### **Priority Tasks:**\n",
    "1. **Performance Analysis**\n",
    "   - Statistical significance testing\n",
    "   - Ablation studies on model components\n",
    "   - Risk score interpretation features\n",
    "\n",
    "2. **Implementation Report**\n",
    "   - Comprehensive documentation\n",
    "   - Deployment guidelines\n",
    "   - Future enhancement recommendations\n",
    "\n",
    "---\n",
    "\n",
    "## ๐ŸŽฏ **SUCCESS METRICS TRACKING**\n",
    "\n",
    "### **Current Status:**\n",
    "- **Data Coverage**: 95.2% (40/42 categories mapped) โœ…\n",
    "- **Baseline Implementation**: 7 risk categories, 142 keywords โœ…  \n",
    "- **Framework Ready**: Calibration and evaluation systems โœ…\n",
    "\n",
    "### **Week 2-3 Targets:**\n",
    "- **Pipeline Efficiency**: <500ms per contract processing\n",
    "- **Cross-validation**: Balanced 70/15/15 splits implemented\n",
    "- **Contract Scoring**: Hierarchical risk aggregation working\n",
    "\n",
    "### **Week 4-6 Targets:**\n",
    "- **Model Performance**: >75% accuracy on risk classification\n",
    "- **Training Efficiency**: <4 hours for full Legal-BERT fine-tuning\n",
    "- **Multi-task Learning**: Joint optimization across all risk tasks\n",
    "\n",
    "### **Week 7-9 Targets:**\n",
    "- **Calibration Quality**: ECE <0.08, Brier Score <0.20\n",
    "- **Expert Correlation**: Pearson >0.65 with legal assessments\n",
    "- **Documentation**: Complete implementation guide\n",
    "\n",
    "---\n",
    "\n",
    "## ๐Ÿš€ **IMMEDIATE NEXT ACTIONS (Week 2)**\n",
    "\n",
    "1. **Start Data Pipeline Development** - Clause segmentation implementation\n",
    "2. **Design Cross-validation Strategy** - Stratified contract-level splits  \n",
    "3. **Plan Legal-BERT Setup** - Environment and dependency preparation\n",
    "4. **Continue Risk Analysis** - Contract-level aggregation strategies\n",
    "\n",
    "**Ready to proceed to Week 2 tasks! ๐ŸŽฏ**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0e41f8e2",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"STARTING WEEK 2: DATA PIPELINE & PREPROCESSING\")\n",
    "print(\"=\"*70)\n",
    "\n",
    "# Build comprehensive preprocessing pipeline for Legal-BERT training\n",
    "\n",
    "class ContractDataPipeline:\n",
    "    \"\"\"\n",
    "    Advanced data pipeline for contract clause processing and Legal-BERT preparation\n",
    "    \"\"\"\n",
    "    \n",
    "    def __init__(self):\n",
    "        # Legal-specific patterns for clause segmentation\n",
    "        self.clause_boundary_patterns = [\n",
    "            r'\\n\\s*\\d+\\.\\s+',  # Numbered sections\n",
    "            r'\\n\\s*\\([a-zA-Z0-9]+\\)\\s+',  # Lettered subsections\n",
    "            r'\\n\\s*[A-Z][A-Z\\s]{10,}:',  # ALL CAPS headers\n",
    "            r'\\.\\s+[A-Z][a-z]+\\s+shall',  # Legal obligation statements\n",
    "            r'\\.\\s+[A-Z][a-z]+\\s+agrees?',  # Agreement statements\n",
    "            r'\\.\\s+In\\s+the\\s+event\\s+that',  # Conditional clauses\n",
    "        ]\n",
    "        \n",
    "        # Legal entity patterns\n",
    "        self.entity_patterns = {\n",
    "            'monetary': r'\\$[\\d,]+(?:\\.\\d{2})?',\n",
    "            'percentage': r'\\d+(?:\\.\\d+)?%',\n",
    "            'time_period': r'\\d+\\s*(?:days?|months?|years?|weeks?)',\n",
    "            'legal_entities': r'(?:Inc\\.|LLC|Corp\\.|Corporation|Company|Ltd\\.)',\n",
    "            'parties': r'\\b(?:Party|Parties|Company|Corporation|Licensor|Licensee|Vendor|Customer)\\b',\n",
    "            'dates': r'\\b(?:January|February|March|April|May|June|July|August|September|October|November|December)\\s+\\d{1,2},?\\s+\\d{4}|\\d{1,2}[/-]\\d{1,2}[/-]\\d{2,4}'\n",
    "        }\n",
    "        \n",
    "        # Legal complexity indicators\n",
    "        self.complexity_indicators = {\n",
    "            'modal_verbs': r'\\b(?:shall|must|may|should|will|might|could|would)\\b',\n",
    "            'conditional_terms': r'\\b(?:if|unless|provided|subject to|in the event|notwithstanding)\\b',\n",
    "            'legal_conjunctions': r'\\b(?:whereas|therefore|furthermore|moreover|however)\\b',\n",
    "            'obligation_terms': r'\\b(?:agrees?|undertakes?|covenants?|warrants?|represents?)\\b'\n",
    "        }\n",
    "    \n",
    "    def clean_clause_text(self, text: str) -> str:\n",
    "        \"\"\"Clean and normalize clause text\"\"\"\n",
    "        if not isinstance(text, str):\n",
    "            return \"\"\n",
    "        \n",
    "        # Remove excessive whitespace\n",
    "        text = re.sub(r'\\s+', ' ', text)\n",
    "        \n",
    "        # Remove special characters but keep legal punctuation\n",
    "        text = re.sub(r'[^\\w\\s\\.\\,\\;\\:\\(\\)\\-\\\"\\'\\$\\%]', ' ', text)\n",
    "        \n",
    "        # Normalize quotes\n",
    "        text = re.sub(r'[\"\"\"]', '\"', text)\n",
    "        text = re.sub(r'['']', \"'\", text)\n",
    "        \n",
    "        return text.strip()\n",
    "    \n",
    "    def extract_legal_entities(self, text: str) -> Dict:\n",
    "        \"\"\"Extract legal entities and key information from clause text\"\"\"\n",
    "        entities = {}\n",
    "        \n",
    "        # Extract using regex patterns\n",
    "        for entity_type, pattern in self.entity_patterns.items():\n",
    "            matches = re.findall(pattern, text, re.IGNORECASE)\n",
    "            entities[entity_type] = matches\n",
    "        \n",
    "        return entities\n",
    "    \n",
    "    def calculate_text_complexity(self, text: str) -> float:\n",
    "        \"\"\"Calculate text complexity score based on legal language features\"\"\"\n",
    "        if not text:\n",
    "            return 0.0\n",
    "        \n",
    "        words = text.split()\n",
    "        if len(words) == 0:\n",
    "            return 0.0\n",
    "        \n",
    "        # Features indicating legal complexity\n",
    "        features = {\n",
    "            'avg_word_length': sum(len(word) for word in words) / len(words),\n",
    "            'long_words': sum(1 for word in words if len(word) > 6) / len(words),\n",
    "            'sentences': len(re.split(r'[.!?]+', text)),\n",
    "            'subordinate_clauses': (text.count(',') + text.count(';')) / len(words) * 100,\n",
    "        }\n",
    "        \n",
    "        # Count legal complexity indicators\n",
    "        for indicator_type, pattern in self.complexity_indicators.items():\n",
    "            matches = len(re.findall(pattern, text, re.IGNORECASE))\n",
    "            features[indicator_type] = matches / len(words) * 100\n",
    "        \n",
    "        # Normalize to 0-10 scale\n",
    "        complexity = (\n",
    "            min(features['avg_word_length'] / 8, 1) * 2 +\n",
    "            features['long_words'] * 2 +\n",
    "            min(features['subordinate_clauses'] / 5, 1) * 2 +\n",
    "            min(features['conditional_terms'] / 2, 1) * 2 +\n",
    "            min(features['modal_verbs'] / 3, 1) * 2\n",
    "        )\n",
    "        \n",
    "        return min(complexity, 10)\n",
    "    \n",
    "    def prepare_clause_for_bert(self, clause_text: str, max_length: int = 512) -> Dict:\n",
    "        \"\"\"\n",
    "        Prepare clause text for Legal-BERT input with tokenization info\n",
    "        \"\"\"\n",
    "        # Clean text\n",
    "        clean_text = self.clean_clause_text(clause_text)\n",
    "        \n",
    "        # Basic tokenization (words)\n",
    "        words = clean_text.split()\n",
    "        \n",
    "        # Truncate if too long (leave room for special tokens)\n",
    "        if len(words) > max_length - 10:\n",
    "            words = words[:max_length-10]\n",
    "            clean_text = ' '.join(words)\n",
    "            truncated = True\n",
    "        else:\n",
    "            truncated = False\n",
    "        \n",
    "        # Extract entities\n",
    "        entities = self.extract_legal_entities(clean_text)\n",
    "        \n",
    "        return {\n",
    "            'text': clean_text,\n",
    "            'word_count': len(words),\n",
    "            'char_count': len(clean_text),\n",
    "            'sentence_count': len(re.split(r'[.!?]+', clean_text)),\n",
    "            'truncated': truncated,\n",
    "            'entities': entities,\n",
    "            'complexity_score': self.calculate_text_complexity(clean_text)\n",
    "        }\n",
    "    \n",
    "    def analyze_contract_structure(self, contract_text: str) -> Dict:\n",
    "        \"\"\"Analyze the overall structure of a contract\"\"\"\n",
    "        structure = {\n",
    "            'total_length': len(contract_text),\n",
    "            'paragraph_count': len([p for p in contract_text.split('\\n\\n') if p.strip()]),\n",
    "            'section_headers': len(re.findall(r'\\n\\s*[A-Z][A-Z\\s]{5,}:', contract_text)),\n",
    "            'numbered_sections': len(re.findall(r'\\n\\s*\\d+\\.\\s+', contract_text)),\n",
    "            'subsections': len(re.findall(r'\\n\\s*\\([a-zA-Z0-9]+\\)\\s+', contract_text)),\n",
    "        }\n",
    "        \n",
    "        # Extract all entities from full contract\n",
    "        all_entities = self.extract_legal_entities(contract_text)\n",
    "        structure['contract_entities'] = {k: len(v) for k, v in all_entities.items()}\n",
    "        \n",
    "        return structure\n",
    "    \n",
    "    def process_cuad_dataset(self, df_clauses: pd.DataFrame, sample_size: Optional[int] = None) -> pd.DataFrame:\n",
    "        \"\"\"\n",
    "        Process the CUAD dataset through the pipeline\n",
    "        \"\"\"\n",
    "        print(\"Processing CUAD dataset through advanced pipeline...\")\n",
    "        \n",
    "        # Sample if requested\n",
    "        if sample_size:\n",
    "            df_clauses = df_clauses.sample(sample_size, random_state=42)\n",
    "            print(f\"Processing sample of {sample_size} clauses\")\n",
    "        \n",
    "        processed_data = []\n",
    "        total_clauses = len(df_clauses)\n",
    "        \n",
    "        for idx, row in df_clauses.iterrows():\n",
    "            if idx % 1000 == 0:\n",
    "                print(f\"Processed {idx}/{total_clauses} clauses ({(idx/total_clauses)*100:.1f}%)\")\n",
    "            \n",
    "            # Process clause through pipeline\n",
    "            bert_ready = self.prepare_clause_for_bert(row['Text'])\n",
    "            \n",
    "            processed_data.append({\n",
    "                'filename': row['Filename'],\n",
    "                'category': row['Category'],\n",
    "                'original_text': row['Text'],\n",
    "                'processed_text': bert_ready['text'],\n",
    "                'word_count': bert_ready['word_count'],\n",
    "                'char_count': bert_ready['char_count'],\n",
    "                'sentence_count': bert_ready['sentence_count'],\n",
    "                'truncated': bert_ready['truncated'],\n",
    "                'complexity_score': bert_ready['complexity_score'],\n",
    "                'monetary_amounts': len(bert_ready['entities']['monetary']),\n",
    "                'time_periods': len(bert_ready['entities']['time_period']),\n",
    "                'legal_entities': len(bert_ready['entities']['legal_entities']),\n",
    "                'source': row['Source']\n",
    "            })\n",
    "        \n",
    "        print(f\"Completed processing {total_clauses} clauses\")\n",
    "        return pd.DataFrame(processed_data)\n",
    "\n",
    "# Initialize the pipeline\n",
    "print(\"\\n=== INITIALIZING CONTRACT DATA PIPELINE ===\")\n",
    "pipeline = ContractDataPipeline()\n",
    "\n",
    "# Test on a sample of clauses\n",
    "print(\"\\n=== TESTING PIPELINE ON SAMPLE CLAUSES ===\")\n",
    "sample_clauses = df_clauses.sample(5, random_state=42)\n",
    "\n",
    "pipeline_results = []\n",
    "for idx, (_, clause) in enumerate(sample_clauses.iterrows(), 1):\n",
    "    print(f\"\\nSample {idx}: {clause['Category']}\")\n",
    "    processed = pipeline.prepare_clause_for_bert(clause['Text'])\n",
    "    \n",
    "    print(f\"Word count: {processed['word_count']}\")\n",
    "    print(f\"Sentences: {processed['sentence_count']}\")\n",
    "    print(f\"Complexity: {processed['complexity_score']:.2f}/10\")\n",
    "    print(f\"Monetary amounts: {len(processed['entities']['monetary'])}\")\n",
    "    print(f\"Time periods: {len(processed['entities']['time_period'])}\")\n",
    "    print(f\"Text preview: {processed['text'][:100]}...\")\n",
    "    \n",
    "    pipeline_results.append({\n",
    "        'category': clause['Category'],\n",
    "        'complexity': processed['complexity_score'],\n",
    "        'word_count': processed['word_count'],\n",
    "        'entities': sum(len(v) for v in processed['entities'].values())\n",
    "    })\n",
    "\n",
    "# Summary of pipeline test\n",
    "print(f\"\\n=== PIPELINE TEST SUMMARY ===\")\n",
    "test_df = pd.DataFrame(pipeline_results)\n",
    "print(f\"Average complexity score: {test_df['complexity'].mean():.2f}\")\n",
    "print(f\"Average word count: {test_df['word_count'].mean():.1f}\")\n",
    "print(f\"Average entities per clause: {test_df['entities'].mean():.1f}\")\n",
    "\n",
    "print(f\"Week 2 Task 1 Complete: Data Pipeline Development\")\n",
    "print(f\"Pipeline ready for Legal-BERT preprocessing!\")\n",
    "\n",
    "# Store pipeline for later use\n",
    "contract_pipeline = pipeline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1eafbb51",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ============================================================================\n",
    "# WEEK 2 - TASK 2: CROSS-VALIDATION STRATEGY & DATA SPLITTING\n",
    "# ============================================================================\n",
    "\n",
    "print(\"\\n\" + \"=\"*70)\n",
    "print(\"WEEK 2 TASK 2: ADVANCED CROSS-VALIDATION STRATEGY\")\n",
    "print(\"=\"*70)\n",
    "\n",
    "class LegalBertDataSplitter:\n",
    "    \"\"\"\n",
    "    Advanced data splitting strategy for Legal-BERT training with contract-level awareness\n",
    "    \"\"\"\n",
    "    \n",
    "    def __init__(self, df_clauses: pd.DataFrame):\n",
    "        self.df_clauses = df_clauses\n",
    "        self.contract_stats = None\n",
    "        self.splits = {}\n",
    "        \n",
    "    def analyze_contract_distribution(self):\n",
    "        \"\"\"Analyze the distribution of contracts and clauses\"\"\"\n",
    "        print(\"Analyzing contract and clause distribution...\")\n",
    "        \n",
    "        # Contract-level statistics\n",
    "        contract_stats = self.df_clauses.groupby('Filename').agg({\n",
    "            'Category': ['count', 'nunique'],\n",
    "            'Text': lambda x: np.mean([len(text.split()) for text in x])  # Avg words per clause\n",
    "        }).round(2)\n",
    "        \n",
    "        contract_stats.columns = ['Total_Clauses', 'Unique_Categories', 'Avg_Words_Per_Clause']\n",
    "        contract_stats = contract_stats.reset_index()\n",
    "        \n",
    "        # Risk category distribution per contract\n",
    "        risk_distribution = self.df_clauses.groupby(['Filename', 'Category']).size().unstack(fill_value=0)\n",
    "        \n",
    "        self.contract_stats = {\n",
    "            'total_contracts': len(contract_stats),\n",
    "            'total_clauses': len(self.df_clauses),\n",
    "            'avg_clauses_per_contract': contract_stats['Total_Clauses'].mean(),\n",
    "            'contract_details': contract_stats,\n",
    "            'risk_distribution': risk_distribution\n",
    "        }\n",
    "        \n",
    "        print(f\"Total contracts: {self.contract_stats['total_contracts']}\")\n",
    "        print(f\"Total clauses: {self.contract_stats['total_clauses']}\")\n",
    "        print(f\"Avg clauses per contract: {self.contract_stats['avg_clauses_per_contract']:.1f}\")\n",
    "        \n",
    "        # Category distribution\n",
    "        category_counts = self.df_clauses['Category'].value_counts()\n",
    "        print(f\"Top 10 Risk Categories:\")\n",
    "        for cat, count in category_counts.head(10).items():\n",
    "            print(f\"    {cat}: {count} clauses ({count/len(self.df_clauses)*100:.1f}%)\")\n",
    "        \n",
    "        return self.contract_stats\n",
    "    \n",
    "    def create_contract_level_splits(self, test_size=0.2, val_size=0.1, random_state=42):\n",
    "        \"\"\"\n",
    "        Create contract-level splits to avoid data leakage\n",
    "        \"\"\"\n",
    "        print(f\"Creating contract-level splits...\")\n",
    "        print(f\"Test size: {test_size*100:.0f}% | Validation size: {val_size*100:.0f}% | Train size: {(1-test_size-val_size)*100:.0f}%\")\n",
    "        \n",
    "        # Get unique contracts\n",
    "        unique_contracts = self.df_clauses['Filename'].unique()\n",
    "        \n",
    "        # First split: train+val vs test\n",
    "        train_val_contracts, test_contracts = train_test_split(\n",
    "            unique_contracts, \n",
    "            test_size=test_size, \n",
    "            random_state=random_state,\n",
    "            shuffle=True\n",
    "        )\n",
    "        \n",
    "        # Second split: train vs val\n",
    "        train_contracts, val_contracts = train_test_split(\n",
    "            train_val_contracts,\n",
    "            test_size=val_size/(1-test_size),  # Adjust for remaining data\n",
    "            random_state=random_state,\n",
    "            shuffle=True\n",
    "        )\n",
    "        \n",
    "        # Create clause-level splits\n",
    "        train_clauses = self.df_clauses[self.df_clauses['Filename'].isin(train_contracts)]\n",
    "        val_clauses = self.df_clauses[self.df_clauses['Filename'].isin(val_contracts)]\n",
    "        test_clauses = self.df_clauses[self.df_clauses['Filename'].isin(test_contracts)]\n",
    "        \n",
    "        self.splits = {\n",
    "            'train': {\n",
    "                'contracts': train_contracts,\n",
    "                'clauses': train_clauses,\n",
    "                'size': len(train_clauses)\n",
    "            },\n",
    "            'val': {\n",
    "                'contracts': val_contracts,\n",
    "                'clauses': val_clauses,\n",
    "                'size': len(val_clauses)\n",
    "            },\n",
    "            'test': {\n",
    "                'contracts': test_contracts,\n",
    "                'clauses': test_clauses,\n",
    "                'size': len(test_clauses)\n",
    "            }\n",
    "        }\n",
    "        \n",
    "        # Print split statistics\n",
    "        print(f\"Split Statistics:\")\n",
    "        for split_name, split_data in self.splits.items():\n",
    "            print(f\"    {split_name.upper():5}: {len(split_data['contracts']):3} contracts | {split_data['size']:5} clauses\")\n",
    "            \n",
    "            # Category distribution in this split\n",
    "            cat_dist = split_data['clauses']['Category'].value_counts()\n",
    "            print(f\"           Top categories: {', '.join(cat_dist.head(3).index.tolist())}\")\n",
    "        \n",
    "        return self.splits\n",
    "    \n",
    "    def create_stratified_cv_folds(self, n_folds=5, random_state=42):\n",
    "        \"\"\"\n",
    "        Create stratified cross-validation folds at contract level\n",
    "        \"\"\"\n",
    "        print(f\"Creating {n_folds}-fold stratified cross-validation...\")\n",
    "        \n",
    "        # Create contract-level stratification based on dominant risk category\n",
    "        contract_dominant_risk = []\n",
    "        for contract in self.df_clauses['Filename'].unique():\n",
    "            contract_clauses = self.df_clauses[self.df_clauses['Filename'] == contract]\n",
    "            dominant_category = contract_clauses['Category'].mode().iloc[0]\n",
    "            contract_dominant_risk.append({\n",
    "                'filename': contract,\n",
    "                'dominant_risk': dominant_category,\n",
    "                'clause_count': len(contract_clauses)\n",
    "            })\n",
    "        \n",
    "        contract_df = pd.DataFrame(contract_dominant_risk)\n",
    "        \n",
    "        # Encode dominant risk categories\n",
    "        le = LabelEncoder()\n",
    "        contract_df['risk_encoded'] = le.fit_transform(contract_df['dominant_risk'])\n",
    "        \n",
    "        # Create stratified folds\n",
    "        skf = StratifiedKFold(n_splits=n_folds, shuffle=True, random_state=random_state)\n",
    "        \n",
    "        cv_folds = []\n",
    "        for fold, (train_idx, val_idx) in enumerate(skf.split(contract_df['filename'], contract_df['risk_encoded'])):\n",
    "            train_contracts = contract_df.iloc[train_idx]['filename'].tolist()\n",
    "            val_contracts = contract_df.iloc[val_idx]['filename'].tolist()\n",
    "            \n",
    "            train_clauses = self.df_clauses[self.df_clauses['Filename'].isin(train_contracts)]\n",
    "            val_clauses = self.df_clauses[self.df_clauses['Filename'].isin(val_contracts)]\n",
    "            \n",
    "            cv_folds.append({\n",
    "                'fold': fold + 1,\n",
    "                'train_contracts': train_contracts,\n",
    "                'val_contracts': val_contracts,\n",
    "                'train_clauses': train_clauses,\n",
    "                'val_clauses': val_clauses,\n",
    "                'train_size': len(train_clauses),\n",
    "                'val_size': len(val_clauses)\n",
    "            })\n",
    "            \n",
    "            print(f\"  Fold {fold+1}: {len(train_contracts)} train contracts ({len(train_clauses)} clauses) | \"\n",
    "                  f\"{len(val_contracts)} val contracts ({len(val_clauses)} clauses)\")\n",
    "        \n",
    "        return cv_folds\n",
    "    \n",
    "    def prepare_legal_bert_datasets(self, processed_df: pd.DataFrame):\n",
    "        \"\"\"\n",
    "        Prepare datasets specifically for Legal-BERT training\n",
    "        \"\"\"\n",
    "        print(f\"\\n๐Ÿค– Preparing Legal-BERT training datasets...\")\n",
    "        \n",
    "        # Apply enhanced risk taxonomy mapping\n",
    "        processed_df['risk_category'] = processed_df['category'].map(enhanced_risk_taxonomy)\n",
    "        processed_df = processed_df.dropna(subset=['risk_category'])\n",
    "        \n",
    "        # Filter out metadata categories\n",
    "        processed_df = processed_df[processed_df['risk_category'] != 'METADATA']\n",
    "        \n",
    "        # Encode risk categories for classification\n",
    "        le_risk = LabelEncoder()\n",
    "        processed_df['risk_label'] = le_risk.fit_transform(processed_df['risk_category'])\n",
    "        \n",
    "        # Calculate severity scores (0-10) based on risk type and complexity\n",
    "        def calculate_severity_score(row):\n",
    "            # Base severity from risk type\n",
    "            risk_severity = {\n",
    "                'LIABILITY_RISK': 8, 'INDEMNITY_RISK': 7, 'TERMINATION_RISK': 6,\n",
    "                'IP_RISK': 6, 'COMPLIANCE_RISK': 5, 'CONFIDENTIALITY_RISK': 5,\n",
    "                'OPERATIONAL_RISK': 4\n",
    "            }\n",
    "            base_severity = risk_severity.get(row['risk_category'], 5)\n",
    "            \n",
    "            # Adjust based on complexity and entities\n",
    "            complexity_factor = (row['complexity_score'] / 10) * 2\n",
    "            entity_factor = min((row['monetary_amounts'] + row['time_periods']) * 0.5, 2)\n",
    "            \n",
    "            severity = base_severity + complexity_factor + entity_factor\n",
    "            return min(severity, 10)\n",
    "        \n",
    "        # Calculate importance scores (0-10) based on clause characteristics\n",
    "        def calculate_importance_score(row):\n",
    "            # Base importance from category\n",
    "            category_importance = {\n",
    "                'LIABILITY_RISK': 9, 'INDEMNITY_RISK': 8, 'TERMINATION_RISK': 7,\n",
    "                'IP_RISK': 6, 'COMPLIANCE_RISK': 6, 'CONFIDENTIALITY_RISK': 5,\n",
    "                'OPERATIONAL_RISK': 4\n",
    "            }\n",
    "            base_importance = category_importance.get(row['risk_category'], 5)\n",
    "            \n",
    "            # Adjust based on text characteristics\n",
    "            length_factor = min(row['word_count'] / 100, 2)  # Longer clauses may be more important\n",
    "            complexity_factor = (row['complexity_score'] / 10) * 2\n",
    "            \n",
    "            importance = base_importance + length_factor + complexity_factor\n",
    "            return min(importance, 10)\n",
    "        \n",
    "        processed_df['severity_score'] = processed_df.apply(calculate_severity_score, axis=1)\n",
    "        processed_df['importance_score'] = processed_df.apply(calculate_importance_score, axis=1)\n",
    "        \n",
    "        # Create final BERT-ready dataset\n",
    "        bert_df = pd.DataFrame({\n",
    "            'text': processed_df['processed_text'],\n",
    "            'filename': processed_df['filename'],\n",
    "            'category': processed_df['category'],\n",
    "            'risk_classification': processed_df['risk_label'],\n",
    "            'severity_regression': processed_df['severity_score'],\n",
    "            'importance_regression': processed_df['importance_score'],\n",
    "        })\n",
    "        \n",
    "        print(f\"BERT Dataset Statistics:\")\n",
    "        print(f\"Total samples: {len(bert_df)}\")\n",
    "        print(f\"Risk classes: {bert_df['risk_classification'].nunique()}\")\n",
    "        print(f\"Severity range: {bert_df['severity_regression'].min():.1f} - {bert_df['severity_regression'].max():.1f}\")\n",
    "        print(f\"Importance range: {bert_df['importance_regression'].min():.1f} - {bert_df['importance_regression'].max():.1f}\")\n",
    "        \n",
    "        return bert_df, le_risk\n",
    "\n",
    "# Initialize data splitter and process\n",
    "print(\"=== INITIALIZING LEGAL-BERT DATA SPLITTING ===\")\n",
    "data_splitter = LegalBertDataSplitter(df_clauses)\n",
    "\n",
    "# Analyze contract distribution\n",
    "contract_distribution = data_splitter.analyze_contract_distribution()\n",
    "\n",
    "# Create contract-level splits\n",
    "splits = data_splitter.create_contract_level_splits()\n",
    "\n",
    "# Create cross-validation folds\n",
    "cv_folds = data_splitter.create_stratified_cv_folds()\n",
    "\n",
    "print(f\"Week 2 Task 2 Complete: Cross-Validation Strategy\")\n",
    "print(f\"Ready for Legal-BERT training with proper data splits!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "35741a37",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ============================================================================\n",
    "# WEEK 2 - TASK 3: LEGAL-BERT ARCHITECTURE DESIGN\n",
    "# ============================================================================\n",
    "\n",
    "print(\"\\n\" + \"=\"*70)\n",
    "print(\"WEEK 2 TASK 3: LEGAL-BERT ARCHITECTURE DESIGN\")\n",
    "print(\"=\"*70)\n",
    "\n",
    "class LegalBertConfig:\n",
    "    \"\"\"Configuration class for Legal-BERT multi-task model\"\"\"\n",
    "    \n",
    "    def __init__(self):\n",
    "        # Model architecture\n",
    "        self.model_name = \"bert-base-uncased\"  # Can be upgraded to legal-specific BERT\n",
    "        self.max_sequence_length = 512\n",
    "        self.hidden_size = 768\n",
    "        self.num_attention_heads = 12\n",
    "        self.num_hidden_layers = 12\n",
    "        \n",
    "        # Task-specific configurations\n",
    "        self.num_risk_classes = 7  # Number of risk categories\n",
    "        self.severity_range = (0, 10)  # Regression range\n",
    "        self.importance_range = (0, 10)  # Regression range\n",
    "        \n",
    "        # Multi-task learning weights\n",
    "        self.task_weights = {\n",
    "            'classification': 1.0,\n",
    "            'severity': 0.8,\n",
    "            'importance': 0.6\n",
    "        }\n",
    "        \n",
    "        # Training hyperparameters\n",
    "        self.learning_rate = 2e-5\n",
    "        self.batch_size = 16\n",
    "        self.num_epochs = 5\n",
    "        self.warmup_steps = 500\n",
    "        self.weight_decay = 0.01\n",
    "        self.dropout_rate = 0.1\n",
    "\n",
    "class LegalBertMultiTask(nn.Module):\n",
    "    \"\"\"\n",
    "    Legal-BERT Multi-task Model for Contract Risk Analysis\n",
    "    \n",
    "    Tasks:\n",
    "    1. Risk classification (7 classes)\n",
    "    2. Severity regression (0-10)\n",
    "    3. Importance regression (0-10)\n",
    "    \"\"\"\n",
    "    \n",
    "    def __init__(self, config: LegalBertConfig):\n",
    "        super().__init__()\n",
    "        self.config = config\n",
    "        \n",
    "        # Load pre-trained BERT model\n",
    "        self.bert_config = BertConfig.from_pretrained(config.model_name)\n",
    "        self.bert_config.hidden_dropout_prob = config.dropout_rate\n",
    "        self.bert_config.attention_probs_dropout_prob = config.dropout_rate\n",
    "        \n",
    "        self.bert = BertModel.from_pretrained(config.model_name, config=self.bert_config)\n",
    "        \n",
    "        # Classification head for risk categories\n",
    "        self.classification_head = nn.Sequential(\n",
    "            nn.Dropout(config.dropout_rate),\n",
    "            nn.Linear(config.hidden_size, config.hidden_size // 2),\n",
    "            nn.ReLU(),\n",
    "            nn.Dropout(config.dropout_rate),\n",
    "            nn.Linear(config.hidden_size // 2, config.num_risk_classes)\n",
    "        )\n",
    "        \n",
    "        # Regression head for severity scoring\n",
    "        self.severity_head = nn.Sequential(\n",
    "            nn.Dropout(config.dropout_rate),\n",
    "            nn.Linear(config.hidden_size, config.hidden_size // 2),\n",
    "            nn.ReLU(),\n",
    "            nn.Dropout(config.dropout_rate),\n",
    "            nn.Linear(config.hidden_size // 2, 1),\n",
    "            nn.Sigmoid()  # Normalize to 0-1, then scale to 0-10\n",
    "        )\n",
    "        \n",
    "        # Regression head for importance scoring\n",
    "        self.importance_head = nn.Sequential(\n",
    "            nn.Dropout(config.dropout_rate),\n",
    "            nn.Linear(config.hidden_size, config.hidden_size // 2),\n",
    "            nn.ReLU(),\n",
    "            nn.Dropout(config.dropout_rate),\n",
    "            nn.Linear(config.hidden_size // 2, 1),\n",
    "            nn.Sigmoid()  # Normalize to 0-1, then scale to 0-10\n",
    "        )\n",
    "        \n",
    "        # Initialize weights\n",
    "        self._init_weights()\n",
    "    \n",
    "    def _init_weights(self):\n",
    "        \"\"\"Initialize weights for custom heads\"\"\"\n",
    "        for module in [self.classification_head, self.severity_head, self.importance_head]:\n",
    "            for layer in module:\n",
    "                if isinstance(layer, nn.Linear):\n",
    "                    layer.weight.data.normal_(mean=0.0, std=0.02)\n",
    "                    if layer.bias is not None:\n",
    "                        layer.bias.data.zero_()\n",
    "    \n",
    "    def forward(self, input_ids, attention_mask=None, token_type_ids=None):\n",
    "        \"\"\"Forward pass through the model\"\"\"\n",
    "        \n",
    "        # BERT encoding\n",
    "        bert_outputs = self.bert(\n",
    "            input_ids=input_ids,\n",
    "            attention_mask=attention_mask,\n",
    "            token_type_ids=token_type_ids\n",
    "        )\n",
    "        \n",
    "        # Use [CLS] token representation for classification/regression\n",
    "        pooled_output = bert_outputs.pooler_output\n",
    "        \n",
    "        # Task-specific predictions\n",
    "        classification_logits = self.classification_head(pooled_output)\n",
    "        severity_score = self.severity_head(pooled_output) * 10  # Scale to 0-10\n",
    "        importance_score = self.importance_head(pooled_output) * 10  # Scale to 0-10\n",
    "        \n",
    "        return {\n",
    "            'classification_logits': classification_logits,\n",
    "            'severity_score': severity_score.squeeze(-1),\n",
    "            'importance_score': importance_score.squeeze(-1),\n",
    "            'hidden_states': bert_outputs.hidden_states,\n",
    "            'attention_weights': bert_outputs.attentions\n",
    "        }\n",
    "\n",
    "class LegalBertDataset(Dataset):\n",
    "    \"\"\"Dataset class for Legal-BERT training\"\"\"\n",
    "    \n",
    "    def __init__(self, texts, labels, tokenizer, max_length=512):\n",
    "        self.texts = texts\n",
    "        self.labels = labels\n",
    "        self.tokenizer = tokenizer\n",
    "        self.max_length = max_length\n",
    "    \n",
    "    def __len__(self):\n",
    "        return len(self.texts)\n",
    "    \n",
    "    def __getitem__(self, idx):\n",
    "        text = str(self.texts[idx])\n",
    "        \n",
    "        # Tokenize text\n",
    "        encoding = self.tokenizer(\n",
    "            text,\n",
    "            add_special_tokens=True,\n",
    "            max_length=self.max_length,\n",
    "            padding='max_length',\n",
    "            truncation=True,\n",
    "            return_tensors='pt'\n",
    "        )\n",
    "        \n",
    "        item = {\n",
    "            'input_ids': encoding['input_ids'].squeeze(),\n",
    "            'attention_mask': encoding['attention_mask'].squeeze(),\n",
    "            'risk_classification': torch.tensor(self.labels['risk_classification'][idx], dtype=torch.long),\n",
    "            'severity_score': torch.tensor(self.labels['severity_regression'][idx], dtype=torch.float),\n",
    "            'importance_score': torch.tensor(self.labels['importance_regression'][idx], dtype=torch.float),\n",
    "        }\n",
    "        \n",
    "        return item\n",
    "\n",
    "class LegalBertTrainer:\n",
    "    \"\"\"Trainer class for Legal-BERT multi-task learning\"\"\"\n",
    "    \n",
    "    def __init__(self, config: LegalBertConfig, device='cuda'):\n",
    "        self.config = config\n",
    "        self.device = device\n",
    "        \n",
    "        # Initialize model\n",
    "        self.model = LegalBertMultiTask(config).to(device)\n",
    "        \n",
    "        # Initialize tokenizer\n",
    "        self.tokenizer = BertTokenizer.from_pretrained(config.model_name)\n",
    "        \n",
    "        # Loss functions\n",
    "        self.classification_loss = nn.CrossEntropyLoss()\n",
    "        self.regression_loss = nn.MSELoss()\n",
    "        \n",
    "        # Optimizer\n",
    "        self.optimizer = torch.optim.AdamW(\n",
    "            self.model.parameters(),\n",
    "            lr=config.learning_rate,\n",
    "            weight_decay=config.weight_decay\n",
    "        )\n",
    "        \n",
    "        # Training history\n",
    "        self.training_history = {\n",
    "            'train_loss': [],\n",
    "            'val_loss': [],\n",
    "            'classification_acc': [],\n",
    "            'severity_mae': [],\n",
    "            'importance_mae': []\n",
    "        }\n",
    "    \n",
    "    def compute_loss(self, outputs, batch):\n",
    "        \"\"\"Compute multi-task loss\"\"\"\n",
    "        \n",
    "        # Classification loss\n",
    "        classification_loss = self.classification_loss(\n",
    "            outputs['classification_logits'], \n",
    "            batch['risk_classification']\n",
    "        )\n",
    "        \n",
    "        # Severity regression loss\n",
    "        severity_loss = self.regression_loss(\n",
    "            outputs['severity_score'], \n",
    "            batch['severity_score']\n",
    "        )\n",
    "        \n",
    "        # Importance regression loss\n",
    "        importance_loss = self.regression_loss(\n",
    "            outputs['importance_score'], \n",
    "            batch['importance_score']\n",
    "        )\n",
    "        \n",
    "        # Weighted combination\n",
    "        total_loss = (\n",
    "            self.config.task_weights['classification'] * classification_loss +\n",
    "            self.config.task_weights['severity'] * severity_loss +\n",
    "            self.config.task_weights['importance'] * importance_loss\n",
    "        )\n",
    "        \n",
    "        return {\n",
    "            'total_loss': total_loss,\n",
    "            'classification_loss': classification_loss,\n",
    "            'severity_loss': severity_loss,\n",
    "            'importance_loss': importance_loss\n",
    "        }\n",
    "    \n",
    "    def train_epoch(self, train_loader):\n",
    "        \"\"\"Train for one epoch\"\"\"\n",
    "        self.model.train()\n",
    "        total_loss = 0\n",
    "        \n",
    "        for batch_idx, batch in enumerate(train_loader):\n",
    "            # Move batch to device\n",
    "            batch = {k: v.to(self.device) for k, v in batch.items()}\n",
    "            \n",
    "            # Forward pass\n",
    "            outputs = self.model(\n",
    "                input_ids=batch['input_ids'],\n",
    "                attention_mask=batch['attention_mask']\n",
    "            )\n",
    "            \n",
    "            # Compute loss\n",
    "            loss_dict = self.compute_loss(outputs, batch)\n",
    "            loss = loss_dict['total_loss']\n",
    "            \n",
    "            # Backward pass\n",
    "            self.optimizer.zero_grad()\n",
    "            loss.backward()\n",
    "            torch.nn.utils.clip_grad_norm_(self.model.parameters(), 1.0)\n",
    "            self.optimizer.step()\n",
    "            \n",
    "            total_loss += loss.item()\n",
    "            \n",
    "            if batch_idx % 100 == 0:\n",
    "                print(f\"  Batch {batch_idx}, Loss: {loss.item():.4f}\")\n",
    "        \n",
    "        return total_loss / len(train_loader)\n",
    "    \n",
    "    def create_dataloaders(self, train_dataset, val_dataset, test_dataset):\n",
    "        \"\"\"Create data loaders for training\"\"\"\n",
    "        \n",
    "        train_loader = DataLoader(\n",
    "            train_dataset, \n",
    "            batch_size=self.config.batch_size, \n",
    "            shuffle=True,\n",
    "            num_workers=2\n",
    "        )\n",
    "        \n",
    "        val_loader = DataLoader(\n",
    "            val_dataset, \n",
    "            batch_size=self.config.batch_size, \n",
    "            shuffle=False,\n",
    "            num_workers=2\n",
    "        )\n",
    "        \n",
    "        test_loader = DataLoader(\n",
    "            test_dataset, \n",
    "            batch_size=self.config.batch_size, \n",
    "            shuffle=False,\n",
    "            num_workers=2\n",
    "        )\n",
    "        \n",
    "        return train_loader, val_loader, test_loader\n",
    "    \n",
    "    def save_model(self, path: str, epoch: int):\n",
    "        \"\"\"Save model checkpoint\"\"\"\n",
    "        torch.save({\n",
    "            'epoch': epoch,\n",
    "            'model_state_dict': self.model.state_dict(),\n",
    "            'optimizer_state_dict': self.optimizer.state_dict(),\n",
    "            'config': self.config,\n",
    "            'training_history': self.training_history\n",
    "        }, path)\n",
    "        \n",
    "    def load_model(self, path: str):\n",
    "        \"\"\"Load model checkpoint\"\"\"\n",
    "        checkpoint = torch.load(path, map_location=self.device)\n",
    "        self.model.load_state_dict(checkpoint['model_state_dict'])\n",
    "        self.optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n",
    "        return checkpoint['epoch']\n",
    "\n",
    "# Initialize Legal-BERT configuration and architecture\n",
    "print(\"Initializing Legal-BERT Configuration...\")\n",
    "legal_bert_config = LegalBertConfig()\n",
    "\n",
    "print(f\"Legal-BERT Configuration:\")\n",
    "print(f\"Base model: {legal_bert_config.model_name}\")\n",
    "print(f\"Max sequence length: {legal_bert_config.max_sequence_length}\")\n",
    "print(f\"Risk classes: {legal_bert_config.num_risk_classes}\")\n",
    "print(f\"Task weights: {legal_bert_config.task_weights}\")\n",
    "print(f\"Learning rate: {legal_bert_config.learning_rate}\")\n",
    "print(f\"Batch size: {legal_bert_config.batch_size}\")\n",
    "\n",
    "# Initialize trainer (without loading actual model weights yet)\n",
    "print(f\"Initializing Legal-BERT Trainer...\")\n",
    "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
    "print(f\"Device: {device}\")\n",
    "\n",
    "# Model architecture summary\n",
    "print(f\"Legal-BERT Architecture Summary:\")\n",
    "print(f\"Input: Contract clauses (max {legal_bert_config.max_sequence_length} tokens)\")\n",
    "print(f\"Encoder: BERT-base (12 layers, 768 hidden size)\")\n",
    "print(f\"Heads: \")\n",
    "print(f\"- Classification: 7 risk categories\")\n",
    "print(f\"- Severity: Regression (0-10 scale)\")\n",
    "print(f\"- Importance: Regression (0-10 scale)\")\n",
    "print(f\"Calibration: Temperature scaling\")\n",
    "print(f\"Output: Multi-task predictions with uncertainty\")\n",
    "\n",
    "print(f\"Week 2 Task 3 Complete: Legal-BERT Architecture Design\")\n",
    "print(f\"Ready for model implementation and training!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e2e48360",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"\\n\" + \"=\"*70)\n",
    "print(\"๐Ÿ—๏ธ  WEEK 2 TASK 3: LEGAL-BERT ARCHITECTURE DESIGN\")\n",
    "print(\"=\"*70)\n",
    "\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "from transformers import BertModel, BertConfig, BertTokenizer\n",
    "from torch.utils.data import Dataset, DataLoader\n",
    "import json\n",
    "from typing import Dict, List, Tuple\n",
    "\n",
    "class LegalBertConfig:\n",
    "    \"\"\"Configuration class for Legal-BERT multi-task model\"\"\"\n",
    "    \n",
    "    def __init__(self):\n",
    "        # Base BERT configuration\n",
    "        self.model_name = 'bert-base-uncased'  # Can be upgraded to legal-specific BERT\n",
    "        self.max_sequence_length = 512\n",
    "        self.hidden_size = 768\n",
    "        self.num_attention_heads = 12\n",
    "        self.num_hidden_layers = 12\n",
    "        self.dropout_prob = 0.1\n",
    "        \n",
    "        # Task-specific configurations\n",
    "        self.num_risk_classes = 7  # Our enhanced risk taxonomy\n",
    "        self.severity_range = (0, 10)  # Regression range\n",
    "        self.importance_range = (0, 10)  # Regression range\n",
    "        \n",
    "        # Multi-task learning weights\n",
    "        self.task_weights = {\n",
    "            'classification': 1.0,\n",
    "            'severity': 0.8,\n",
    "            'importance': 0.6\n",
    "        }\n",
    "        \n",
    "        # Training configuration\n",
    "        self.learning_rate = 2e-5\n",
    "        self.batch_size = 16\n",
    "        self.num_epochs = 5\n",
    "        self.warmup_steps = 1000\n",
    "        self.max_grad_norm = 1.0\n",
    "        \n",
    "        # Calibration configuration\n",
    "        self.calibration_method = 'temperature_scaling'\n",
    "        self.calibration_validation_split = 0.2\n",
    "\n",
    "class LegalBertMultiTaskModel(nn.Module):\n",
    "    \"\"\"\n",
    "    Multi-task Legal-BERT model for:\n",
    "    1. Risk classification (7 classes)\n",
    "    2. Severity regression (0-10)\n",
    "    3. Importance regression (0-10)\n",
    "    \"\"\"\n",
    "    \n",
    "    def __init__(self, config: LegalBertConfig):\n",
    "        super(LegalBertMultiTaskModel, self).__init__()\n",
    "        self.config = config\n",
    "        \n",
    "        # Load pre-trained BERT\n",
    "        self.bert = BertModel.from_pretrained(\n",
    "            config.model_name,\n",
    "            num_labels=config.num_risk_classes,\n",
    "            output_attentions=False,\n",
    "            output_hidden_states=True  # For analysis\n",
    "        )\n",
    "        \n",
    "        # Freeze first few layers for stability\n",
    "        for param in self.bert.embeddings.parameters():\n",
    "            param.requires_grad = False\n",
    "        \n",
    "        for layer in self.bert.encoder.layer[:6]:  # Freeze first 6 layers\n",
    "            for param in layer.parameters():\n",
    "                param.requires_grad = False\n",
    "        \n",
    "        # Multi-task heads\n",
    "        self.dropout = nn.Dropout(config.dropout_prob)\n",
    "        \n",
    "        # Classification head for risk categories\n",
    "        self.classification_head = nn.Sequential(\n",
    "            nn.Linear(config.hidden_size, config.hidden_size // 2),\n",
    "            nn.ReLU(),\n",
    "            nn.Dropout(config.dropout_prob),\n",
    "            nn.Linear(config.hidden_size // 2, config.num_risk_classes)\n",
    "        )\n",
    "        \n",
    "        # Regression head for severity scoring\n",
    "        self.severity_head = nn.Sequential(\n",
    "            nn.Linear(config.hidden_size, config.hidden_size // 2),\n",
    "            nn.ReLU(),\n",
    "            nn.Dropout(config.dropout_prob),\n",
    "            nn.Linear(config.hidden_size // 2, 1),\n",
    "            nn.Sigmoid()  # Output between 0-1, then scale to 0-10\n",
    "        )\n",
    "        \n",
    "        # Regression head for importance scoring\n",
    "        self.importance_head = nn.Sequential(\n",
    "            nn.Linear(config.hidden_size, config.hidden_size // 2),\n",
    "            nn.ReLU(),\n",
    "            nn.Dropout(config.dropout_prob),\n",
    "            nn.Linear(config.hidden_size // 2, 1),\n",
    "            nn.Sigmoid()  # Output between 0-1, then scale to 0-10\n",
    "        )\n",
    "        \n",
    "        # Calibration layer for uncertainty estimation\n",
    "        self.temperature = nn.Parameter(torch.ones(1))\n",
    "        \n",
    "    def forward(self, input_ids, attention_mask, token_type_ids=None):\n",
    "        \"\"\"Forward pass through multi-task model\"\"\"\n",
    "        \n",
    "        # BERT encoding\n",
    "        outputs = self.bert(\n",
    "            input_ids=input_ids,\n",
    "            attention_mask=attention_mask,\n",
    "            token_type_ids=token_type_ids\n",
    "        )\n",
    "        \n",
    "        # Use [CLS] token representation\n",
    "        pooled_output = outputs.pooler_output\n",
    "        pooled_output = self.dropout(pooled_output)\n",
    "        \n",
    "        # Task-specific predictions\n",
    "        classification_logits = self.classification_head(pooled_output)\n",
    "        severity_score = self.severity_head(pooled_output) * 10  # Scale to 0-10\n",
    "        importance_score = self.importance_head(pooled_output) * 10  # Scale to 0-10\n",
    "        \n",
    "        # Apply temperature scaling for calibration\n",
    "        calibrated_logits = classification_logits / self.temperature\n",
    "        \n",
    "        return {\n",
    "            'classification_logits': classification_logits,\n",
    "            'calibrated_logits': calibrated_logits,\n",
    "            'severity_score': severity_score.squeeze(-1),\n",
    "            'importance_score': importance_score.squeeze(-1),\n",
    "            'hidden_states': outputs.hidden_states,\n",
    "            'pooled_output': pooled_output\n",
    "        }\n",
    "\n",
    "class LegalBertDataset(Dataset):\n",
    "    \"\"\"Dataset class for Legal-BERT multi-task training\"\"\"\n",
    "    \n",
    "    def __init__(self, data: List[Dict], tokenizer, max_length: int = 512):\n",
    "        self.data = data\n",
    "        self.tokenizer = tokenizer\n",
    "        self.max_length = max_length\n",
    "    \n",
    "    def __len__(self):\n",
    "        return len(self.data)\n",
    "    \n",
    "    def __getitem__(self, idx):\n",
    "        item = self.data[idx]\n",
    "        \n",
    "        # Tokenize text\n",
    "        encoding = self.tokenizer(\n",
    "            item['text'],\n",
    "            truncation=True,\n",
    "            padding='max_length',\n",
    "            max_length=self.max_length,\n",
    "            return_tensors='pt'\n",
    "        )\n",
    "        \n",
    "        return {\n",
    "            'input_ids': encoding['input_ids'].flatten(),\n",
    "            'attention_mask': encoding['attention_mask'].flatten(),\n",
    "            'token_type_ids': encoding.get('token_type_ids', torch.zeros_like(encoding['input_ids'])).flatten(),\n",
    "            'risk_label': torch.tensor(item['risk_classification'], dtype=torch.long),\n",
    "            'severity_score': torch.tensor(item['severity_regression'], dtype=torch.float),\n",
    "            'importance_score': torch.tensor(item['importance_regression'], dtype=torch.float),\n",
    "            'filename': item['filename'],\n",
    "            'metadata': item['metadata']\n",
    "        }\n",
    "\n",
    "class LegalBertTrainer:\n",
    "    \"\"\"Training class for Legal-BERT multi-task model\"\"\"\n",
    "    \n",
    "    def __init__(self, config: LegalBertConfig):\n",
    "        self.config = config\n",
    "        self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
    "        \n",
    "        # Initialize model\n",
    "        self.model = LegalBertMultiTaskModel(config)\n",
    "        self.model.to(self.device)\n",
    "        \n",
    "        # Initialize tokenizer\n",
    "        self.tokenizer = BertTokenizer.from_pretrained(config.model_name)\n",
    "        \n",
    "        # Loss functions\n",
    "        self.classification_loss = nn.CrossEntropyLoss()\n",
    "        self.regression_loss = nn.MSELoss()\n",
    "        \n",
    "        # Optimizer\n",
    "        self.optimizer = torch.optim.AdamW(\n",
    "            self.model.parameters(),\n",
    "            lr=config.learning_rate,\n",
    "            weight_decay=0.01\n",
    "        )\n",
    "        \n",
    "        # Training metrics\n",
    "        self.training_history = {\n",
    "            'epochs': [],\n",
    "            'train_loss': [],\n",
    "            'val_loss': [],\n",
    "            'classification_acc': [],\n",
    "            'severity_mae': [],\n",
    "            'importance_mae': []\n",
    "        }\n",
    "    \n",
    "    def multi_task_loss(self, outputs, batch):\n",
    "        \"\"\"Calculate weighted multi-task loss\"\"\"\n",
    "        \n",
    "        # Classification loss\n",
    "        clf_loss = self.classification_loss(\n",
    "            outputs['classification_logits'], \n",
    "            batch['risk_label']\n",
    "        )\n",
    "        \n",
    "        # Severity regression loss\n",
    "        severity_loss = self.regression_loss(\n",
    "            outputs['severity_score'], \n",
    "            batch['severity_score']\n",
    "        )\n",
    "        \n",
    "        # Importance regression loss\n",
    "        importance_loss = self.regression_loss(\n",
    "            outputs['importance_score'], \n",
    "            batch['importance_score']\n",
    "        )\n",
    "        \n",
    "        # Weighted combination\n",
    "        total_loss = (\n",
    "            self.config.task_weights['classification'] * clf_loss +\n",
    "            self.config.task_weights['severity'] * severity_loss +\n",
    "            self.config.task_weights['importance'] * importance_loss\n",
    "        )\n",
    "        \n",
    "        return {\n",
    "            'total_loss': total_loss,\n",
    "            'classification_loss': clf_loss,\n",
    "            'severity_loss': severity_loss,\n",
    "            'importance_loss': importance_loss\n",
    "        }\n",
    "    \n",
    "    def prepare_data_loaders(self, train_data, val_data, test_data):\n",
    "        \"\"\"Prepare PyTorch data loaders for training\"\"\"\n",
    "        \n",
    "        train_dataset = LegalBertDataset(train_data, self.tokenizer, self.config.max_sequence_length)\n",
    "        val_dataset = LegalBertDataset(val_data, self.tokenizer, self.config.max_sequence_length)\n",
    "        test_dataset = LegalBertDataset(test_data, self.tokenizer, self.config.max_sequence_length)\n",
    "        \n",
    "        train_loader = DataLoader(\n",
    "            train_dataset, \n",
    "            batch_size=self.config.batch_size, \n",
    "            shuffle=True,\n",
    "            num_workers=2\n",
    "        )\n",
    "        \n",
    "        val_loader = DataLoader(\n",
    "            val_dataset, \n",
    "            batch_size=self.config.batch_size, \n",
    "            shuffle=False,\n",
    "            num_workers=2\n",
    "        )\n",
    "        \n",
    "        test_loader = DataLoader(\n",
    "            test_dataset, \n",
    "            batch_size=self.config.batch_size, \n",
    "            shuffle=False,\n",
    "            num_workers=2\n",
    "        )\n",
    "        \n",
    "        return train_loader, val_loader, test_loader\n",
    "    \n",
    "    def save_model(self, path: str, epoch: int):\n",
    "        \"\"\"Save model checkpoint\"\"\"\n",
    "        torch.save({\n",
    "            'epoch': epoch,\n",
    "            'model_state_dict': self.model.state_dict(),\n",
    "            'optimizer_state_dict': self.optimizer.state_dict(),\n",
    "            'config': self.config,\n",
    "            'training_history': self.training_history\n",
    "        }, path)\n",
    "        \n",
    "    def load_model(self, path: str):\n",
    "        \"\"\"Load model checkpoint\"\"\"\n",
    "        checkpoint = torch.load(path, map_location=self.device)\n",
    "        self.model.load_state_dict(checkpoint['model_state_dict'])\n",
    "        self.optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n",
    "        return checkpoint['epoch']\n",
    "\n",
    "# Initialize Legal-BERT configuration and architecture\n",
    "print(\"๐Ÿ”ง Initializing Legal-BERT Configuration...\")\n",
    "legal_bert_config = LegalBertConfig()\n",
    "\n",
    "print(f\"Legal-BERT Configuration:\")\n",
    "print(f\"Base model: {legal_bert_config.model_name}\")\n",
    "print(f\"Max sequence length: {legal_bert_config.max_sequence_length}\")\n",
    "print(f\"Risk classes: {legal_bert_config.num_risk_classes}\")\n",
    "print(f\"Task weights: {legal_bert_config.task_weights}\")\n",
    "print(f\"Learning rate: {legal_bert_config.learning_rate}\")\n",
    "print(f\"Batch size: {legal_bert_config.batch_size}\")\n",
    "\n",
    "# Initialize trainer (without loading actual model weights yet)\n",
    "print(f\"Initializing Legal-BERT Trainer...\")\n",
    "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
    "print(f\"Device: {device}\")\n",
    "\n",
    "# Model architecture summary\n",
    "print(f\"Legal-BERT Architecture Summary:\")\n",
    "print(f\"Input: Contract clauses (max {legal_bert_config.max_sequence_length} tokens)\")\n",
    "print(f\"Encoder: BERT-base (12 layers, 768 hidden size)\")\n",
    "print(f\"Heads: \")\n",
    "print(f\"- Classification: 7 risk categories\")\n",
    "print(f\"- Severity: Regression (0-10 scale)\")\n",
    "print(f\"- Importance: Regression (0-10 scale)\")\n",
    "print(f\"Calibration: Temperature scaling\")\n",
    "print(f\"Output: Multi-task predictions with uncertainty\")\n",
    "\n",
    "print(f\"Week 2 Task 3 Complete: Legal-BERT Architecture Design\")\n",
    "print(f\"Ready for model implementation and training!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b6ee9f72",
   "metadata": {},
   "source": [
    "## Calibration Framework Setup\n",
    "\n",
    "Comprehensive calibration framework for Legal-BERT uncertainty quantification with multiple calibration methods including temperature scaling, Platt scaling, isotonic regression, Monte Carlo dropout, and ensemble calibration."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ef15663f",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"\\n\" + \"=\"*70)\n",
    "print(\"WEEK 2 TASK 4: CALIBRATION FRAMEWORK SETUP\")\n",
    "print(\"=\"*70)\n",
    "\n",
    "class CalibrationFramework:\n",
    "    \"\"\"\n",
    "    Comprehensive calibration framework for Legal-BERT uncertainty quantification\n",
    "    \"\"\"\n",
    "    \n",
    "    def __init__(self):\n",
    "        self.calibrators = {}\n",
    "        self.calibration_metrics = {}\n",
    "        self.temperature_params = {}\n",
    "        \n",
    "    def expected_calibration_error(self, y_true, y_prob, n_bins=10):\n",
    "        \"\"\"Calculate Expected Calibration Error (ECE)\"\"\"\n",
    "        bin_boundaries = np.linspace(0, 1, n_bins + 1)\n",
    "        bin_lowers = bin_boundaries[:-1]\n",
    "        bin_uppers = bin_boundaries[1:]\n",
    "        \n",
    "        ece = 0\n",
    "        for bin_lower, bin_upper in zip(bin_lowers, bin_uppers):\n",
    "            # Get predictions in this bin\n",
    "            in_bin = (y_prob > bin_lower) & (y_prob <= bin_upper)\n",
    "            prop_in_bin = in_bin.mean()\n",
    "            \n",
    "            if prop_in_bin > 0:\n",
    "                accuracy_in_bin = y_true[in_bin].mean()\n",
    "                avg_confidence_in_bin = y_prob[in_bin].mean()\n",
    "                ece += np.abs(avg_confidence_in_bin - accuracy_in_bin) * prop_in_bin\n",
    "        \n",
    "        return ece\n",
    "    \n",
    "    def maximum_calibration_error(self, y_true, y_prob, n_bins=10):\n",
    "        \"\"\"Calculate Maximum Calibration Error (MCE)\"\"\"\n",
    "        bin_boundaries = np.linspace(0, 1, n_bins + 1)\n",
    "        bin_lowers = bin_boundaries[:-1]\n",
    "        bin_uppers = bin_boundaries[1:]\n",
    "        \n",
    "        mce = 0\n",
    "        for bin_lower, bin_upper in zip(bin_lowers, bin_uppers):\n",
    "            in_bin = (y_prob > bin_lower) & (y_prob <= bin_upper)\n",
    "            prop_in_bin = in_bin.mean()\n",
    "            \n",
    "            if prop_in_bin > 0:\n",
    "                accuracy_in_bin = y_true[in_bin].mean()\n",
    "                avg_confidence_in_bin = y_prob[in_bin].mean()\n",
    "                mce = max(mce, np.abs(avg_confidence_in_bin - accuracy_in_bin))\n",
    "        \n",
    "        return mce\n",
    "    \n",
    "    def temperature_scaling(self, logits, labels, validation_logits=None):\n",
    "        \"\"\"\n",
    "        Temperature scaling calibration method\n",
    "        \"\"\"\n",
    "        print(\"Applying temperature scaling...\")\n",
    "        \n",
    "        # Convert to numpy if needed\n",
    "        if torch.is_tensor(logits):\n",
    "            logits = logits.detach().cpu().numpy()\n",
    "        if torch.is_tensor(labels):\n",
    "            labels = labels.detach().cpu().numpy()\n",
    "        \n",
    "        # Find optimal temperature\n",
    "        def temperature_loss(T):\n",
    "            scaled_logits = logits / T\n",
    "            scaled_probs = softmax(scaled_logits, axis=1)\n",
    "            return log_loss(labels, scaled_probs)\n",
    "        \n",
    "        # Optimize temperature\n",
    "        result = minimize_scalar(temperature_loss, bounds=(0.1, 10.0), method='bounded')\n",
    "        optimal_temp = result.x\n",
    "        \n",
    "        self.temperature_params['classification'] = optimal_temp\n",
    "        \n",
    "        # Apply to validation set if provided\n",
    "        if validation_logits is not None:\n",
    "            if torch.is_tensor(validation_logits):\n",
    "                validation_logits = validation_logits.detach().cpu().numpy()\n",
    "            calibrated_logits = validation_logits / optimal_temp\n",
    "            calibrated_probs = softmax(calibrated_logits, axis=1)\n",
    "            return calibrated_probs, optimal_temp\n",
    "        \n",
    "        return optimal_temp\n",
    "    \n",
    "    def platt_scaling(self, logits, labels):\n",
    "        \"\"\"\n",
    "        Platt scaling (sigmoid) calibration method\n",
    "        \"\"\"\n",
    "        print(\"Applying Platt scaling...\")\n",
    "        \n",
    "        # Convert to numpy if needed\n",
    "        if torch.is_tensor(logits):\n",
    "            logits = logits.detach().cpu().numpy()\n",
    "        if torch.is_tensor(labels):\n",
    "            labels = labels.detach().cpu().numpy()\n",
    "        \n",
    "        # For multi-class, apply to each class vs rest\n",
    "        calibrators = {}\n",
    "        \n",
    "        for class_idx in range(logits.shape[1]):\n",
    "            # One-vs-rest binary problem\n",
    "            binary_labels = (labels == class_idx).astype(int)\n",
    "            class_scores = logits[:, class_idx].reshape(-1, 1)\n",
    "            \n",
    "            # Fit logistic regression\n",
    "            calibrator = LogisticRegression()\n",
    "            calibrator.fit(class_scores, binary_labels)\n",
    "            calibrators[class_idx] = calibrator\n",
    "        \n",
    "        self.calibrators['platt'] = calibrators\n",
    "        return calibrators\n",
    "    \n",
    "    def isotonic_regression(self, scores, labels):\n",
    "        \"\"\"\n",
    "        Isotonic regression calibration method\n",
    "        \"\"\"\n",
    "        print(\"Applying isotonic regression...\")\n",
    "        \n",
    "        calibrator = IsotonicRegression(out_of_bounds='clip')\n",
    "        calibrator.fit(scores, labels)\n",
    "        \n",
    "        self.calibrators['isotonic'] = calibrator\n",
    "        return calibrator\n",
    "    \n",
    "    def ensemble_calibration(self, predictions_list, labels, method='average'):\n",
    "        \"\"\"\n",
    "        Ensemble-based calibration for multiple models\n",
    "        \"\"\"\n",
    "        print(f\"Applying ensemble calibration ({method})...\")\n",
    "        \n",
    "        if method == 'average':\n",
    "            ensemble_pred = np.mean(predictions_list, axis=0)\n",
    "        elif method == 'weighted':\n",
    "            # Weight by individual model calibration\n",
    "            weights = []\n",
    "            for pred in predictions_list:\n",
    "                ece = self.expected_calibration_error(labels, pred)\n",
    "                weight = 1 / (ece + 1e-8)  # Inverse ECE weighting\n",
    "                weights.append(weight)\n",
    "            \n",
    "            weights = np.array(weights) / np.sum(weights)\n",
    "            ensemble_pred = np.average(predictions_list, axis=0, weights=weights)\n",
    "        \n",
    "        return ensemble_pred\n",
    "    \n",
    "    def monte_carlo_dropout(self, model, input_data, n_samples=100):\n",
    "        \"\"\"\n",
    "        Monte Carlo Dropout for uncertainty estimation\n",
    "        \"\"\"\n",
    "        print(f\"Applying Monte Carlo Dropout ({n_samples} samples)...\")\n",
    "        \n",
    "        model.train()  # Enable dropout\n",
    "        predictions = []\n",
    "        \n",
    "        with torch.no_grad():\n",
    "            for _ in range(n_samples):\n",
    "                output = model(input_data)\n",
    "                predictions.append(output['classification_logits'].cpu().numpy())\n",
    "        \n",
    "        model.eval()  # Disable dropout\n",
    "        \n",
    "        # Calculate mean and variance\n",
    "        predictions = np.array(predictions)\n",
    "        mean_pred = np.mean(predictions, axis=0)\n",
    "        var_pred = np.var(predictions, axis=0)\n",
    "        \n",
    "        return mean_pred, var_pred\n",
    "    \n",
    "    def calibrate_regression_outputs(self, predictions, targets, method='quantile'):\n",
    "        \"\"\"\n",
    "        Calibrate regression outputs (severity and importance scores)\n",
    "        \"\"\"\n",
    "        print(f\"๐Ÿ“ Calibrating regression outputs ({method})...\")\n",
    "        \n",
    "        if method == 'quantile':\n",
    "            # Quantile-based calibration\n",
    "            def calibrate_quantile(pred, target, alpha=0.1):\n",
    "                # Calculate prediction intervals\n",
    "                lower_quantile = alpha / 2\n",
    "                upper_quantile = 1 - alpha / 2\n",
    "                \n",
    "                residuals = target - pred\n",
    "                lower_bound = np.quantile(residuals, lower_quantile)\n",
    "                upper_bound = np.quantile(residuals, upper_quantile)\n",
    "                \n",
    "                return pred + lower_bound, pred + upper_bound\n",
    "            \n",
    "            return calibrate_quantile\n",
    "        \n",
    "        elif method == 'gaussian':\n",
    "            # Gaussian process-based calibration\n",
    "            mean_residual = np.mean(targets - predictions)\n",
    "            std_residual = np.std(targets - predictions)\n",
    "            \n",
    "            calibrated_pred = predictions + mean_residual\n",
    "            uncertainty = np.full_like(predictions, std_residual)\n",
    "            \n",
    "            return calibrated_pred, uncertainty\n",
    "    \n",
    "    def evaluate_calibration(self, y_true, y_prob, task_type='classification'):\n",
    "        \"\"\"\n",
    "        Comprehensive calibration evaluation\n",
    "        \"\"\"\n",
    "        print(f\"๐Ÿ“Š Evaluating calibration for {task_type}...\")\n",
    "        \n",
    "        metrics = {}\n",
    "        \n",
    "        if task_type == 'classification':\n",
    "            # For classification\n",
    "            y_pred = np.argmax(y_prob, axis=1) if y_prob.ndim > 1 else (y_prob > 0.5).astype(int)\n",
    "            max_probs = np.max(y_prob, axis=1) if y_prob.ndim > 1 else y_prob\n",
    "            \n",
    "            metrics['accuracy'] = np.mean(y_pred == y_true)\n",
    "            metrics['ece'] = self.expected_calibration_error(y_true == y_pred, max_probs)\n",
    "            metrics['mce'] = self.maximum_calibration_error(y_true == y_pred, max_probs)\n",
    "            metrics['brier_score'] = brier_score_loss(y_true, max_probs)\n",
    "            \n",
    "        elif task_type == 'regression':\n",
    "            # For regression\n",
    "            mae = np.mean(np.abs(y_true - y_prob))\n",
    "            mse = np.mean((y_true - y_prob) ** 2)\n",
    "            \n",
    "            metrics['mae'] = mae\n",
    "            metrics['mse'] = mse\n",
    "            metrics['rmse'] = np.sqrt(mse)\n",
    "            \n",
    "            # Calculate prediction intervals coverage\n",
    "            residuals = y_true - y_prob\n",
    "            metrics['std_residuals'] = np.std(residuals)\n",
    "            metrics['mean_residuals'] = np.mean(residuals)\n",
    "        \n",
    "        return metrics\n",
    "    \n",
    "    def plot_calibration_curve(self, y_true, y_prob, n_bins=10, title=\"Calibration Curve\"):\n",
    "        \"\"\"\n",
    "        Plot calibration curve for visualization\n",
    "        \"\"\"\n",
    "        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))\n",
    "        \n",
    "        # Calibration curve\n",
    "        bin_boundaries = np.linspace(0, 1, n_bins + 1)\n",
    "        bin_lowers = bin_boundaries[:-1]\n",
    "        bin_uppers = bin_boundaries[1:]\n",
    "        \n",
    "        bin_centers = []\n",
    "        bin_accuracies = []\n",
    "        bin_sizes = []\n",
    "        \n",
    "        for bin_lower, bin_upper in zip(bin_lowers, bin_uppers):\n",
    "            in_bin = (y_prob > bin_lower) & (y_prob <= bin_upper)\n",
    "            prop_in_bin = in_bin.sum()\n",
    "            \n",
    "            if prop_in_bin > 0:\n",
    "                accuracy_in_bin = y_true[in_bin].mean()\n",
    "                avg_confidence_in_bin = y_prob[in_bin].mean()\n",
    "                \n",
    "                bin_centers.append(avg_confidence_in_bin)\n",
    "                bin_accuracies.append(accuracy_in_bin)\n",
    "                bin_sizes.append(prop_in_bin)\n",
    "        \n",
    "        # Plot calibration curve\n",
    "        ax1.plot([0, 1], [0, 1], 'k--', label='Perfect calibration')\n",
    "        ax1.scatter(bin_centers, bin_accuracies, s=bin_sizes, alpha=0.7, label='Model')\n",
    "        ax1.set_xlabel('Mean Predicted Probability')\n",
    "        ax1.set_ylabel('Fraction of Positives')\n",
    "        ax1.set_title(f'{title} - Calibration Curve')\n",
    "        ax1.legend()\n",
    "        ax1.grid(True, alpha=0.3)\n",
    "        \n",
    "        # Plot histogram of predictions\n",
    "        ax2.hist(y_prob, bins=n_bins, alpha=0.7, density=True)\n",
    "        ax2.set_xlabel('Predicted Probability')\n",
    "        ax2.set_ylabel('Density')\n",
    "        ax2.set_title(f'{title} - Prediction Distribution')\n",
    "        ax2.grid(True, alpha=0.3)\n",
    "        \n",
    "        plt.tight_layout()\n",
    "        return fig\n",
    "\n",
    "# Initialize calibration framework\n",
    "print(\"Initializing Calibration Framework...\")\n",
    "calibration_framework = CalibrationFramework()\n",
    "\n",
    "# Test calibration metrics on sample data\n",
    "print(\"Testing calibration metrics on sample data...\")\n",
    "np.random.seed(42)\n",
    "\n",
    "# Generate sample predictions and labels\n",
    "n_samples = 1000\n",
    "sample_logits = np.random.randn(n_samples, 7)  # 7 risk classes\n",
    "sample_probs = softmax(sample_logits, axis=1)\n",
    "sample_labels = np.random.randint(0, 7, n_samples)\n",
    "\n",
    "# Calculate sample calibration metrics\n",
    "max_probs = np.max(sample_probs, axis=1)\n",
    "pred_labels = np.argmax(sample_probs, axis=1)\n",
    "correct_predictions = (pred_labels == sample_labels)\n",
    "\n",
    "sample_ece = calibration_framework.expected_calibration_error(correct_predictions, max_probs)\n",
    "sample_mce = calibration_framework.maximum_calibration_error(correct_predictions, max_probs)\n",
    "\n",
    "print(f\"Sample ECE: {sample_ece:.4f}\")\n",
    "print(f\"Sample MCE: {sample_mce:.4f}\")\n",
    "print(f\"Sample Accuracy: {np.mean(correct_predictions):.4f}\")\n",
    "\n",
    "# Calibration methods available\n",
    "print(f\"Available Calibration Methods:\")\n",
    "print(f\"1. Temperature Scaling - Learns single temperature parameter\")\n",
    "print(f\"2. Platt Scaling - Sigmoid-based calibration\")\n",
    "print(f\"3. Isotonic Regression - Non-parametric calibration\")\n",
    "print(f\"4. Monte Carlo Dropout - Uncertainty via multiple forward passes\")\n",
    "print(f\"5. Ensemble Calibration - Combines multiple model predictions\")\n",
    "\n",
    "# Legal-specific calibration considerations\n",
    "print(f\"Legal-Specific Calibration Considerations:\")\n",
    "print(f\"- High-stakes decisions require well-calibrated confidence\")\n",
    "print(f\"- Different risk categories may need different calibration\")\n",
    "print(f\"- Severity and importance scores need regression calibration\")\n",
    "print(f\"- Contract-level aggregation of clause predictions\")\n",
    "print(f\"- Temporal calibration for evolving legal standards\")\n",
    "\n",
    "print(f\" Week 2 Task 4 Complete: Calibration Framework Setup\")\n",
    "print(f\"Framework ready for Legal-BERT uncertainty quantification!\")\n",
    "\n",
    "# Store calibration framework for later use\n",
    "legal_calibration = calibration_framework"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "project (3.8.10)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}