File size: 107,727 Bytes
2f6b10b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import collections
import json
import os
import pathlib
import random
import re
import shutil
import typing
from datetime import datetime

import numpy as np
import sqlalchemy
from montreal_forced_aligner import config

config.TEMPORARY_DIRECTORY = pathlib.Path(os.path.dirname(os.path.abspath(__file__)))
config.USE_POSTGRES = False
import montreal_forced_aligner.utils
from montreal_forced_aligner.data import PhoneSetType, voiced_variants, voiceless_variants
from montreal_forced_aligner.db import Phone, PhoneType, Pronunciation, Word
from montreal_forced_aligner.dictionary.multispeaker import MultispeakerDictionary
from montreal_forced_aligner.models import MODEL_TYPES

rng = np.random.default_rng(1234)
random.seed(1234)

root_dir = pathlib.Path(__file__).resolve().parent
template_dir = root_dir.joinpath("templates")

CURRENT_MODEL_VERSION = "3.3.0"

# Get corpus information

current_corpora = {
    "english": [
        "Common Voice English v8_0",
        "LibriSpeech English",
        "Corpus of Regional African American Language v2021_07",
        "Google Nigerian English",
        "Google UK and Ireland English",
        "NCHLT English",
        "ARU English corpus",
        "ICE-Nigeria",
        "A Scripted Pakistani English Daily-use Speech Corpus",
        "L2-ARCTIC",
    ],
    "czech": [
        "Common Voice Czech v9_0",
        "GlobalPhone Czech v3_1",
        "Large Corpus of Czech Parliament Plenary Hearings",
        "Czech Parliament Meetings",
    ],
    "hausa": ["Common Voice Hausa v9_0", "GlobalPhone Hausa v3_1"],
    "swahili": ["Common Voice Swahili v9_0", "ALFFA Swahili", "GlobalPhone Swahili v3_1"],
    "korean": [
        "GlobalPhone Korean v3_1",
        "Deeply Korean read speech corpus public sample",
        "Pansori TEDxKR",
        "Zeroth Korean",
        "Seoul Corpus",
        "ASR-KCSC: A Korean Conversational Speech Corpus",
        "ASR-SKDuSC: A Scripted Korean Daily-use Speech Corpus",
        "Korean Single Speaker Speech Dataset",
        "Common Voice Korean v16_1",
    ],
    "mandarin": [
        "Common Voice Chinese (China) v9_0",
        "Common Voice Chinese (Taiwan) v9_0",
        "AI-DataTang Corpus",
        "AISHELL-3",
        "THCHS-30",
        "GlobalPhone Chinese-Mandarin v3_1",
    ],
    "japanese": [
        "Common Voice Japanese v9_0",
        "GlobalPhone Japanese v3_1",
        "Microsoft Speech Language Translation Japanese",
        "Japanese Versatile Speech",
        "TEDxJP-10K v1_1",
    ],
    "thai": ["Common Voice Thai v9_0", "GlobalPhone Thai v3_1"],
    "vietnamese": ["Common Voice Vietnamese v9_0", "VIVOS", "GlobalPhone Vietnamese v3_1"],
}

model_corpus_mapping = {
    "Abkhaz CV acoustic model v2_0_0": ["Common Voice Abkhaz v7_0"],
    "Armenian CV acoustic model v2_0_0": ["Common Voice Armenian v7_0"],
    "Bashkir CV acoustic model v2_0_0": ["Common Voice Bashkir v7_0"],
    "Basque CV acoustic model v2_0_0": ["Common Voice Basque v7_0"],
    "Belarusian CV acoustic model v2_0_0": ["Common Voice Belarusian v7_0"],
    "Bulgarian CV acoustic model v2_0_0": ["Common Voice Bulgarian v7_0"],
    "Chuvash CV acoustic model v2_0_0": ["Common Voice Chuvash v7_0"],
    "Czech CV acoustic model v2_0_0": ["Common Voice Czech v7_0"],
    "Dutch CV acoustic model v2_0_0": ["Common Voice Dutch v7_0"],
    "Georgian CV acoustic model v2_0_0": ["Common Voice Georgian v7_0"],
    "Greek CV acoustic model v2_0_0": ["Common Voice Greek v7_0"],
    "Guarani CV acoustic model v2_0_0": ["Common Voice Guarani v7_0"],
    "Hausa CV acoustic model v2_0_0": ["Common Voice Hausa v7_0"],
    "Hungarian CV acoustic model v2_0_0": ["Common Voice Hungarian v7_0"],
    "Italian CV acoustic model v2_0_0": ["Common Voice Italian v7_0"],
    "Kazakh CV acoustic model v2_0_0": ["Common Voice Kazakh v7_0"],
    "Kurmanji CV acoustic model v2_0_0": ["Common Voice Kurmanji v7_0"],
    "Kyrgyz CV acoustic model v2_0_0": ["Common Voice Kyrgyz v7_0"],
    "Polish CV acoustic model v2_0_0": ["Common Voice Polish v7_0"],
    "Portuguese CV acoustic model v2_0_0": ["Common Voice Portuguese v7_0"],
    "Romanian CV acoustic model v2_0_0": ["Common Voice Romanian v7_0"],
    "Russian CV acoustic model v2_0_0": ["Common Voice Russian v7_0"],
    "Sorbian (Upper) CV acoustic model v2_0_0": ["Common Voice Sorbian Upper v7_0"],
    "Swedish CV acoustic model v2_0_0": ["Common Voice Swedish v7_0"],
    "Tamil CV acoustic model v2_0_0": ["Common Voice Tamil v7_0"],
    "Tatar CV acoustic model v2_0_0": ["Common Voice Tatar v7_0"],
    "Thai CV acoustic model v2_0_0": ["Common Voice Thai v7_0"],
    "Turkish CV acoustic model v2_0_0": ["Common Voice Turkish v7_0"],
    "Ukrainian CV acoustic model v2_0_0": ["Common Voice Ukrainian v7_0"],
    "Uyghur CV acoustic model v2_0_0": ["Common Voice Uyghur v7_0"],
    "Uzbek CV acoustic model v2_0_0": ["Common Voice Uzbek v7_0"],
    "Vietnamese CV acoustic model v2_0_0": ["Common Voice Vietnamese v7_0"],
    "English (US) ARPA acoustic model v2_0_0": ["LibriSpeech English"],
    "English (US) ARPA acoustic model v2_0_0a": ["LibriSpeech English"],
    "English (US) ARPA acoustic model v3_0_0": ["LibriSpeech English"],
    "English MFA acoustic model v2_0_0": [
        "Common Voice English v8_0",
        "LibriSpeech English",
        "Corpus of Regional African American Language v2021_07",
        "Google Nigerian English",
        "Google UK and Ireland English",
        "NCHLT English",
        "ARU English corpus",
    ],
    "English MFA acoustic model v2_0_0a": [
        "Common Voice English v8_0",
        "LibriSpeech English",
        "Corpus of Regional African American Language v2021_07",
        "Google Nigerian English",
        "Google UK and Ireland English",
        "NCHLT English",
        "ARU English corpus",
    ],
    "English MFA acoustic model v2_2_1": [
        "Common Voice English v8_0",
        "LibriSpeech English",
        "Corpus of Regional African American Language v2021_07",
        "Google Nigerian English",
        "Google UK and Ireland English",
        "NCHLT English",
        "ARU English corpus",
        "ICE-Nigeria",
        "A Scripted Pakistani English Daily-use Speech Corpus",
        "L2-ARCTIC",
    ],
    "English MFA acoustic model v3_0_0": [
        "Common Voice English v8_0",
        "LibriSpeech English",
        "Corpus of Regional African American Language v2021_07",
        "Google Nigerian English",
        "Google UK and Ireland English",
        "NCHLT English",
        "ARU English corpus",
        "ICE-Nigeria",
        "A Scripted Pakistani English Daily-use Speech Corpus",
        "L2-ARCTIC",
    ],
    "English MFA acoustic model v3_1_0": [
        "Common Voice English v17_0",
        "LibriSpeech English",
        "Corpus of Regional African American Language v2021_07",
        "Google Nigerian English",
        "Google UK and Ireland English",
        "NCHLT English",
        "ARU English corpus",
        "ICE-Nigeria",
        "A Scripted Pakistani English Daily-use Speech Corpus",
        "L2-ARCTIC",
    ],
    "English MFA ivector extractor v2_1_0": current_corpora["english"],
    "Multilingual MFA ivector extractor v2_1_0": [
        x
        for k in [
            "english",
            "czech",
            "hausa",
            "swahili",
            "thai",
            "vietnamese",
            "japanese",
            "mandarin",
        ]
        for x in current_corpora[k]
    ],
    "French MFA acoustic model v2_0_0": [
        "Common Voice French v8_0",
        "Multilingual LibriSpeech French",
        "GlobalPhone French v3_1",
        "African-accented French",
    ],
    "French MFA acoustic model v2_0_0a": [
        "Common Voice French v8_0",
        "Multilingual LibriSpeech French",
        "GlobalPhone French v3_1",
        "African-accented French",
    ],
    "French MFA acoustic model v3_0_0": [
        "Common Voice French v16_1",
        "GlobalPhone French v3_1",
        "African-accented French",
    ],
    "German MFA acoustic model v2_0_0": [
        "Common Voice German v8_0",
        "Multilingual LibriSpeech German",
        "GlobalPhone German v3_1",
    ],
    "German MFA acoustic model v3_0_0": ["Common Voice German v16_1", "GlobalPhone German v3_1"],
    "German MFA acoustic model v2_0_0a": [
        "Common Voice German v8_0",
        "Multilingual LibriSpeech German",
        "GlobalPhone German v3_1",
    ],
    "Japanese MFA acoustic model v2_0_1a": [
        "Common Voice Japanese v12_0",
        "GlobalPhone Japanese v3_1",
        "Microsoft Speech Language Translation Japanese",
        "Japanese Versatile Speech",
        "TEDxJP-10K v1_1",
    ],
    "Japanese MFA acoustic model v3_0_0": [
        "Common Voice Japanese v12_0",
        "GlobalPhone Japanese v3_1",
        "Microsoft Speech Language Translation Japanese",
        "Japanese Versatile Speech",
        "TEDxJP-10K v1_1",
    ],
    "Hausa MFA acoustic model v2_0_0": ["Common Voice Hausa v8_0", "GlobalPhone Hausa v3_1"],
    "Hausa MFA acoustic model v2_0_0a": ["Common Voice Hausa v9_0", "GlobalPhone Hausa v3_1"],
    "Hausa MFA acoustic model v3_0_0": ["Common Voice Hausa v9_0", "GlobalPhone Hausa v3_1"],
    "Mandarin MFA acoustic model v2_0_0": [
        "Common Voice Chinese (China) v8_0",
        "Common Voice Chinese (Taiwan) v8_0",
        "AI-DataTang Corpus",
        "AISHELL-3",
        "THCHS-30",
    ],
    "Mandarin MFA acoustic model v2_0_0a": [
        "Common Voice Chinese (China) v9_0",
        "Common Voice Chinese (Taiwan) v9_0",
        "AI-DataTang Corpus",
        "AISHELL-3",
        "THCHS-30",
        "GlobalPhone Chinese-Mandarin v3_1",
    ],
    "Mandarin MFA acoustic model v3_0_0": [
        "Common Voice Chinese (China) v16_1",
        "Common Voice Chinese (Taiwan) v16_1",
        "AI-DataTang Corpus",
        "AISHELL-3",
        "THCHS-30",
        "GlobalPhone Chinese-Mandarin v3_1",
    ],
    "Korean MFA acoustic model v2_0_0": [
        "GlobalPhone Korean v3_1",
        "Deeply Korean read speech corpus public sample",
        "Pansori TEDxKR",
        "Zeroth Korean",
        "Seoul Corpus",
    ],
    "Korean MFA acoustic model v2_0_0a": [
        "GlobalPhone Korean v3_1",
        "Deeply Korean read speech corpus public sample",
        "Pansori TEDxKR",
        "Zeroth Korean",
        "Seoul Corpus",
    ],
    "Korean MFA acoustic model v3_0_0": [
        "GlobalPhone Korean v3_1",
        "Deeply Korean read speech corpus public sample",
        "Pansori TEDxKR",
        "Zeroth Korean",
        "ASR-KCSC A Korean Conversational Speech Corpus",
        "ASR-SKDuSC A Scripted Korean Daily-use Speech Corpus",
        "Korean Single Speaker Speech Dataset",
        "Common Voice Korean v16_1",
    ],
    "Polish MFA acoustic model v2_0_0": [
        "Common Voice Polish v8_0",
        "Multilingual LibriSpeech Polish",
        "M-AILABS Polish",
        "GlobalPhone Polish v3_1",
    ],
    "Polish MFA acoustic model v2_0_0a": [
        "Common Voice Polish v8_0",
        "Multilingual LibriSpeech Polish",
        "M-AILABS Polish",
        "GlobalPhone Polish v3_1",
    ],
    "Portuguese MFA acoustic model v2_0_0": [
        "Common Voice Portuguese v8_0",
        "Multilingual LibriSpeech Portuguese",
        "GlobalPhone Portuguese (Brazilian) v3_1",
    ],
    "Portuguese MFA acoustic model v2_0_0a": [
        "Common Voice Portuguese v8_0",
        "Multilingual LibriSpeech Portuguese",
        "GlobalPhone Portuguese (Brazilian) v3_1",
    ],
    "Russian MFA acoustic model v2_0_0": [
        "Common Voice Russian v8_0",
        "Russian LibriSpeech",
        "M-AILABS Russian",
        "GlobalPhone Russian v3_1",
    ],
    "Russian MFA acoustic model v2_0_0a": [
        "Common Voice Russian v9_0",
        "Russian LibriSpeech",
        "M-AILABS Russian",
        "GlobalPhone Russian v3_1",
    ],
    "Russian MFA acoustic model v3_1_0": [
        "Common Voice Russian v17_0",
        "Russian LibriSpeech",
        "M-AILABS Russian",
        "Multilingual TEDx Russian",
        "GlobalPhone Russian v3_1",
    ],
    "Spanish MFA acoustic model v2_0_0": [
        "Common Voice Spanish v8_0",
        "Multilingual LibriSpeech Spanish",
        "Google i18n Chile",
        "Google i18n Columbia",
        "Google i18n Peru",
        "Google i18n Puerto Rico",
        "Google i18n Venezuela",
        "M-AILABS Spanish",
        "GlobalPhone Spanish (Latin American) v3_1",
    ],
    "Spanish MFA acoustic model v2_0_0a": [
        "Common Voice Spanish v8_0",
        "Multilingual LibriSpeech Spanish",
        "Google i18n Chile",
        "Google i18n Columbia",
        "Google i18n Peru",
        "Google i18n Puerto Rico",
        "Google i18n Venezuela",
        "M-AILABS Spanish",
        "GlobalPhone Spanish (Latin American) v3_1",
    ],
    "Spanish MFA acoustic model v3_3_0": [
        "Common Voice Spanish v8_0",
        "Multilingual LibriSpeech Spanish",
        "Google i18n Chile",
        "Google i18n Columbia",
        "Google i18n Peru",
        "Google i18n Puerto Rico",
        "Google i18n Venezuela",
        "M-AILABS Spanish",
        "GlobalPhone Spanish (Latin American) v3_1",
        "Multilingual TEDx Spanish",
    ],
    "Swahili MFA acoustic model v2_0_0": [
        "Common Voice Swahili v8_0",
        "ALFFA Swahili",
        "GlobalPhone Swahili v3_1",
    ],
    "Swahili MFA acoustic model v2_0_0a": [
        "Common Voice Swahili v9_0",
        "ALFFA Swahili",
        "GlobalPhone Swahili v3_1",
    ],
    "Swedish MFA acoustic model v2_0_0": [
        "Common Voice Swedish v8_0",
        "NST Swedish",
        "GlobalPhone Swedish v3_1",
    ],
    "Swedish MFA acoustic model v2_0_0a": [
        "Common Voice Swedish v8_0",
        "NST Swedish",
        "GlobalPhone Swedish v3_1",
    ],
    "Swedish MFA acoustic model v3_0_0": [
        "Common Voice Swedish v8_0",
        "NST Swedish",
        "GlobalPhone Swedish v3_1",
    ],
    "Thai MFA acoustic model v2_0_0": ["Common Voice Thai v8_0", "GlobalPhone Thai v3_1"],
    "Thai MFA acoustic model v2_0_0a": ["Common Voice Thai v9_0", "GlobalPhone Thai v3_1"],
    "Thai MFA acoustic model v3_0_0": [
        "Common Voice Thai v16_1",
        "GlobalPhone Thai v3_1",
        "Lotus Corpus v1_0",
        "Gowajee Corpus v0_9_3",
        "Thai Elderly Speech dataset by Data Wow and VISAI v1_0_0",
    ],
    "Bulgarian MFA acoustic model v2_0_0": [
        "Common Voice Bulgarian v8_0",
        "GlobalPhone Bulgarian v3_1",
    ],
    "Bulgarian MFA acoustic model v2_0_0a": [
        "Common Voice Bulgarian v9_0",
        "GlobalPhone Bulgarian v3_1",
    ],
    "Bulgarian MFA acoustic model v3_0_0": [
        "Common Voice Bulgarian v16_1",
        "GlobalPhone Bulgarian v3_1",
    ],
    "Croatian MFA acoustic model v2_0_0": [
        "Common Voice Serbian v8_0",
        "GlobalPhone Croatian v3_1",
    ],
    "Croatian MFA acoustic model v2_0_0a": [
        "Common Voice Serbian v9_0",
        "GlobalPhone Croatian v3_1",
    ],
    "Croatian MFA acoustic model v3_3_0": [
        "Common Voice Serbian v9_0",
        "GlobalPhone Croatian v3_1",
    ],
    "Czech MFA acoustic model v2_0_0": [
        "Common Voice Czech v8_0",
        "GlobalPhone Czech v3_1",
        "Large Corpus of Czech Parliament Plenary Hearings",
        "Czech Parliament Meetings",
    ],
    "Czech MFA acoustic model v2_0_0a": [
        "Common Voice Czech v9_0",
        "GlobalPhone Czech v3_1",
        "Large Corpus of Czech Parliament Plenary Hearings",
        "Czech Parliament Meetings",
    ],
    "Czech MFA acoustic model v3_3_0": [
        "Common Voice Czech v9_0",
        "GlobalPhone Czech v3_1",
        "Large Corpus of Czech Parliament Plenary Hearings",
        "Czech Parliament Meetings",
    ],
    "Turkish MFA acoustic model v3_0_0": [
        "Common Voice Turkish v16_1",
        "GlobalPhone Turkish v3_1",
    ],
    "Turkish MFA acoustic model v2_0_0": [
        "Common Voice Turkish v8_0",
        "MediaSpeech Turkish v1_1",
        "GlobalPhone Turkish v3_1",
    ],
    "Turkish MFA acoustic model v2_0_0a": [
        "Common Voice Turkish v8_0",
        "MediaSpeech Turkish v1_1",
        "GlobalPhone Turkish v3_1",
    ],
    "Ukrainian MFA acoustic model v2_0_0": [
        "Common Voice Ukrainian v8_0",
        "M-AILABS Ukrainian",
        "GlobalPhone Ukrainian v3_1",
    ],
    "Ukrainian MFA acoustic model v2_0_0a": [
        "Common Voice Ukrainian v9_0",
        "M-AILABS Ukrainian",
        "GlobalPhone Ukrainian v3_1",
    ],
    "Ukrainian MFA acoustic model v3_0_0": [
        "Common Voice Ukrainian v16_1",
        "M-AILABS Ukrainian",
        "GlobalPhone Ukrainian v3_1",
    ],
    "Vietnamese MFA acoustic model v2_0_0": [
        "Common Voice Vietnamese v8_0",
        "VIVOS",
        "GlobalPhone Vietnamese v3_1",
    ],
    "Vietnamese MFA acoustic model v2_0_0a": [
        "Common Voice Vietnamese v9_0",
        "VIVOS",
        "GlobalPhone Vietnamese v3_1",
    ],
    "Vietnamese MFA acoustic model v3_0_0": [
        "Common Voice Vietnamese v17_0",
        "VIVOS",
        "GlobalPhone Vietnamese v3_1",
    ],
}

model_dictionary_mapping = {
    "English MFA acoustic model v2_0_0": [
        "English (US) MFA dictionary v2_0_0",
        "English (UK) MFA dictionary v2_0_0",
        "English (Nigeria) MFA dictionary v2_0_0",
    ],
    "English MFA acoustic model v3_0_0": [
        "English (US) MFA dictionary v3_0_0",
        "English (UK) MFA dictionary v3_0_0",
        "English (Nigeria) MFA dictionary v3_0_0",
        "English (India) MFA dictionary v3_0_0",
    ],
    "English MFA acoustic model v3_1_0": [
        "English (US) MFA dictionary v3_1_0",
        "English (UK) MFA dictionary v3_1_0",
        "English (Nigeria) MFA dictionary v3_1_0",
        "English (India) MFA dictionary v3_1_0",
    ],
    "Vietnamese MFA acoustic model v2_0_0": [
        "Vietnamese (Hanoi) MFA dictionary v2_0_0",
        "Vietnamese (Ho Chi Minh City) MFA dictionary v2_0_0",
        "Vietnamese (Hue) MFA dictionary v2_0_0",
        "Vietnamese MFA dictionary v2_0_0",
    ],
    "Spanish MFA acoustic model v2_0_0": [
        "Spanish (Latin America) MFA dictionary v2_0_0",
        "Spanish (Spain) MFA dictionary v2_0_0",
        "Spanish MFA dictionary v2_0_0",
    ],
    "Spanish MFA acoustic model v3_3_0": [
        "Spanish (Latin America) MFA dictionary v3_3_0",
        "Spanish (Spain) MFA dictionary v3_3_0",
    ],
    "Portuguese MFA acoustic model v2_0_0": [
        "Portuguese (Brazil) MFA dictionary v2_0_0",
        "Portuguese (Portugal) MFA dictionary v2_0_0",
        "Portuguese MFA dictionary v2_0_0",
    ],
    "Mandarin MFA acoustic model v2_0_0": [
        "Mandarin (China) MFA dictionary v2_0_0",
        "Mandarin (Erhua) MFA dictionary v2_0_0",
        "Mandarin (Taiwan) MFA dictionary v2_0_0",
    ],
}


def make_path_safe(string):
    s = re.sub(r"[- .:()]+", "_", string.lower())
    if s.endswith("_"):
        s = s[:-1]
    return s


def get_model_card_directory(model_type, meta_data):
    model_directory = os.path.join(mfa_model_root, model_type)
    if model_type == "language_model":
        language, version = meta_data["language"], meta_data["version"]
        directory = os.path.join(model_directory, language.lower(), "mfa", f"v{version}")
    elif model_type in {"ivector", "tokenizer"}:
        language, version = meta_data["language"], meta_data["version"]
        directory = os.path.join(model_directory, language.lower(), f"v{version}")
    elif model_type == "corpus":
        language, name = meta_data["language"], meta_data["name"]
        name = make_path_safe(name)
        if "version" in meta_data:
            version = meta_data["version"]
            directory = os.path.join(model_directory, language.lower(), name, f"{version}")
        else:
            directory = os.path.join(model_directory, language.lower(), name)
    else:
        language, phone_set, dialect, version = (
            meta_data["language"],
            meta_data["phone_set"],
            meta_data["dialect"],
            meta_data["version"],
        )
        if dialect:
            phoneset_folder = f"{dialect}_{phone_set}".replace(" ", "_").lower()
        else:
            phoneset_folder = phone_set.lower()
        directory = os.path.join(model_directory, language.lower(), phoneset_folder, f"v{version}")

    return directory


mfa_model_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

OVERWRITE_METADATA = False
OVERWRITE_MD = False

mfa_citation_template = (
    "@techreport{{{id},\n\tauthor={{{extra_authors}McAuliffe, Michael and Sonderegger, Morgan}},"
    "\n\ttitle={{{title}}},"
    "\n\taddress={{\\url{{https://mfa-models.readthedocs.io/{model_type}/{language}/{link_safe_title}.html}}}},"
    "\n\tyear={{{year}}},\n\tmonth={{{month}}},"
    "\n}}"
)
cv_citation = (
    "@misc{Ahn_Chodroff_2022,\n\tauthor={Ahn, Emily and Chodroff, Eleanor},"
    "\n\ttitle={VoxCommunis Corpus},"
    "\n\taddress={\\url{https://osf.io/t957v}},"
    "\n\tpublisher={OSF},"
    "\n\tyear={2022}, \n\tmonth={Jan}\n}"
)
prosodylab_citation = (
    "@article{gorman2011prosodylab,\n\tauthor={Gorman, Kyle and Howell, Jonathan and Wagner, Michael},"
    "\n\ttitle={Prosodylab-aligner: A tool for forced alignment of laboratory speech},"
    "\n\tjournal={Canadian Acoustics},"
    "\n\tvolume={39},\n\tnumber={3},\n\tpages={192--193},\n\tyear={2011}\n}"
)

language_link_template = "[{}]({})"

license_links = {
    "CC-0": "https://creativecommons.org/publicdomain/zero/1.0/",
    "CC BY 4.0": "https://creativecommons.org/licenses/by/4.0/",
    "CC BY 3.0": "https://creativecommons.org/licenses/by/3.0/",
    "CC BY-SA-NC 3.0": "https://creativecommons.org/licenses/by-nc-sa/3.0/",
    "CC BY-NC-SA 4.0": "https://creativecommons.org/licenses/by-nc-sa/4.0/",
    "CC BY-NC-SA 3.0": "https://creativecommons.org/licenses/by-nc-sa/3.0/",
    "CC BY-NC 4.0": "https://creativecommons.org/licenses/by-nc/4.0/",
    "CC BY-SA 4.0": "https://creativecommons.org/licenses/by-sa/4.0/",
    "CC BY-NC-ND 4.0": "https://creativecommons.org/licenses/by-nc-nd/4.0/",
    "CC BY-NC 2.0": "https://creativecommons.org/licenses/by-nc/2.0/",
    "CC BY-NC-ND 3.0": "https://creativecommons.org/licenses/by-nc-nd/3.0/",
    "Microsoft Research Data License": "https://msropendata-web-api.azurewebsites.net/licenses/2f933be3-284d-500b-7ea3-2aa2fd0f1bb2/view",
    "Apache 2.0": "https://www.apache.org/licenses/LICENSE-2.0",
    "O-UDA v1.0": "https://msropendata-web-api.azurewebsites.net/licenses/f1f352a6-243f-4905-8e00-389edbca9e83/view",
    "MIT": "https://opensource.org/licenses/MIT",
    "Public domain in the USA": "https://creativecommons.org/share-your-work/public-domain/cc0/",
    "M-AILABS License": "https://www.caito.de/2019/01/the-m-ailabs-speech-dataset/",
    "ELRA": "https://www.elra.info/en/services-around-lrs/distribution/licensing/",
    "Buckeye License": "https://buckeyecorpus.osu.edu/php/registration.php",
    "LDC License": "https://www.ldc.upenn.edu/data-management/using/licensing",
    "LaboroTV Non-commercial": "https://laboro.ai/activity/column/engineer/eg-laboro-tv-corpus-jp/",
}

mfa_maintainer = "[Montreal Forced Aligner](https://montreal-forced-aligner.readthedocs.io/)"
cv_maintainer = "[Vox Communis](https://osf.io/t957v/)"

corpus_detail_template = """
   * {link}:
     * **Hours:** `{num_hours:.2f}`
     * **Speakers:** `{num_speakers:,}`
     * **Utterances:** `{num_utterances:,}`"""

g2p_training_detail_template = """
* **Words:** `{num_words:,}`
* **Phones:** `{num_phones:,}`
* **Graphemes:** `{num_graphemes:,}`"""

g2p_evaluation_detail_template = """
* **Words:** `{num_words:,}`
* **WER:** `{word_error_rate:.2f}%`
* **PER:** `{phone_error_rate:.2f}%`"""

tokenizer_training_detail_template = """
* **Utterances:** `{num_utterances:,}`
* **Graphemes:** `{num_graphemes:,}`"""

tokenizer_evaluation_detail_template = """
* **Utterances:** `{num_utterances:,}`
* **UER:** `{utterance_error_rate:.2f}%`
* **CER:** `{character_error_rate:.2f}%`"""

lm_training_detail_template = """
* **Words:** `{num_words:,}`
* **OOVs:** `{num_oovs:,}`"""

lm_evaluation_detail_template = """
* **Large model:** `{large_perplexity:.2f}`
* **Medium model:** `{medium_perplexity:.2f}`
* **Small model:** `{small_perplexity:.2f}`"""

link_template = "* {{ref}}`{}`"

see_also_template = """```{{admonition}} {model_type_name}
   {links}
   ```"""

mfa_acoustic_model_card_template = template_dir.joinpath(
    "mfa_acoustic_model_card_template.md"
).read_text("utf8")
ivector_card_template = template_dir.joinpath("ivector_card_template.md").read_text("utf8")
other_acoustic_model_card_template = template_dir.joinpath(
    "other_acoustic_model_card_template.md"
).read_text("utf8")
g2p_model_card_template = template_dir.joinpath("g2p_model_card_template.md").read_text("utf8")
language_model_card_template = template_dir.joinpath("language_model_card_template.md").read_text(
    "utf8"
)
mfa_dictionary_card_template = template_dir.joinpath("mfa_dictionary_card_template.md").read_text(
    "utf8"
)
other_dictionary_card_template = template_dir.joinpath(
    "other_dictionary_card_template.md"
).read_text("utf8")
corpus_card_template = template_dir.joinpath("corpus_card_template.md").read_text("utf8")
tokenizer_model_card_template = template_dir.joinpath(
    "tokenizer_model_card_template.md"
).read_text("utf8")


corpus_docs_md_template = template_dir.joinpath("corpus_docs_md_template.md").read_text("utf8")
acoustic_docs_md_template = template_dir.joinpath("acoustic_docs_md_template.md").read_text("utf8")
ivector_docs_md_template = template_dir.joinpath("ivector_docs_md_template.md").read_text("utf8")
g2p_docs_md_template = template_dir.joinpath("g2p_docs_md_template.md").read_text("utf8")
lm_docs_md_template = template_dir.joinpath("lm_docs_md_template.md").read_text("utf8")
tokenizer_docs_md_template = template_dir.joinpath("tokenizer_docs_md_template.md").read_text(
    "utf8"
)
mfa_dictionary_docs_md_template = template_dir.joinpath(
    "mfa_dictionary_docs_md_template.md"
).read_text("utf8")
other_dictionary_docs_md_template = template_dir.joinpath(
    "other_dictionary_docs_md_template.md"
).read_text("utf8")

language_links = {
    "Abkhaz": ("Abkhaz", "https://en.wikipedia.org/wiki/Abkhaz_language"),
    "Arabic": ("Arabic", "https://en.wikipedia.org/wiki/Arabic"),
    "Armenian": ("Armenian", "https://en.wikipedia.org/wiki/Armenian_language"),
    "Bashkir": ("Bashkir", "https://en.wikipedia.org/wiki/Bashkir_language"),
    "Basque": ("Basque", "https://en.wikipedia.org/wiki/Basque_language"),
    "Belarusian": ("Belarusian", "https://en.wikipedia.org/wiki/Belarusian_language"),
    "Bulgarian": ("Bulgarian", "https://en.wikipedia.org/wiki/Bulgarian_language"),
    "Chuvash": ("Chuvash", "https://en.wikipedia.org/wiki/Chuvash_language"),
    "Croatian": ("Serbo-Croatian", "https://en.wikipedia.org/wiki/Serbo-Croatian"),
    "Serbocroatian": ("Serbo-Croatian", "https://en.wikipedia.org/wiki/Serbo-Croatian"),
    "Czech": ("Czech", "https://en.wikipedia.org/wiki/Czech_language"),
    "Dutch": ("Dutch", "https://en.wikipedia.org/wiki/Dutch_language"),
    "English": ("English", "https://en.wikipedia.org/wiki/English_language"),
    ("English", "US"): (
        "General American English",
        "https://en.wikipedia.org/wiki/General_American_English",
    ),
    ("English", "UK"): ("British English", "https://en.wikipedia.org/wiki/British_English"),
    ("English", "Nigeria"): ("Nigerian English", "https://en.wikipedia.org/wiki/Nigerian_English"),
    ("English", "India"): ("Indian English", "Japanese tokenizer v2_1_0.md"),
    "French": ("French", "https://en.wikipedia.org/wiki/French_language"),
    "Georgian": ("Georgian", "https://en.wikipedia.org/wiki/Georgian_language"),
    "German": ("German", "https://en.wikipedia.org/wiki/German_language"),
    "Greek": ("Greek", "https://en.wikipedia.org/wiki/Greek_language"),
    "Guarani": ("Guarani", "https://en.wikipedia.org/wiki/Guarani_language"),
    "Hungarian": ("Hungarian", "https://en.wikipedia.org/wiki/Hungarian_language"),
    "Italian": ("Italian", "https://en.wikipedia.org/wiki/Italian_language"),
    "Indonesian": ("Indonesian", "https://en.wikipedia.org/wiki/Indonesian_language"),
    "Hausa": ("Hausa", "https://en.wikipedia.org/wiki/Hausa_language"),
    "Kazakh": ("Kazakh", "https://en.wikipedia.org/wiki/Kazakh_language"),
    "Kyrgyz": ("Kyrgyz", "https://en.wikipedia.org/wiki/Kyrgyz_language"),
    "Kurmanji": ("Kurmanji", "https://en.wikipedia.org/wiki/Kurmanji"),
    "Maltese": ("Maltese", "https://en.wikipedia.org/wiki/Maltese_language"),
    "Uzbek": ("Uzbek", "https://en.wikipedia.org/wiki/Uzbek_language"),
    "Uyghur": ("Uyghur", "https://en.wikipedia.org/wiki/Uyghur_language"),
    "Punjabi": ("Punjabi", "https://en.wikipedia.org/wiki/Punjabi_language"),
    "Hindi": ("Hindi", "https://en.wikipedia.org/wiki/Hindi_language"),
    "Hindi-Urdu": ("Hindi-Urdu", "https://en.wikipedia.org/wiki/Hindustani_language"),
    "Japanese": ("Japanese", "https://en.wikipedia.org/wiki/Japanese_language"),
    "Korean": ("Korean", "https://en.wikipedia.org/wiki/Korean_language"),
    "Polish": ("Polish", "https://en.wikipedia.org/wiki/Polish_language"),
    "Portuguese": ("Portuguese", "https://en.wikipedia.org/wiki/Portuguese_language"),
    ("Portuguese", "Brazil"): (
        "Brazilian Portuguese",
        "https://en.wikipedia.org/wiki/Brazilian_Portuguese",
    ),
    ("Portuguese", "Portugal"): (
        "European Portuguese",
        "https://en.wikipedia.org/wiki/European_Portuguese",
    ),
    "Romanian": ("Romanian", "https://en.wikipedia.org/wiki/Romanian_language"),
    "Russian": ("Russian", "https://en.wikipedia.org/wiki/Russian_language"),
    "Spanish": ("Spanish", "https://en.wikipedia.org/wiki/Spanish_language"),
    ("Spanish", "Latin America"): (
        "Spanish in the Americas",
        "https://en.wikipedia.org/wiki/Spanish_language_in_the_Americas",
    ),
    ("Spanish", "Spain"): (
        "Peninsular Spanish",
        "https://en.wikipedia.org/wiki/Peninsular_Spanish",
    ),
    "Swahili": ("Swahili", "https://en.wikipedia.org/wiki/Swahili_language"),
    "Swedish": ("Swedish", "https://en.wikipedia.org/wiki/Swedish_language"),
    "Tamil": ("Tamil", "https://en.wikipedia.org/wiki/Tamil_language"),
    "Tatar": ("Tatar", "https://en.wikipedia.org/wiki/Tatar_language"),
    "Thai": ("Thai", "https://en.wikipedia.org/wiki/Thai_language"),
    "Turkish": ("Turkish", "https://en.wikipedia.org/wiki/Turkish_language"),
    "Ukrainian": ("Ukrainian", "https://en.wikipedia.org/wiki/Ukrainian_language"),
    "Vietnamese": ("Vietnamese", "https://en.wikipedia.org/wiki/Vietnamese_language"),
    ("Vietnamese", "Ho Chi Minh City"): (
        "Southern Vietnamese",
        "https://en.wikipedia.org/wiki/Vietnamese_language#Language_variation",
    ),
    ("Vietnamese", "Hanoi"): (
        "Northern Vietnamese",
        "https://en.wikipedia.org/wiki/Vietnamese_language#Language_variation",
    ),
    "Sorbian": ("Sorbian", "https://en.wikipedia.org/wiki/Sorbian_languages"),
    ("Sorbian", "Upper"): (
        "Upper Sorbian",
        "https://en.wikipedia.org/wiki/Upper_Sorbian_language",
    ),
    "Mandarin": ("Mandarin Chinese", "https://en.wikipedia.org/wiki/Mandarin_Chinese"),
    ("Mandarin", "Taiwan"): (
        "Taiwanese Mandarin",
        "https://en.wikipedia.org/wiki/Taiwanese_Mandarin",
    ),
    ("Mandarin", "Erhua"): ("Beijing Mandarin", "https://en.wikipedia.org/wiki/Beijing_dialect"),
    ("Mandarin", "China"): (
        "Standard Mandarin Chinese",
        "https://en.wikipedia.org/wiki/Standard_Chinese",
    ),
    "Urdu": ("Urdu", "https://en.wikipedia.org/wiki/Urdu"),
}

cv_phone_set_mapping = {
    "abkhaz": "XPF",
    "armenian": "XPF",
    "bashkir": "XPF",
    "basque": "XPF",
    "belarusian": "XPF",
    "bulgarian": "XPF",
    "chuvash": "XPF",
    "czech": "XPF",
    "dutch": "Epitran",
    "georgian": "XPF",
    "greek": "XPF",
    "guarani": "XPF",
    "hausa": "Epitran",
    "hindi": "Epitran",
    "hungarian": "XPF",
    "indonesian": "Epitran",
    "italian": "Epitran",
    "kazakh": "Epitran",
    "kurmanji": "Epitran",
    "kyrgyz": "Epitran",
    "maltese": "Epitran",
    "polish": "Epitran",
    "punjabi": "Epitran",
    "portuguese": "Epitran",
    "romanian": "XPF",
    "russian": "Epitran",
    "sorbian_upper": "XPF",
    "sorbian": "XPF",
    "swedish": "XPF",
    "tamil": "XPF",
    "tatar": "Epitran",
    "thai": "XPF",
    "turkish": "XPF",
    "ukrainian": "XPF",
    "uyghur": "Epitran",
    "uzbek": "Epitran",
    "urdu": "Epitran",
    "vietnamese": "XPF",
}

phone_set_templates = {
    "Epitran": "[Epitran](https://github.com/dmort27/epitran)",
    "XPF": "[XPF](https://github.com/CohenPr-XPF/XPF)",
    "ARPA": "[ARPA](https://en.wikipedia.org/wiki/ARPABET)",
    "PINYIN": "[PINYIN](https://en.wikipedia.org/wiki/Pinyin)",
    "PROSODYLAB": "[PROSODYLAB](https://github.com/prosodylab/prosodylab.dictionaries)",
    "MFA": "[MFA](https://mfa-models.readthedocs.io/en/refactor/mfa_phone_set.html#{language})",
}

model_id_templates = {
    "acoustic": "{language}{dialect_title_string} {phone_set} acoustic model{version_string}",
    "dictionary": "{language}{dialect_title_string} {phone_set} dictionary{version_string}",
    "g2p": "{language}{dialect_title_string} {phone_set} G2P model{version_string}",
    "language_model": "{language}{dialect_title_string} language model{version_string}",
    "corpus": "{corpus_name}{version_string}",
    "ivector": "{language} {phone_set} ivector extractor{version_string}",
    "tokenizer": "{language} tokenizer{version_string}",
}

pronunciation_dictionaries = {}


def load_dict(dictionary_path, dict_name, phone_set_type) -> MultispeakerDictionary:
    if dict_name not in pronunciation_dictionaries:
        pronunciation_dictionaries[dict_name] = MultispeakerDictionary(
            dictionary_path, phone_set_type=phone_set_type, position_dependent_phones=False
        )
        if os.path.exists(pronunciation_dictionaries[dict_name].output_directory):
            shutil.rmtree(pronunciation_dictionaries[dict_name].output_directory)
        pronunciation_dictionaries[dict_name].dictionary_setup()
    return pronunciation_dictionaries[dict_name]


def generate_id(meta_data, model_type):
    if "dialect" in meta_data and meta_data["dialect"]:
        dialect_title_string = f' ({meta_data["dialect"]})'
    else:
        dialect_title_string = ""
    if "version" in meta_data and meta_data["version"]:
        version_string = f' v{meta_data["version"]}'
    else:
        version_string = ""
    template = model_id_templates[model_type]
    if model_type == "corpus":
        fields = {"corpus_name": meta_data["name"], "version_string": version_string}
    else:
        fields = {
            "language": meta_data["language"].title(),
            "dialect_title_string": dialect_title_string,
            "version_string": version_string,
        }
        if model_type not in {"language_model"}:
            fields["phone_set"] = meta_data["phone_set"]
        if model_type == "ivector":
            fields["phone_set"] = "MFA"
    return template.format(**fields).replace(".", "_")


def generate_meta_data(model, model_type, language, dialect, version, phone_set):
    citation_details = {
        "model_name": model.name,
        "version": version,
        "extra_authors": "",
        "model_type": model_type,
        "language": language.title(),
        "phone_set": phone_set.upper(),
    }
    citation_template = mfa_citation_template
    if language in {"Arabic"}:
        citation_details["extra_authors"] = "Shmueli, Natalia and "
    maintainer = mfa_maintainer
    if dialect:
        phone_set_folder = f"{dialect}_{phone_set}".replace(" ", "_").lower()
        citation_details["dialect"] = dialect
    else:
        phone_set_folder = phone_set.lower()
    license = "CC BY 4.0"
    license_link = f"[CC BY 4.0](https://github.com/MontrealCorpusTools/mfa-models/tree/main/{model_type}/{language.lower()}/{phone_set_folder}/v{version}/LICENSE)"
    if model_type == "acoustic":
        if model.source.name.endswith("_cv.zip"):
            citation = cv_citation
            maintainer = cv_maintainer
            license = "CC-0"
            license_link = "[CC-0](https://creativecommons.org/publicdomain/zero/1.0/)"
            train_date = "02-11-2022"
        else:
            train_date = datetime.fromisoformat(model.meta["train_date"]).date()
            citation_details["year"] = train_date.year
            citation_details["month"] = train_date.strftime("%b")
            citation_details["title"] = generate_id(citation_details, model_type).replace("_", ".")
            citation_details["link_safe_title"] = generate_id(citation_details, model_type)
            citation_details["id"] = f'mfa_{model.name}_acoustic_{citation_details["year"]}'
            citation = mfa_citation_template.format(**citation_details)
        features = "MFCC"
        if model.meta["features"].get("use_pitch", False):
            features += " + pitch"
        return {
            "name": model.name,
            "language": language.title(),
            "dialect": dialect,
            "phone_set": phone_set,
            "version": version,
            "maintainer": maintainer,
            "citation": citation,
            "license": license,
            "license_link": license_link,
            "architecture": model.meta["architecture"],
            "features": features,
            "evaluation": {},
            "decode": {},
            "train_date": str(train_date),
        }
    if model_type == "dictionary":
        train_date = datetime.today().date()
        citation_details["model_type"] = "pronunciation dictionary"
        citation_details["year"] = train_date.year
        citation_details["month"] = train_date.strftime("%b")
        citation_details["link_safe_title"] = generate_id(citation_details, model_type)
        citation_details["id"] = f"mfa_{model.name}_dictionary_{train_date.year}"
        citation_details["title"] = generate_id(citation_details, model_type).replace("_", ".")
        citation = citation_template.format(**citation_details)
        phone_set = phone_set.upper()
        if model.path.name.endswith("_cv.dict"):
            citation = cv_citation
            maintainer = cv_maintainer
            license_link = "[CC-0](https://creativecommons.org/publicdomain/zero/1.0/)"
            dictionary_phone_set = "IPA"
        elif model.path.name.endswith("_mfa.dict"):
            dictionary_phone_set = "IPA"
        else:
            if model.path.name.endswith("_prosodylab.dict") or model.path.name.endswith(
                "us_arpa.dict"
            ):
                citation = prosodylab_citation
            try:
                dictionary_phone_set = montreal_forced_aligner.data.PhoneSetType[phone_set].name
            except KeyError:
                dictionary_phone_set = "UNKNOWN"
        dictionary = load_dict(model.path, model.name, phone_set_type=dictionary_phone_set)
        word_count = len(dictionary.actual_words)
        data = {
            "name": model.name,
            "language": language.title(),
            "dialect": dialect,
            "maintainer": maintainer,
            "license_link": license_link,
            "license": license,
            "phone_set": phone_set,
            "phones": sorted(dictionary.non_silence_phones),
            "word_count": word_count,
            "train_date": str(train_date),
            "version": version,
            "citation": citation,
        }
        output_path = os.path.join(
            os.path.dirname(get_model_card_directory("dictionary", data)),
            dictionary.name + ".dict",
        )
        dictionary.export_lexicon(1, output_path)
        return data
    if model_type == "g2p":
        train_date = datetime.fromisoformat(model.meta["train_date"]).date()
        citation_details["model_type"] = "G2P model"
        citation_details["year"] = train_date.year
        citation_details["month"] = train_date.strftime("%b")
        citation_details["link_safe_title"] = generate_id(citation_details, model_type)
        citation_details["title"] = generate_id(citation_details, model_type).replace("_", ".")
        citation_details["id"] = f"mfa_{model.name}_g2p_{train_date.year}"
        return {
            "name": model.name,
            "language": language.title(),
            "dialect": dialect,
            "maintainer": maintainer,
            "license_link": license_link,
            "license": license,
            "architecture": model.meta["architecture"],
            "training": model.meta["training"],
            "evaluation": {
                k: v if v is not None else 100 for k, v in model.meta["evaluation"].items()
            },
            "phone_set": phone_set,
            "phones": sorted(model.meta["phones"]),
            "version": version,
            "train_date": str(train_date),
            "citation": citation_template.format(**citation_details),
        }
    if model_type == "language_model":
        train_date = datetime.fromisoformat(model.meta["train_date"]).date()
        citation_details["model_type"] = "language model"
        citation_details["year"] = train_date.year
        citation_details["title"] = generate_id(citation_details, model_type).replace("_", ".")
        citation_details["link_safe_title"] = generate_id(citation_details, model_type)
        citation_details["month"] = train_date.strftime("%b")
        citation_details["id"] = f"mfa_{model.name}_lm_{train_date.year}"
        return {
            "name": model.name,
            "language": language.title(),
            "dialect": dialect,
            "phone_set": "MFA",
            "maintainer": maintainer,
            "license_link": license_link,
            "license": license,
            "architecture": model.meta["architecture"],
            "version": version,
            "train_date": str(train_date),
            "training": {
                "num_words": model.meta["training"]["num_words"],
                "num_oovs": model.meta["training"]["num_oovs"],
            },
            "evaluation": {
                "large_perplexity": model.meta["evaluation_training"]["large_perplexity"],
                "medium_perplexity": model.meta["evaluation_training"]["medium_perplexity"],
                "small_perplexity": model.meta["evaluation_training"]["small_perplexity"],
            },
            "citation": citation_template.format(**citation_details),
        }
    if model_type == "tokenizer":
        train_date = datetime.fromisoformat(model.meta["train_date"]).date()
        citation_details["model_type"] = "tokenizer"
        citation_details["year"] = train_date.year
        citation_details["title"] = generate_id(citation_details, model_type).replace("_", ".")
        citation_details["link_safe_title"] = generate_id(citation_details, model_type)
        citation_details["month"] = train_date.strftime("%b")
        citation_details["id"] = f"mfa_{model.name}_tokenizer_{train_date.year}"
        return {
            "name": model.name,
            "language": language.title(),
            "dialect": dialect,
            "phone_set": "MFA",
            "maintainer": maintainer,
            "license_link": license_link,
            "license": license,
            "architecture": model.meta["architecture"],
            "version": version,
            "train_date": str(train_date),
            "training": {
                "num_utterances": model.meta["training"]["num_utterances"],
                "num_graphemes": model.meta["training"]["num_graphemes"],
            },
            "evaluation": {
                k: v if v is not None else 100 for k, v in model.meta["evaluation"].items()
            },
            "citation": citation_template.format(**citation_details),
        }
    if model_type == "ivector":
        print(model.meta)
        if "train_date" in model.meta:
            train_date = datetime.fromisoformat(model.meta["train_date"]).date()
        else:
            train_date = datetime.now().date()
        citation_details["model_type"] = "ivector"
        citation_details["year"] = train_date.year
        citation_details["title"] = generate_id(citation_details, model_type).replace("_", ".")
        citation_details["link_safe_title"] = generate_id(citation_details, model_type)
        citation_details["month"] = train_date.strftime("%b")
        citation_details["id"] = f"mfa_{model.name}_ivector_{train_date.year}"
        return {
            "name": model.name,
            "language": language.title(),
            "dialect": dialect,
            "phone_set": "MFA",
            "maintainer": maintainer,
            "license_link": license_link,
            "license": license,
            "version": version,
            "train_date": str(train_date),
            "citation": citation_template.format(**citation_details),
        }
    return {}


def extract_model_card_fields(meta_data, model_type):
    dialect_link = "N/A"
    if "dialect" in meta_data and meta_data["dialect"]:
        key = (meta_data["language"], meta_data["dialect"])
        if key in language_links:
            dialect_link = language_link_template.format(*language_links[key])
    if meta_data["language"] != "Multilingual":
        language_link = language_link_template.format(*language_links[meta_data["language"]])
    else:
        language_link = meta_data["language"]
    if "dialects" in meta_data and meta_data["dialects"]:
        dialect_links = []
        for d in meta_data["dialects"]:
            key = (meta_data["language"], d)
            if key in language_links:
                dialect_links.append(language_link_template.format(*language_links[key]))
        dialect_link = ", ".join(dialect_links)
    if "phone_set" in meta_data:
        phone_set = meta_data["phone_set"]
        if phone_set == "CV":
            phone_set = cv_phone_set_mapping[language.lower()]
        phone_set_link = phone_set_templates[phone_set]
        if phone_set == "MFA":
            phone_set_link = phone_set_link.format(language=meta_data["language"].lower())
    name = generate_id(meta_data, model_type)
    discussion_title = name.replace(" ", "+").replace(")", "").replace("(", "").replace("_", ".")
    if model_type == "acoustic":
        corpora_details = ""
        if "corpus" in meta_data:
            for corpus in meta_data["corpus"]:
                if "version" in corpus and corpus["version"]:
                    corpus_link_template = "[{name}](../../../../corpus/{language}/{corpus_safe_name}/{version}/README.md)"
                    link = corpus_link_template.format(
                        name=corpus["name"],
                        language=make_path_safe(corpus["language"]),
                        corpus_safe_name=make_path_safe(corpus["name"]),
                        version=corpus["version"],
                    )
                else:
                    corpus_link_template = (
                        "[{name}](../../../../corpus/{language}/{corpus_safe_name}/README.md)"
                    )
                    link = corpus_link_template.format(
                        name=corpus["name"],
                        language=make_path_safe(corpus["language"]),
                        corpus_safe_name=make_path_safe(corpus["name"]),
                    )

                data = {
                    "name": corpus["name"],
                    "link": link,
                    "num_hours": corpus["num_hours"],
                    "num_speakers": corpus["num_speakers"],
                    "num_utterances": corpus["num_utterances"],
                }
                corpora_details += "\n" + corpus_detail_template.format(**data)
        return {
            "model_name": meta_data["name"],
            "title": name.replace("_", "."),
            "discussion_title": discussion_title,
            "language": meta_data["language"],
            "language_link": language_link,
            "dialect": meta_data["dialect"],
            "dialect_link": dialect_link,
            "version": meta_data["version"],
            "maintainer": meta_data["maintainer"],
            "features": meta_data["features"],
            "architecture": meta_data["architecture"],
            "mfa_version": CURRENT_MODEL_VERSION,
            "date": meta_data["train_date"],
            "citation": meta_data["citation"],
            "license_link": meta_data["license_link"],
            "corpora_details": corpora_details,
            "phone_set_link": phone_set_link,
        }
    if model_type == "ivector":
        corpora_details = ""
        if "corpus" in meta_data:
            for corpus in meta_data["corpus"]:
                if "version" in corpus and corpus["version"]:
                    corpus_link_template = "[{name}](../../../corpus/{language}/{corpus_safe_name}/{version}/README.md)"
                    link = corpus_link_template.format(
                        name=corpus["name"],
                        language=make_path_safe(corpus["language"]),
                        corpus_safe_name=make_path_safe(corpus["name"]),
                        version=corpus["version"],
                    )
                else:
                    corpus_link_template = (
                        "[{name}](../../../corpus/{language}/{corpus_safe_name}/README.md)"
                    )
                    link = corpus_link_template.format(
                        name=corpus["name"],
                        language=make_path_safe(corpus["language"]),
                        corpus_safe_name=make_path_safe(corpus["name"]),
                    )

                data = {
                    "name": corpus["name"],
                    "link": link,
                    "num_hours": corpus["num_hours"],
                    "num_speakers": corpus["num_speakers"],
                    "num_utterances": corpus["num_utterances"],
                }
                corpora_details += "\n" + corpus_detail_template.format(**data)
        return {
            "model_name": meta_data["name"],
            "title": name.replace("_", "."),
            "discussion_title": discussion_title,
            "language": meta_data["language"],
            "language_link": language_link,
            "version": meta_data["version"],
            "maintainer": meta_data["maintainer"],
            "features": meta_data.get("features", "MFCC"),
            "architecture": meta_data.get("architecture", "ivector"),
            "mfa_version": CURRENT_MODEL_VERSION,
            "date": meta_data["train_date"],
            "citation": meta_data["citation"],
            "license_link": meta_data["license_link"],
            "corpora_details": corpora_details,
        }
    if model_type == "corpus":
        citation = meta_data.get("citation", "")
        version = meta_data.get("version", "")
        dialects = meta_data.get("dialects", [])
        if dialects:
            dialects = ", ".join(dialects)
        else:
            dialects = "N/A"
        if version:
            version = f"- **Version:** `{version}`"
        return {
            "corpus_name": meta_data["name"],
            "title": meta_data["id"].replace("_", "."),
            "corpus_id": meta_data["id"],
            "language": meta_data["language"],
            "language_link": language_link,
            "discussion_title": discussion_title,
            "corpus_link": f"[{meta_data['name']}]({meta_data['link']})",
            "dialects": dialects,
            "dialect_link": dialect_link,
            "num_hours": meta_data["num_hours"],
            "num_utterances": meta_data["num_utterances"],
            "num_speakers": meta_data["num_speakers"],
            "num_female": meta_data.get("num_female", 0),
            "num_male": meta_data.get("num_male", 0),
            "num_other": meta_data.get("num_other", meta_data["num_speakers"]),
            "license_link": meta_data["license_link"],
            "version": version,
            "citation": citation,
        }
    if model_type == "dictionary":
        data = {
            "model_name": meta_data["name"],
            "title": name.replace("_", "."),
            "language": meta_data["language"],
            "language_link": language_link,
            "dialect": meta_data["dialect"],
            "dialect_link": dialect_link,
            "discussion_title": discussion_title,
            "version": meta_data["version"],
            "maintainer": meta_data["maintainer"],
            "license_link": meta_data["license_link"],
            "mfa_version": CURRENT_MODEL_VERSION,
            "date": meta_data["train_date"],
            "citation": meta_data["citation"],
            "phone_set": meta_data["phone_set"],
            "phones": " ".join(sorted(meta_data["phones"])),
            "word_count": meta_data["word_count"],
            "phone_set_link": phone_set_link,
        }
        if meta_data["phone_set"] in {"MFA", "ARPA"}:
            data[
                "plain_link"
            ] = f"https://raw.githubusercontent.com/MontrealCorpusTools/mfa-models/main/dictionary/{language.lower()}/mfa/{model_name}.dict"
        return data
    if model_type == "g2p":
        training_details = g2p_training_detail_template.format(**meta_data["training"])
        evaluation_details = g2p_evaluation_detail_template.format(**meta_data["evaluation"])
        return {
            "model_name": meta_data["name"],
            "title": name.replace("_", "."),
            "language": meta_data["language"],
            "language_link": language_link,
            "dialect": meta_data["dialect"],
            "dialect_link": dialect_link,
            "discussion_title": discussion_title,
            "architecture": meta_data["architecture"],
            "maintainer": meta_data["maintainer"],
            "version": meta_data["version"],
            "license_link": meta_data["license_link"],
            "mfa_version": CURRENT_MODEL_VERSION,
            "date": meta_data["train_date"],
            "citation": meta_data["citation"],
            "phone_set": meta_data["phone_set"],
            "phones": ", ".join(f"{{ipa_inline}}`{x}`" for x in meta_data["phones"]),
            "training_details": training_details,
            "evaluation_details": evaluation_details,
            "phone_set_link": phone_set_link,
        }
    if model_type == "tokenizer":
        training_details = tokenizer_training_detail_template.format(**meta_data["training"])
        evaluation_details = tokenizer_evaluation_detail_template.format(**meta_data["evaluation"])
        return {
            "model_name": meta_data["name"],
            "title": name.replace("_", "."),
            "language": meta_data["language"],
            "language_link": language_link,
            "discussion_title": discussion_title,
            "architecture": meta_data["architecture"],
            "maintainer": meta_data["maintainer"],
            "version": meta_data["version"],
            "license_link": meta_data["license_link"],
            "mfa_version": CURRENT_MODEL_VERSION,
            "date": meta_data["train_date"],
            "citation": meta_data["citation"],
            "training_details": training_details,
            "evaluation_details": evaluation_details,
        }
    if model_type == "language_model":
        training_details = lm_training_detail_template.format(**meta_data["training"])
        evaluation_details = lm_evaluation_detail_template.format(**meta_data["evaluation"])
        return {
            "model_name": meta_data["name"],
            "title": name.replace("_", "."),
            "language": meta_data["language"],
            "language_link": language_link,
            "dialect": meta_data["dialect"],
            "dialect_link": dialect_link,
            "discussion_title": discussion_title,
            "architecture": meta_data["architecture"],
            "maintainer": meta_data["maintainer"],
            "version": meta_data["version"],
            "license_link": meta_data["license_link"],
            "mfa_version": CURRENT_MODEL_VERSION,
            "date": meta_data["train_date"],
            "citation": meta_data["citation"],
            "training_details": training_details,
            "evaluation_details": evaluation_details,
        }


def extract_doc_card_fields(meta_data, model_type):
    tags = [meta_data["language"]]
    if model_type not in {"language_model", "corpus"}:
        tags.append(meta_data["phone_set"].upper())

    see_also = ""
    links = []
    for k in ["corpus", "dictionary", "g2p", "acoustic", "language_model", "tokenizer"]:
        if k == "corpus" and model_type in {"acoustic", "ivector"}:
            continue
        if k in meta_data:
            if k == "corpus":
                links.append(
                    see_also_template.format(
                        links="\n".join(
                            link_template.format(x["id"].lower().replace(" ", "_"))
                            for x in meta_data[k]
                        ),
                        model_type_name=model_type_names[k],
                    )
                )
            else:
                print(meta_data[k])
                links.append(
                    see_also_template.format(
                        links="\n".join(
                            link_template.format(x.lower().replace(" ", "_")) for x in meta_data[k]
                        ),
                        model_type_name=model_type_names[k],
                    )
                )

    if links:
        see_also = "\n\n".join(links)
    try:
        license_link = f"[{meta_data['license']}]({license_links[meta_data['license']]})"
    except KeyError:
        license_link = meta_data["license"]
    layout_type = "not_mfa"
    if "phone_set" in meta_data:
        phone_set = meta_data["phone_set"]
        if phone_set == "CV":
            phone_set = cv_phone_set_mapping[meta_data["language"].lower()]
        elif phone_set in {"MFA", "ARPA", "PROSODYLAB"}:
            layout_type = "mfa"
        try:
            phone_set_link = phone_set_templates[phone_set]
            if phone_set == "MFA":
                phone_set_link = phone_set_link.format(language=meta_data["language"].lower())
        except KeyError:
            phone_set_link = phone_set
        if "dialect" in meta_data and meta_data["dialect"]:
            language_sub_folder = f"{meta_data['dialect']}_{meta_data['phone_set']}".replace(
                " ", "_"
            ).lower()
            dialect_title_string = f" ({meta_data['dialect']})"
        else:
            language_sub_folder = meta_data["phone_set"].lower()
            dialect_title_string = ""
    name = generate_id(meta_data, model_type)
    if model_type == "acoustic":
        corpora_details = ""
        corpus_link_template = "{{ref}}`{corpus_id}`"
        dialects = []
        if "corpus" in meta_data:
            for corpus in meta_data["corpus"]:
                if "dialects" in corpus:
                    dialects.extend(corpus["dialects"])
                data = {
                    "name": corpus["name"],
                    "link": corpus_link_template.format(corpus_id=corpus["id"].replace(" ", "_")),
                    "num_hours": corpus["num_hours"],
                    "num_speakers": corpus["num_speakers"],
                    "num_utterances": corpus["num_utterances"],
                }
                corpora_details += "\n" + corpus_detail_template.format(**data)
        if not dialects and "dialect" in meta_data and meta_data["dialect"]:
            dialects = [meta_data["dialect"]]
        if meta_data["phone_set"] in {"CV", "MFA"}:
            tags.append("IPA")
        return {
            "model_name": name,
            "ref": name.replace(" ", "_"),
            "title": name.replace("_", "."),
            "model_type": model_type,
            "architecture": meta_data["architecture"],
            "version": meta_data["version"],
            "corpora_details": corpora_details,
            "see_also": see_also,
            "tags": ";".join(tags),
            "dialects": ";".join(sorted(set(dialects))) if dialects else "N/A",
            "language": meta_data["language"].lower(),
            "language_name": meta_data["language"].title(),
            "license": meta_data["license"],
            "phone_set": phone_set,
            "layout_type": layout_type,
            "license_link": license_link,
            "phone_set_link": phone_set_link,
            "dialect_title_string": dialect_title_string,
            "language_sub_folder": language_sub_folder,
            "phone_set_name": meta_data["phone_set"].upper(),
        }
    if model_type == "ivector":
        corpora_details = ""
        corpus_link_template = "{{ref}}`{corpus_id}`"
        if "corpus" in meta_data:
            for corpus in meta_data["corpus"]:
                data = {
                    "name": corpus["name"],
                    "link": corpus_link_template.format(corpus_id=corpus["id"].replace(" ", "_")),
                    "num_hours": corpus["num_hours"],
                    "num_speakers": corpus["num_speakers"],
                    "num_utterances": corpus["num_utterances"],
                }
                corpora_details += "\n" + corpus_detail_template.format(**data)
        return {
            "model_name": name,
            "ref": name.replace(" ", "_"),
            "title": name.replace("_", "."),
            "model_type": model_type,
            "architecture": meta_data.get("architecture", "ivector"),
            "version": meta_data["version"],
            "corpora_details": corpora_details,
            "see_also": see_also,
            "tags": ";".join(tags),
            "language": meta_data["language"].lower(),
            "language_name": meta_data["language"].title(),
            "license": meta_data["license"],
            "layout_type": layout_type,
            "license_link": license_link,
        }
    if model_type == "corpus":
        if "tags" in meta_data:
            tags.extend(meta_data["tags"])
        dialects = []
        if "dialects" in meta_data:
            dialects = meta_data["dialects"]
        version_subdirectory = meta_data.get("version", "")
        if version_subdirectory:
            version_subdirectory = f"/{version_subdirectory}"
        return {
            "corpus_id": name,
            "ref": name.replace(" ", "_"),
            "title": name.replace("_", "."),
            "corpus_name": meta_data["name"],
            "corpus_name_safe": make_path_safe(meta_data["name"]),
            "license": meta_data["license"],
            "see_also": see_also,
            "layout_type": layout_type,
            "tags": ";".join(tags),
            "version_subdirectory": version_subdirectory,
            "language": meta_data["language"].lower(),
            "dialects": ";".join(sorted(set(dialects))) if dialects else "N/A",
            "language_name": meta_data["language"].title(),
        }
    if model_type == "dictionary":
        if meta_data["name"].endswith("_cv") or meta_data["name"].endswith("_mfa"):
            tags.append("IPA")
        elif meta_data["name"].endswith("_prosodylab") or meta_data["name"].endswith("us_arpa"):
            tags.append("PROSODYLAB")
            tags.append("MFA")
        data = {
            "model_name": name,
            "ref": name.replace(" ", "_"),
            "title": name.replace("_", "."),
            "model_type": model_type,
            "version": meta_data["version"],
            "see_also": see_also,
            "tags": ";".join(tags),
            "layout_type": layout_type,
            "language": meta_data["language"].lower(),
            "license": meta_data["license"],
            "language_name": meta_data["language"].title(),
            "dialects": meta_data["dialect"] if meta_data["dialect"] else "N/A",
            "phone_set": phone_set,
            "language_sub_folder": language_sub_folder,
            "dialect_title_string": dialect_title_string,
            "phone_set_name": meta_data["phone_set"].upper(),
        }
        if meta_data["name"] in phone_charts:
            charts = phone_charts[meta_data["name"]]
            data["consonant_chart"] = charts["consonant_chart"]
            data["vowel_section"] = charts["oral_vowel_chart"]
            if charts["nasal_vowel_chart"]:
                data["vowel_section"] = "#### Oral Vowels\n\n" + data["vowel_section"]
                data["vowel_section"] += "\n\n#### Nasal Vowels\n\n" + charts["nasal_vowel_chart"]
            if charts["diphthongs"]:
                data["vowel_section"] += "\n\n#### Diphthongs\n\n* " + "\n* ".join(
                    f"{{ipa_inline}}`{x}`" for x in sorted(charts["diphthongs"])
                )
            if charts["triphthongs"]:
                data["vowel_section"] += "\n\n#### Triphthongs\n\n* " + "\n* ".join(
                    f"{{ipa_inline}}`{x}`" for x in sorted(charts["triphthongs"])
                )
            if "tones" in charts and charts["tones"]:
                data["vowel_section"] += "\n\n#### Tones\n\n* " + "\n* ".join(
                    f"{{ipa_inline}}`{x}`" for x in sorted(charts["tones"])
                )
            if "stress" in charts and charts["stress"]:
                data["vowel_section"] += "\n\n#### Stress\n\n* " + "\n* ".join(
                    f"{{ipa_inline}}`{x}`" for x in sorted(charts["stress"])
                )
            if "other" in charts and charts["other"]:
                data["vowel_section"] += "\n\n### Other phones\n\n* " + "\n* ".join(
                    f"{{ipa_inline}}`{x}`" for x in sorted(charts["other"])
                )

        return data
    if model_type == "g2p":
        if meta_data["phone_set"] in {"CV", "MFA"}:
            tags.append("IPA")
        return {
            "model_name": name,
            "ref": name.replace(" ", "_"),
            "title": name.replace("_", "."),
            "model_type": model_type,
            "architecture": meta_data["architecture"],
            "version": meta_data["version"],
            "see_also": see_also,
            "layout_type": layout_type,
            "language_sub_folder": language_sub_folder,
            "dialect_title_string": dialect_title_string,
            "tags": ";".join(tags),
            "license": meta_data["license"],
            "language": meta_data["language"].lower(),
            "dialects": meta_data["dialect"] if meta_data["dialect"] else "N/A",
            "language_name": meta_data["language"].title(),
            "phone_set": phone_set,
            "phone_set_name": meta_data["phone_set"].upper(),
        }
    if model_type == "language_model":
        tags = ["MFA"]
        return {
            "model_name": name,
            "ref": name.replace(" ", "_"),
            "title": name.replace("_", "."),
            "model_type": model_type,
            "layout_type": layout_type,
            "language": meta_data["language"].lower(),
            "dialects": meta_data["dialect"] if meta_data["dialect"] else "N/A",
            "architecture": meta_data["architecture"],
            "language_name": meta_data["language"].title(),
            "dialect_title_string": dialect_title_string,
            "license": meta_data["license"],
            "version": meta_data["version"],
            "source": "mfa",
            "see_also": see_also,
            "tags": ";".join(tags),
        }
    if model_type == "tokenizer":
        tags = ["MFA"]
        return {
            "model_name": name,
            "ref": name.replace(" ", "_"),
            "title": name.replace("_", "."),
            "model_type": model_type,
            "layout_type": layout_type,
            "language": meta_data["language"].lower(),
            "architecture": meta_data["architecture"],
            "language_name": meta_data["language"].title(),
            "license": meta_data["license"],
            "version": meta_data["version"],
            "source": "mfa",
            "see_also": see_also,
            "tags": ";".join(tags),
        }


model_card_templates = {
    "acoustic": {
        "mfa": mfa_acoustic_model_card_template,
        "other": other_acoustic_model_card_template,
    },
    "dictionary": {"mfa": mfa_dictionary_card_template, "other": other_dictionary_card_template},
    "g2p": {"mfa": g2p_model_card_template, "other": g2p_model_card_template},
    "language_model": {"mfa": language_model_card_template, "other": language_model_card_template},
    "corpus": {"mfa": corpus_card_template, "other": corpus_card_template},
    "ivector": {"mfa": ivector_card_template, "other": ivector_card_template},
    "tokenizer": {"mfa": tokenizer_model_card_template, "other": tokenizer_model_card_template},
}
docs_card_templates = {
    "acoustic": {"mfa": acoustic_docs_md_template, "other": acoustic_docs_md_template},
    "dictionary": {
        "mfa": mfa_dictionary_docs_md_template,
        "other": other_dictionary_docs_md_template,
    },
    "g2p": {"mfa": g2p_docs_md_template, "other": g2p_docs_md_template},
    "language_model": {"mfa": lm_docs_md_template, "other": lm_docs_md_template},
    "corpus": {"mfa": corpus_docs_md_template, "other": corpus_docs_md_template},
    "ivector": {"mfa": ivector_docs_md_template, "other": ivector_docs_md_template},
    "tokenizer": {"mfa": tokenizer_docs_md_template, "other": tokenizer_docs_md_template},
}
model_type_names = {
    "acoustic": "Acoustic models",
    "dictionary": "Pronunciation dictionaries",
    "g2p": "G2P models",
    "language_model": "Language models",
    "corpus": "Corpora",
    "ivector": "Ivector extractors",
    "tokenizer": "Tokenizer models",
}
model_type_columns = {
    "acoustic": "ID;language;dialect;phoneset;license",
    "ivector": "ID;language;license",
    "dictionary": "ID;language;dialect;phoneset;license",
    "g2p": "ID;language;dialect;phoneset;license",
    "language_model": "ID;language;dialect;license",
    "corpus": "ID;language;dialect;license",
    "tokenizer": "ID;language;license",
}
model_type_column_widths = {
    "acoustic": "40;20;20;10;10",
    "dictionary": "40;20;20;10;10",
    "g2p": "40;20;20;10;10",
    "language_model": "50;20;20;10",
    "ivector": "50;25;25",
    "tokenizer": "50;25;25",
    "corpus": "40;20;25;15",
}

meta_datas = {}

chart_template = """``````{{list-table}}
:header-rows: 1
:stub-columns: {stub_column_count}
:class: {type}_chart table-striped table-bordered

* - {header_data}
* - {row_data}
``````
"""


def generate_extra_data(dictionary, base_indent):
    lines = []
    for key, value in dictionary.items():
        if isinstance(value, dict):
            lines.append(f"{base_indent}* {key}")
            if len(value) > 4:
                value = {k: value[k] for k in rng.choice(list(value.keys()), 4, replace=False)}
            lines.extend(generate_extra_data(value, base_indent="  " + base_indent))
        else:
            lines.append(f"{base_indent}* {key}: {value}")
    return lines


def format_ipa_cell(
    phone_data: dict[str, list[str]],
    extra_data: dict[str, dict[str, typing.Any]] = None,
    base_indent: typing.Optional[str] = "",
) -> str:
    cell_lines = [f"```{{ipa_cell}}"]
    for phone_class, v in phone_data.items():
        if not v:
            continue
        cell_lines.append(f"{base_indent}* {phone_class}")
        for phone in v:
            cell_lines.append(f"{base_indent}  * {phone}")
            if phone in extra_data:
                cell_lines.extend(
                    generate_extra_data(extra_data[phone], base_indent=base_indent + "    ")
                )
    cell_lines.append(f"{base_indent}```")
    cell_content = "\n".join(cell_lines)
    return cell_content


def check_phone(phone, feature_set, phone_set_type):
    if phone_set_type is PhoneSetType.ARPA:
        return phone in feature_set
    else:
        return any(x in phone for x in feature_set)


def analyze_dictionary(dictionary_path, name, phone_set_type):
    d = load_dict(dictionary_path, name, phone_set_type=phone_set_type)
    dictionary_mapping = collections.defaultdict(set)
    if d.phone_set_type is PhoneSetType.ARPA:
        super_segmentals = {"stress": re.compile(r"[0-2]+")}
        ipa_mapping = {
            "stops": d.phone_set_type.stops,
            "voiced": d.phone_set_type.voiced_obstruents,
            "voiceless": d.phone_set_type.voiceless_obstruents,
            "fricative": d.phone_set_type.fricatives,
            "affricates": d.phone_set_type.affricates,
            "sibilant": d.phone_set_type.sibilants,
            "lateral": d.phone_set_type.laterals,
            "nasal": d.phone_set_type.nasals,
            "approximant": d.phone_set_type.approximants,
            "labial": d.phone_set_type.labials,
            "labiodental": d.phone_set_type.labiodental,
            "dental": d.phone_set_type.dental,
            "alveolar": d.phone_set_type.alveolar,
            "alveopalatal": d.phone_set_type.alveopalatal,
            "velar": d.phone_set_type.velar,
            "glottal": d.phone_set_type.glottal,
            "implosive": set(),
            "lateral_tap": set(),
            "tap": set(),
            "palatal": d.phone_set_type.palatal,
            "trill": set(),
            "pharyngeal": set(),
            "epiglottal": set(),
            "uvular": set(),
            "retroflex": set(),
            "lateral_fricative": set(),
            "close": d.phone_set_type.close_vowels,
            "close-mid": d.phone_set_type.close_mid_vowels,
            "open-mid": d.phone_set_type.open_mid_vowels,
            "open": d.phone_set_type.open_vowels,
            "front": d.phone_set_type.front_vowels - {"IH"},
            "near-front": {"IH"},
            "central": d.phone_set_type.central_vowels,
            "back": d.phone_set_type.back_vowels - {"UH"},
            "near-back": {"UH"},
            "rounded": d.phone_set_type.rounded_vowels,
            "unrounded": d.phone_set_type.unrounded_vowels,
            "lax": {"IH", "UH", "AH", "AE", "ER"},
            "other": set(),
        }
    else:
        ipa_mapping = {
            "stops": d.phone_set_type.stops,
            "voiced": d.phone_set_type.voiced_obstruents,
            "voiceless": d.phone_set_type.voiceless_obstruents,
            "implosive": d.phone_set_type.implosive_obstruents,
            "fricative": d.phone_set_type.fricatives,
            "sibilant": d.phone_set_type.sibilants,
            "lateral": d.phone_set_type.laterals,
            "lateral_fricative": d.phone_set_type.lateral_fricatives,
            "nasal": d.phone_set_type.nasals,
            "nasal_approximants": d.phone_set_type.nasal_approximants,
            "trill": d.phone_set_type.trills,
            "tap": d.phone_set_type.taps,
            "lateral_tap": d.phone_set_type.lateral_taps,
            "approximant": d.phone_set_type.approximants - d.phone_set_type.nasal_approximants,
            "labial": d.phone_set_type.labials,
            "labiodental": d.phone_set_type.labiodental,
            "dental": d.phone_set_type.dental,
            "alveolar": d.phone_set_type.alveolar,
            "retroflex": d.phone_set_type.retroflex,
            "alveopalatal": d.phone_set_type.alveopalatal,
            "palatal": d.phone_set_type.palatal,
            "velar": d.phone_set_type.velar,
            "uvular": d.phone_set_type.uvular,
            "pharyngeal": d.phone_set_type.pharyngeal,
            "epiglottal": d.phone_set_type.epiglottal,
            "glottal": d.phone_set_type.glottal,
            "close": d.phone_set_type.close_vowels,
            "close-mid": d.phone_set_type.close_mid_vowels,
            "open-mid": d.phone_set_type.open_mid_vowels,
            "open": d.phone_set_type.open_vowels,
            "front": d.phone_set_type.front_vowels - {"ɪ", "ʏ", "ɛ̈", "ʏ̈"},
            "near-front": {"ɪ", "ʏ", "ɛ̈", "ʏ̈"},
            "central": d.phone_set_type.central_vowels,
            "back": d.phone_set_type.back_vowels - {"ʊ", "ɔ̈"},
            "near-back": {"ʊ", "ɔ̈"},
            "rounded": d.phone_set_type.rounded_vowels,
            "unrounded": d.phone_set_type.unrounded_vowels,
            "lax": {"ɪ", "ʏ", "ʊ", "ə", "ɐ", "æ", "ɚ"},
            "nasalized": {"ã", "õ", "ĩ", "ũ", "ẽ"},
            "other": {"kp", "ɧ", "ŋm"},
        }
        super_segmentals = {"tones": re.compile(r"[˩˨˧˦˥ˀ]+")}
        for k, v in ipa_mapping.items():
            voiceless = [x for x in v if x in ipa_mapping["voiceless"]]
            voiced = [x for x in v if x not in ipa_mapping["voiceless"]]
            mod_phones = set()
            for p in voiceless:
                mod_phones |= voiceless_variants(p)
            for p in voiced:
                mod_phones |= voiced_variants(p)
            ipa_mapping[k] = mod_phones | v
    extra_data = {}
    with d.session() as session:
        phones = session.query(Phone).filter(Phone.phone_type == PhoneType.non_silence)
        phone_counts = collections.Counter()
        pronunciations = session.query(Pronunciation.pronunciation)
        for (p,) in pronunciations:
            p = p.split()
            phone_counts.update(p)

    total_phones = set()
    triphthongs = d.phone_set_type.triphthong_phones
    diphthongs = d.phone_set_type.diphthong_phones
    for phone in phones:
        words = (
            session.query(Word.word, Pronunciation.pronunciation)
            .join(Word.pronunciations)
            .filter(
                sqlalchemy.func.length(Word.word) > 2,
                sqlalchemy.func.length(Word.word) < 6,
                Pronunciation.probability != None,  # noqa
                Pronunciation.pronunciation.regexp_match(rf"\b{phone.phone}(?=\s|$)"),
            )
            .distinct()
            .order_by(sqlalchemy.func.random())
            .limit(4)
        )
        for super_seg, pattern in super_segmentals.items():
            phone_m = pattern.search(phone.phone)
            if phone_m:
                dictionary_mapping[super_seg].add(phone_m.group(0))
                counts = phone_counts[phone.phone]
                examples = {}
                for w, pron in words:
                    examples[w] = f"[{pron}]"
                phone = phone.phone.replace(phone_m.group(0), "")
                if phone not in extra_data:
                    extra_data[phone] = {"Occurrences": 0, "Examples": {}}
                if isinstance(extra_data[phone]["Occurrences"], str):
                    try:
                        extra_data[phone]["Occurrences"] = int(extra_data[phone]["Occurrences"])
                    except ValueError:
                        extra_data[phone]["Occurrences"] = 0
                extra_data[phone]["Occurrences"] += counts
                extra_data[phone]["Examples"].update(examples)
                break
        else:
            extra_data[phone.phone] = {"Occurrences": phone_counts[phone.phone], "Examples": {}}
            phone = phone.phone
            for w, pron in words:
                extra_data[phone]["Examples"][w] = f"[{pron}]"
        base_phone = d.get_base_phone(phone)
        query_set = {phone, base_phone}
        if base_phone in ipa_mapping["other"]:
            dictionary_mapping["other"].add(phone)
            continue
        if "ʲ" in phone:
            dictionary_mapping["palatalized"].add(phone)
        if "ʷ" in phone:
            dictionary_mapping["labialized"].add(phone)
        if "̃" in phone:
            dictionary_mapping["nasalized"].add(phone)
            base_phone = base_phone.replace("̃", "")
        if "͈" in phone:
            dictionary_mapping["tense"].add(phone)
            dictionary_mapping["voiceless"].add(phone)
        if "̪" in phone:
            dictionary_mapping["dental"].add(phone)
        if any(x in phone for x in ["ⁿ", "ᵑ", "ᵐ"]):
            dictionary_mapping["prenasalized"].add(phone)
            dictionary_mapping["voiced"].add(phone)
        elif "ʱ" in phone or "̤" in phone:
            dictionary_mapping["aspirated"].add(phone)
            dictionary_mapping["voiced"].add(phone)
        elif check_phone(phone, ipa_mapping["voiced"], d.phone_set_type):
            dictionary_mapping["voiced"].add(phone)
        elif check_phone(phone, ipa_mapping["implosive"], d.phone_set_type):
            dictionary_mapping["implosive"].add(phone)
            dictionary_mapping["voiced"].add(phone)
        elif "ʰ" in phone:
            dictionary_mapping["aspirated"].add(phone)
            dictionary_mapping["voiceless"].add(phone)
        elif "ʼ" in phone:
            dictionary_mapping["ejective"].add(phone)
            dictionary_mapping["voiceless"].add(phone)
        elif check_phone(phone, ipa_mapping["voiceless"], d.phone_set_type):
            dictionary_mapping["voiceless"].add(phone)
        if "̚" in phone:
            dictionary_mapping["unreleased"].add(phone)
        if any(x in diphthongs for x in query_set):
            dictionary_mapping["diphthong"].add(phone)
        elif any(x in triphthongs for x in query_set):
            dictionary_mapping["triphthong"].add(phone)
        elif any(x in d.phone_set_type.affricates for x in query_set):
            dictionary_mapping["affricate"].add(phone)
        elif any(x in d.phone_set_type.stops for x in query_set):
            dictionary_mapping["stop"].add(phone)
        for k, v in ipa_mapping.items():
            if base_phone in v:
                dictionary_mapping[k].add(phone)
        total_phones.add(phone)
        for v in dictionary_mapping.values():
            if phone in v:
                break
        else:
            dictionary_mapping["other"].add(phone)
    places = [
        "labial",
        "labiodental",
        "dental",
        "alveolar",
        "alveopalatal",
        "retroflex",
        "palatal",
        "velar",
        "uvular",
        "pharyngeal",
        "epiglottal",
        "glottal",
    ]
    columns = []
    for p in places:
        if p in dictionary_mapping:
            columns.append(p)
    sub_manners = ["tense", "aspirated", "implosive", "ejective", "unreleased", "prenasalized"]

    rows = []
    plotted = set()
    for manner in [
        "nasal",
        "stop",
        "affricate",
        "sibilant",
        "fricative",
        "approximant",
        "tap",
        "trill",
        "lateral_fricative",
        "lateral",
        "lateral_tap",
    ]:
        if manner not in dictionary_mapping:
            continue
        realized_submanner_rows = {}
        for x in sub_manners:
            if dictionary_mapping[manner] & dictionary_mapping[x]:
                realized_submanner_rows[x] = [f"{{submanner}}`{x.title()}`"]
        row_title = f"{{manner}}`{manner.replace('_',' ').title()}`"
        if realized_submanner_rows:
            row_title += " {submanner}`Plain`"
        row = [row_title]
        for place in columns:
            cell_set = dictionary_mapping[manner] & dictionary_mapping[place]
            base_set = dictionary_mapping[manner] & dictionary_mapping[place]
            for x in sub_manners:
                cell_set -= dictionary_mapping[x]
                base_set -= dictionary_mapping[x]
            voiced_set = base_set & dictionary_mapping["voiced"]
            voiceless_set = base_set & dictionary_mapping["voiceless"]
            other_set = base_set - dictionary_mapping["voiceless"] - dictionary_mapping["voiced"]
            plotted.update(voiceless_set)
            plotted.update(voiced_set)
            plotted.update(other_set)
            cell_data = {
                "voiceless": sorted(voiceless_set),
                "voiced": sorted(voiced_set),
                "other": sorted(other_set),
            }
            cell_contents = format_ipa_cell(cell_data, extra_data, base_indent="    ")
            row.append(cell_contents)
        rows.append(row)
        if realized_submanner_rows:
            for place in columns:
                for sub_manner in realized_submanner_rows.keys():
                    cell_set = (
                        dictionary_mapping[manner]
                        & dictionary_mapping[place]
                        & dictionary_mapping[sub_manner]
                    )
                    for s in realized_submanner_rows.keys():
                        if s == sub_manner:
                            continue
                        cell_set -= dictionary_mapping[s]
                    voiced_set = cell_set & dictionary_mapping["voiced"]
                    voiceless_set = cell_set & dictionary_mapping["voiceless"]
                    other_set = (
                        cell_set - dictionary_mapping["voiceless"] - dictionary_mapping["voiced"]
                    )
                    plotted.update(voiceless_set)
                    plotted.update(voiced_set)
                    plotted.update(other_set)
                    cell_data = {
                        "voiceless": sorted(voiceless_set),
                        "voiced": sorted(voiced_set),
                        "other": sorted(other_set),
                    }
                    cell_contents = format_ipa_cell(cell_data, extra_data, base_indent="    ")
                    realized_submanner_rows[sub_manner].append(cell_contents)
            rows.extend(realized_submanner_rows.values())
    row_headers = ["Manner"]
    columns = row_headers + columns
    consonants = {"header": columns, "rows": rows}

    oral_rows = []
    nasal_rows = []
    headers = ["front", "near-front", "central", "near-back", "back"]
    has_nasal = False
    for height in ["close", "close-mid", "open-mid", "open"]:
        for on in ["nasalized", "oral"]:
            main_row = [height.title()]
            lax_row = [""]
            for column in headers:
                cell_set = dictionary_mapping[height] & dictionary_mapping[column]
                if on in dictionary_mapping:  # nasalized
                    cell_set &= dictionary_mapping["nasalized"]
                    if cell_set and not has_nasal:
                        has_nasal = True
                else:
                    cell_set -= dictionary_mapping["nasalized"]
                if height == "close" and column in {"front", "back"}:
                    lax_set = set()
                    tense_set = cell_set - dictionary_mapping["lax"]
                elif height == "close" and column in {"near-front", "near-back"}:
                    tense_set = set()
                    lax_set = cell_set & dictionary_mapping["lax"]
                else:
                    tense_set = cell_set - dictionary_mapping["lax"]
                    lax_set = cell_set & dictionary_mapping["lax"]

                tense_rounded = tense_set & dictionary_mapping["rounded"]
                tense_unrounded = tense_set & dictionary_mapping["unrounded"]
                cell_data = {
                    "unrounded": sorted(tense_unrounded),
                    "rounded": sorted(tense_rounded),
                }
                plotted.update(tense_unrounded)
                plotted.update(tense_rounded)
                tense_cell_contents = format_ipa_cell(cell_data, extra_data, base_indent="    ")

                lax_rounded = lax_set & dictionary_mapping["rounded"]
                lax_unrounded = lax_set & dictionary_mapping["unrounded"]
                plotted.update(lax_rounded)
                plotted.update(lax_unrounded)
                cell_data = {
                    "unrounded": sorted(lax_unrounded),
                    "rounded": sorted(lax_rounded),
                }
                lax_cell_contents = format_ipa_cell(cell_data, extra_data, base_indent="    ")

                main_row.append(tense_cell_contents)
                lax_row.append(lax_cell_contents)
            if on in dictionary_mapping:  # nasalized
                nasal_rows.append(main_row)
                if height != "open":
                    nasal_rows.append(lax_row)
            else:
                oral_rows.append(main_row)
                if height != "open":
                    oral_rows.append(lax_row)

    headers = [""] + [x.title() for x in headers]
    if not has_nasal:
        nasal_rows = None

    header_row_string = "\n  - ".join(x.title() for x in consonants["header"])
    row_strings = "\n* - ".join("\n  - ".join(x) for x in consonants["rows"])
    stub_column_count = 1
    consonant_chart = chart_template.format(
        header_data=header_row_string,
        row_data=row_strings,
        type="consonant",
        stub_column_count=stub_column_count,
    )
    vowels = {
        "oral_rows": oral_rows,
        "nasal_rows": nasal_rows,
        "header": headers,
    }
    header_row_string = "\n  - ".join(vowels["header"])
    row_strings = "\n* - ".join("\n  - ".join(x) for x in vowels["oral_rows"])

    oral_chart = chart_template.format(
        header_data=header_row_string, row_data=row_strings, type="vowel", stub_column_count=1
    )
    nasal_chart = None
    if nasal_rows:
        header_row_string = "\n  - ".join(vowels["header"])
        row_strings = "\n* - ".join("\n  - ".join(x) for x in vowels["nasal_rows"])

        nasal_chart = chart_template.format(
            header_data=header_row_string, row_data=row_strings, type="vowel", stub_column_count=1
        )

    data = {
        "consonant_chart": consonant_chart,
        "oral_vowel_chart": oral_chart,
        "nasal_vowel_chart": nasal_chart,
        "diphthongs": dictionary_mapping["diphthong"],
        "other": dictionary_mapping["other"] & (total_phones - plotted),
        "triphthongs": dictionary_mapping["triphthong"],
    }
    for k in super_segmentals.keys():
        if k in dictionary_mapping:
            data[k] = dictionary_mapping[k]
    return data


phone_charts = {}
model_mappings = {}
for model_type, model_class in MODEL_TYPES.items():
    # if model_type != 'ivector':
    #    continue
    meta_datas[model_type] = {}
    model_mappings[model_type] = {}
    model_directory = os.path.join(mfa_model_root, model_type)
    staging_directory = os.path.join(model_directory, "staging")

    models_to_stage = os.listdir(staging_directory)
    for file_name in models_to_stage:
        if not os.path.isfile(os.path.join(staging_directory, file_name)):
            continue
        if model_type == "dictionary" and not file_name.endswith(".dict"):
            continue
        print(file_name)
        model = model_class(os.path.join(staging_directory, file_name))
        print(model.meta)
        s = model.name.split("_")
        dialect = ""
        if model_type == "language_model":
            if "_mfa" in model.name:
                s = model.name.replace("_mfa", "").split("_")
            language = "_".join(s[:-1])
            dialect = " ".join(s[1:-1])
            phone_set = "MFA"
        elif model_type == "ivector":
            language = model.name.replace("_mfa", "")
            dialect = ""
            phone_set = ""
        elif model_type == "tokenizer":
            language = model.name.replace("_mfa", "")
            dialect = ""
            phone_set = ""
        elif len(s) == 1:
            language = s[0]
            phone_set = "Unknown"
            dialect = ""
        elif len(s) == 2:
            language, phone_set = s
            phone_set = phone_set.upper()
            dialect = ""
        else:
            language = s[0]
            phone_set = s[-1].upper()
            dialect = " ".join(s[1:-1])
        try:
            version = model.meta["version"]
        except KeyError:
            version = montreal_forced_aligner.utils.get_mfa_version()
        if version.startswith("2.") or version.startswith("3."):
            version = CURRENT_MODEL_VERSION
        language = language.title()
        if len(dialect) == 2:
            dialect = dialect.upper()
        else:
            dialect = dialect.title()
        print(model_directory, language, phone_set, version)
        if dialect:
            phone_set_folder = f"{dialect}_{phone_set}".replace(" ", "_").lower()
        else:
            phone_set_folder = phone_set.lower()
        if phone_set_folder:
            output_directory = os.path.join(
                model_directory, language.lower(), phone_set_folder, f"v{version}"
            )
        else:
            output_directory = os.path.join(model_directory, language.lower(), f"v{version}")
        os.makedirs(output_directory, exist_ok=True)
        license_path = os.path.join(output_directory, "LICENSE")
        if phone_set != "CV" and not os.path.exists(license_path):
            shutil.copyfile(os.path.join(mfa_model_root, "LICENSE"), license_path)
        meta_path = os.path.join(output_directory, "meta.json")
        if OVERWRITE_METADATA or not os.path.exists(meta_path):
            meta_data = generate_meta_data(
                model, model_type, language, dialect, version, phone_set
            )
            with open(meta_path, "w", encoding="utf8") as f:
                json.dump(meta_data, f, indent=4, ensure_ascii=False)
        else:
            with open(meta_path, "r", encoding="utf8") as f:
                meta_data = json.load(f)
        meta_datas[model_type][generate_id(meta_data, model_type)] = meta_data
        keys = [language]
        if model_type in {"language_model", "ivector", "tokenizer"}:
            if dialect:
                keys.append((language, dialect))
                key = (language, dialect)
        else:
            if dialect:
                keys.append((language, dialect))
                keys.append((language, dialect, phone_set))
                key = (language, dialect, phone_set)
                dialect_key = (language, dialect)
            else:
                keys.append((language, phone_set))
        for key in keys:
            if key not in model_mappings[model_type]:
                model_mappings[model_type][key] = []
            model_mappings[model_type][key].append(generate_id(meta_data, model_type))
        if model_type == "dictionary" and phone_set in {"MFA", "CV", "ARPA"}:
            phone_set_type = "IPA"
            if phone_set == "ARPA":
                phone_set_type = "ARPA"
            phone_charts[meta_data["name"]] = analyze_dictionary(
                model.path, model.name, phone_set_type
            )
            # if language == 'hindi':
            #    err
    existing_models = []
    for language in os.listdir(model_directory):
        if language in {"staging", "training", "filter_lists", "1.0"}:
            continue
        language_directory = os.path.join(model_directory, language)
        if not os.path.isdir(language_directory):
            continue
        language = language.title()
        if model_type in {"ivector", "tokenizer"}:
            for version in os.listdir(language_directory):
                meta_path = os.path.join(language_directory, version, "meta.json")
                if not os.path.exists(meta_path):
                    continue
                with open(meta_path, "r", encoding="utf8") as f:
                    meta_data = json.load(f)
                meta_datas[model_type][generate_id(meta_data, model_type)] = meta_data
                keys = [language]
                for key in keys:
                    if key not in model_mappings[model_type]:
                        model_mappings[model_type][key] = []
                    model_mappings[model_type][key].append(generate_id(meta_data, model_type))

        else:
            for phone_set in os.listdir(language_directory):
                print(phone_set)
                phone_set_dir = os.path.join(language_directory, phone_set)
                if "_" in phone_set:
                    dialect, phone_set = phone_set.rsplit("_", maxsplit=1)
                else:
                    dialect = ""
                for version in os.listdir(phone_set_dir):
                    meta_path = os.path.join(phone_set_dir, version, "meta.json")
                    if not os.path.exists(meta_path):
                        continue
                    with open(meta_path, "r", encoding="utf8") as f:
                        meta_data = json.load(f)
                    meta_datas[model_type][generate_id(meta_data, model_type)] = meta_data
                    keys = [language]
                    if model_type == "language_model":
                        if dialect:
                            keys.append((language, dialect))
                            key = (language, dialect)
                    else:
                        if dialect:
                            keys.append((language, dialect))
                            keys.append((language, dialect, phone_set))
                            key = (language, dialect, phone_set)
                            dialect_key = (language, dialect)
                        else:
                            keys.append((language, phone_set))
                    for key in keys:
                        if key not in model_mappings[model_type]:
                            model_mappings[model_type][key] = []
                        model_mappings[model_type][key].append(generate_id(meta_data, model_type))


if "dictionary" in meta_datas:
    for k in model_corpus_mapping.keys():
        dict_id = k.replace("acoutic model", "dictionary")
        if dict_id in meta_datas["dictionary"]:
            model_dictionary_mapping[k] = [dict_id]

if "g2p" in meta_datas:
    for v in model_corpus_mapping.values():
        for d_id in v:
            g2p_id = d_id.replace("dictionary", "G2P model")
            if g2p_id in meta_datas["g2p"]:
                model_dictionary_mapping[g2p_id] = [d_id]


if "language_model" in meta_datas:
    for k, v in model_dictionary_mapping.items():
        lm_id = k.replace("acoustic", "language")
        if lm_id in meta_datas["language_model"]:
            model_dictionary_mapping[lm_id] = v


if "tokenizer" in meta_datas:
    for k, v in model_dictionary_mapping.items():
        tokenizer_id = k.replace("tokenizer", "language")
        if tokenizer_id in meta_datas["tokenizer"]:
            model_dictionary_mapping[tokenizer_id] = v


corpora_metadata = {}
model_mappings["corpus"] = {}
corpus_metadata_file = os.path.join(mfa_model_root, "corpus", "staging", "corpus_data.json")
if os.path.exists(corpus_metadata_file):
    with open(corpus_metadata_file, "r", encoding="utf8") as f:
        data = json.load(f)
    for language, c_list in data.items():
        if language == "Hindi-Urdu":
            continue
        for c in c_list:
            name = c["name"]
            if "version" in c:
                name += f'_{c["version"]}'
            id = make_path_safe(name)
            c["language"] = language
            c["id"] = generate_id(c, "corpus")

            c["license_link"] = f"[{c['license']}]({license_links[c['license']]})"
            if "dialects" not in c:
                c["dialects"] = []
            c["dialects"] = [x.title() if len(x) > 2 else x.upper() for x in c["dialects"]]
            corpora_metadata[c["id"]] = c
            print(c)
            print(generate_id(c, "corpus"))
            language_key = language
            if language_key not in model_mappings["corpus"]:
                model_mappings["corpus"][language_key] = []
            model_mappings["corpus"][language_key].append(c["id"])
            if c["dialects"]:
                for d in c["dialects"]:
                    key = (language, d)
                    if key not in model_mappings["corpus"]:
                        model_mappings["corpus"][key] = []
                    model_mappings["corpus"][key].append(c["id"])

    meta_datas["corpus"] = corpora_metadata

# Add links
for model_type, data in meta_datas.items():
    for model_name, meta_data in data.items():
        model_id = generate_id(meta_data, model_type)
        if model_type in {"acoustic", "language_model", "ivector", "tokenizer"}:
            print("HELLO!?", model_id, model_corpus_mapping.keys())
            if model_id in model_corpus_mapping:
                print(model_corpus_mapping[model_id])
                print(corpora_metadata.keys())
                meta_data["corpus"] = [corpora_metadata[x] for x in model_corpus_mapping[model_id]]
                for corpus_id in model_corpus_mapping[model_id]:
                    if model_type not in meta_datas["corpus"][corpus_id]:
                        meta_datas["corpus"][corpus_id][model_type] = []
                    meta_datas["corpus"][corpus_id][model_type].append(model_id)
        if model_type in {"language_model", "corpus", "ivector"}:
            if "dialect" in meta_data and meta_data["dialect"]:
                key = (meta_data["language"], meta_data["dialect"])
            else:
                key = meta_data["language"]
        else:
            if "dialect" in meta_data and meta_data["dialect"]:
                key = (meta_data["language"], meta_data["dialect"], meta_data["phone_set"])
            else:
                key = (meta_data["language"], meta_data["phone_set"])
        if model_type in {"acoustic", "language_model", "g2p"}:
            print(meta_data["name"])
            print(key)
            print(model_mappings["dictionary"])
            if key in model_mappings["dictionary"]:
                if "dictionary" not in meta_data:
                    meta_data["dictionary"] = []
                meta_data["dictionary"].extend(model_mappings["dictionary"][key])
            if model_id in model_dictionary_mapping:
                if "dictionary" not in meta_data:
                    meta_data["dictionary"] = []
                meta_data["dictionary"].extend(
                    [
                        x
                        for x in model_dictionary_mapping[model_id]
                        if x not in meta_data["dictionary"]
                    ]
                )
        elif model_type == "dictionary":
            for t in ["acoustic", "g2p", "language_model", "corpus"]:
                if key in model_mappings[t]:
                    if t not in meta_data:
                        meta_data[t] = []
                    meta_data[t].extend(model_mappings[t][key])
        elif model_type == "corpus":
            meta_data["dictionary"] = []
            if "dialects" in meta_data and meta_data["dialects"]:
                for dialect in meta_data["dialects"]:
                    key = (meta_data["language"], dialect)
                    if key in model_mappings["dictionary"]:
                        meta_data["dictionary"].extend(model_mappings["dictionary"][key])
            else:
                print(
                    meta_data["language"],
                    model_mappings["dictionary"],
                    meta_data["language"] in model_mappings["dictionary"],
                )
                if meta_data["language"] in model_mappings["dictionary"]:
                    for dictionary_id in model_mappings["dictionary"][meta_data["language"]]:
                        m = meta_datas["dictionary"][dictionary_id]
                        meta_data["dictionary"].append(dictionary_id)

for model_type, data in meta_datas.items():
    docs_dir = os.path.join(mfa_model_root, "docs", "source", model_type)
    os.makedirs(docs_dir, exist_ok=True)
    language_model_doc_mds = {}
    for model_name, meta_data in data.items():
        print(model_name, meta_data)
        if model_type not in {"language_model", "corpus"} and meta_data["phone_set"] in {
            "PROSODYLAB",
            "PINYIN",
        }:
            model_card_template = model_card_templates[model_type]["other"]
            docs_md_template = docs_card_templates[model_type]["other"]
        elif model_type not in {"language_model", "corpus"} and meta_data["phone_set"] in {"CV"}:
            model_card_template = model_card_templates[model_type]["other"]
            docs_md_template = docs_card_templates[model_type]["mfa"]
        else:
            model_card_template = model_card_templates[model_type]["mfa"]
            docs_md_template = docs_card_templates[model_type]["mfa"]
        if model_type == "language_model":
            language, version = meta_data["language"], meta_data["version"]
        elif model_type == "corpus":
            language, name = meta_data["language"], meta_data["name"]
            name = make_path_safe(name)
        else:
            language, phone_set, dialect, version = (
                meta_data["language"],
                meta_data["phone_set"],
                meta_data["dialect"],
                meta_data["version"],
            )
        output_directory = get_model_card_directory(model_type, meta_data)
        os.makedirs(output_directory, exist_ok=True)
        model_card_path = os.path.join(output_directory, "README.md")
        rst_path = model_name + ".md"
        docs_language_dir = os.path.join(docs_dir, language)
        if language not in language_model_doc_mds:
            language_model_doc_mds[language] = []
        os.makedirs(docs_language_dir, exist_ok=True)
        docs_card_path = os.path.join(docs_language_dir, rst_path)
        language_model_doc_mds[language].append(rst_path)
        if OVERWRITE_MD or not os.path.exists(model_card_path):
            with open(model_card_path, "w", encoding="utf8") as f:
                print(meta_data)
                fields = extract_model_card_fields(meta_data, model_type)
                f.write(model_card_template.format(**fields))
        if OVERWRITE_MD or not os.path.exists(docs_card_path):
            with open(docs_card_path, "w", encoding="utf8") as f:
                print(meta_data)
                fields = extract_doc_card_fields(meta_data, model_type)
                f.write(docs_md_template.format(**fields))
    index_path = os.path.join(docs_dir, "index.rst")
    rst_string = "   " + "\n   ".join(
        f"{x}/index.rst" for x in sorted(language_model_doc_mds.keys())
    )
    if model_type == "dictionary":
        rst_string = "   ../mfa_phone_set.md\n" + rst_string
    model_type_name = model_type_names[model_type]
    columns = model_type_columns[model_type]
    widths = model_type_column_widths[model_type]
    with open(index_path, "w", encoding="utf8") as f:
        f.write(
            f"""

.. _{model_type}:

{model_type_name}
{'='* len(model_type_name)}

.. needtable::
   :types: {model_type}
   :style: datatable
   :columns: {columns}
   :class: table-striped
   :colwidths: {widths}

.. toctree::
   :hidden:

{rst_string}
"""
        )
    for language, model_doc_mds in sorted(language_model_doc_mds.items()):
        index_path = os.path.join(docs_dir, language, "index.rst")
        rst_string = "   " + "\n   ".join(model_doc_mds)
        with open(index_path, "w", encoding="utf8") as f:
            f.write(
                f"""

.. _{model_type}_{language.lower()}:

{language.title()}
{'='* len(language)}

.. needtable::
   :types: {model_type}
   :filter: language == "{language.title()}"
   :style: datatable
   :columns: {columns}
   :class: table-striped
   :colwidths: {widths}

.. toctree::
   :hidden:

{rst_string}
"""
            )