File size: 56,813 Bytes
0eb3766
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from email.mime import audio
import json
import os
from pandas import read_json
from regex import B, D
import tqdm
from typing import List, Dict, Any
import nltk
from nltk.translate.bleu_score import sentence_bleu, SmoothingFunction
from dataclasses import dataclass
from abc import ABC, abstractmethod
from rouge_score import rouge_scorer
import math
import time
from urllib.request import urlopen
import librosa
from transformers import Qwen2AudioForConditionalGeneration, AutoProcessor
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM


def read_json(file_path: str) -> Dict[str, Any]:
    with open(file_path, "r") as f:
        data = json.load(f)
    return data


def exact_match_accuracy(predictions: List[str], references: List[str]) -> float:
    correct = 0
    for pred, ref in zip(predictions, references):
        if isinstance(ref, str):
            ref = [ref]
        if isinstance(ref, int):
            ref = [ref]
        is_match_this_turn = False
        for r in ref:
            if pred.strip() == r.strip():
                is_match_this_turn = True
        if is_match_this_turn:
            correct += 1
    return correct / len(predictions) if predictions else 0.0


def blur_match_accuracy(predictions: List[str], references: List[str]) -> float:
    correct = 0
    for pred, ref in zip(predictions, references):
        # if isinstance(ref, int):
        #     if  == ref:
        if str(ref) in str(pred).strip().lower():
            correct += 1
    return correct / len(predictions) if predictions else 0.0


def calculate_f1(predictions: List[str], references: List[str]) -> float:
    def compute_f1(pred: str, ref: str) -> float:
        pred_tokens = pred.strip().split()
        ref_tokens = ref.strip().split()
        
        common_tokens = set(pred_tokens) & set(ref_tokens)
        num_common = len(common_tokens)
        
        if num_common == 0:
            return 0.0
        
        precision = num_common / len(pred_tokens)
        recall = num_common / len(ref_tokens)
        
        return 2 * precision * recall / (precision + recall)
    
    total_f1 = 0.0
    for pred, ref in zip(predictions, references):
        if isinstance(ref, str):
            ref = [ref]
        max_f1 = 0.0
        for r in ref:
            max_f1 = max(compute_f1(pred, r), max_f1)
        total_f1 += max_f1
    
    return total_f1 / len(predictions) if predictions else 0.0


def rouge_evaluation(predictions: List[str], references: List[str]) -> Dict[str, float]:
    scorer = rouge_scorer.RougeScorer(['rouge1', 'rouge2', 'rougeL'], use_stemmer=True)
    rouge1_scores, rouge2_scores, rougel_scores = [], [], []
    for pred, ref in zip(predictions, references):
        if isinstance(ref, str):
            ref = [ref]
        rouge1, rouge2, rougeL = 0, 0, 0
        for r in ref:
            scores = scorer.score(r, pred)
            rouge1 = max(scores['rouge1'].fmeasure, rouge1)
            rouge2 = max(scores['rouge2'].fmeasure, rouge2)
            rougeL = max(scores['rougeL'].fmeasure, rougeL)
        rouge1_scores.append(rouge1)
        rouge2_scores.append(rouge2)
        rougel_scores.append(rougeL)
    return {
        'rouge1': sum(rouge1_scores) / len(rouge1_scores),
        'rouge2': sum(rouge2_scores) / len(rouge2_scores),
        'rougeL': sum(rougel_scores) / len(rougel_scores),
    }


def bleu_evaluation(predictions: List[str], references: List[str]) -> Dict[str, float]:
    smoothie = SmoothingFunction().method4
    bleu1_scores, bleu2_scores, bleu3_scores, bleu4_scores = [], [], [], []
    
    for pred, ref in zip(predictions, references):
        hypothesis = nltk.word_tokenize(pred)
        if isinstance(ref, str):
            ref = [ref]
        bleu1, bleu2, bleu3, bleu4 = 0, 0, 0, 0
        for r in ref:
            reference = [nltk.word_tokenize(r)]
            bleu1 = max(sentence_bleu(reference, hypothesis, weights=(1, 0, 0, 0), smoothing_function=smoothie), bleu1)
            bleu2 = max(sentence_bleu(reference, hypothesis, weights=(0.5, 0.5, 0, 0), smoothing_function=smoothie), bleu2)
            bleu3 = max(sentence_bleu(reference, hypothesis, weights=(1/3, 1/3, 1/3, 0), smoothing_function=smoothie), bleu3)
            bleu4 = max(sentence_bleu(reference, hypothesis, weights=(0.25, 0.25, 0.25, 0.25), smoothing_function=smoothie), bleu4)
        
        bleu1_scores.append(bleu1)
        bleu2_scores.append(bleu2)
        bleu3_scores.append(bleu3)
        bleu4_scores.append(bleu4)
    
    return {
        'bleu1': sum(bleu1_scores) / len(bleu1_scores) if bleu1_scores else 0.0,
        'bleu2': sum(bleu2_scores) / len(bleu2_scores) if bleu2_scores else 0.0,
        'bleu3': sum(bleu3_scores) / len(bleu3_scores) if bleu3_scores else 0.0,
        'bleu4': sum(bleu4_scores) / len(bleu4_scores) if bleu4_scores else 0.0,
    }


def mean_absolute_error(predictions: List[float], references: List[float]) -> float:
    if not predictions:
        return 0.0
    error_sum = 0.0
    for p, r in zip(predictions, references):
        error_sum += abs(p - r)
    return error_sum / len(predictions)


def mean_squared_error(predictions: List[float], references: List[float]) -> float:
    if not predictions:
        return 0.0
    error_sum = 0.0
    for p, r in zip(predictions, references):
        error_sum += (p - r) ** 2
    return error_sum / len(predictions)


def root_mean_squared_error(predictions: List[float], references: List[float]) -> float:
    return math.sqrt(mean_squared_error(predictions, references))


def post_process_output(output: str) -> str:
    cnt = 0
    for d in output:
        if d['gt'] in d['response'].strip().lower():
            cnt += 1
    acc = round(cnt / len(output), 4)
    print(f"Accuracy: {acc}")
    return acc


def evaluation_accuracy(predictions: List[str]) -> Dict[str, float]:
    correct = 0
    for pred in predictions:
        if pred == '1':
            correct += 1
    return correct / len(predictions) if predictions else 0.0


class AudioComprehensionModel:
    def __init__(self, model_name: str):
        self.model_name = model_name
        self.load_model()
    
    def load_model(self):
        if 'qwen-audio-chat' in self.model_name.lower():
            self.model = AutoModelForCausalLM.from_pretrained(self.model_name, device_map='cuda', trust_remote_code=True).eval()
            self.tokenizer = AutoTokenizer.from_pretrained(self.model_name, trust_remote_code=True)
            self.tokenizer.padding_side = 'left'
            self.tokenizer.pad_token_id = self.tokenizer.eod_id
        elif 'qwen2' in self.model_name.lower():
            self.processor = AutoProcessor.from_pretrained(self.model_name)
            print(self.processor.chat_template)
            self.model = Qwen2AudioForConditionalGeneration.from_pretrained(self.model_name, device_map="auto").eval()
        
        elif 'new_model_name' in self.model_name.lower():
            # support to load self-build models here
            pass

        else:
            raise ValueError(f"Unsupported model name: {self.model_name}")
        
    def generate(self, prompt: str, max_new_tokens=256, audio_path: str=None) -> str:
        
        if "qwen-audio-chat" in self.model_name.lower():
            query = self.tokenizer.from_list_format([
                {'audio': audio_path}, # Either a local path or an url
                {'text': prompt} # The query,
            ])
            response, history = self.model.chat(self.tokenizer, query=query, history=None)
            return response
        
        elif "qwen2" in self.model_name.lower():
            conversation = [
                {'role': 'system', 'content': 'You are a helpful assistant.'}, 
                {"role": "user", "content": [
                    {"type": "audio", "audio": audio_path},
                    {"type": "text", "text": prompt},
                ]},
            ]
            text = self.processor.apply_chat_template(conversation, add_generation_prompt=True, tokenize=False)
            audios = []
            for message in conversation:
                if isinstance(message["content"], list):
                    for ele in message["content"]:
                        if ele["type"] == "audio":
                            audios.append(
                                librosa.load(
                                    ele['audio'], 
                                    sr=self.processor.feature_extractor.sampling_rate)[0]
                            )
            # print(text)
            inputs = self.processor(text=text, audios=audios, return_tensors="pt", padding=True)
            inputs.input_ids = inputs.input_ids.to("cuda")
            inputs = inputs.to("cuda")
            # print(inputs)
            # exit(0)
            generate_ids = self.model.generate(**inputs, max_length=300)
            generate_ids = generate_ids[:, inputs.input_ids.size(1):]

            response = self.processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
            return response
        
        elif "new" in self.model_name.lower():
            # support to generate response based on self-build models here
            pass
        
        else:
            raise ValueError(f"Unsupported model name: {self.model_name}")
        


@dataclass
class Instance:
    input: Dict[str, Any]
    output: Dict[str, Any]
    id: str


class BaseTask(ABC):
    def __init__(self, task_data: Dict[str, Any], model: AudioComprehensionModel, audio_dir: str = None, output_dir: str = None, task_name: str = None):
        self.task_data = read_json(task_data)
        self.model = model
        self.audio_dir = audio_dir  # should include the audios files
        self.data = self._parse_data(self.task_data)
        self.choice_candidate = self._get_choice_candidate(self.task_data)
        self.task_name = os.path.dirname(task_data).split("/")[-1] if task_name is None else task_name
        self.output_dir = output_dir
        os.makedirs(self.output_dir, exist_ok=True) if self.output_dir else None

        self.references = []
        self.predictions = []

    def save_predictions(self, audio_paths):
        results = []
        for gt, response, audio_path in zip(self.references, self.predictions, audio_paths):
            results.append({
                'gt': gt,
                'response': response,
                'audio_path': audio_path,
            })
        time_prefix = time.strftime('%y%m%d%H%M%S', time.localtime())
        results_file = os.path.join(self.output_dir, f'{self.task_name }_{time_prefix}.json') if self.output_dir else f'{self.task_name }_{time_prefix}.json'
        json.dump(results, open(results_file, 'w'))

    @abstractmethod
    def _get_choice_candidate(self):
        pass

    @abstractmethod
    def _parse_data(self, task_data: Dict[str, Any]) -> List[Instance]:
        pass
    
    @abstractmethod
    def evaluate(self) -> Dict[str, float]:
        pass

    @abstractmethod
    def run_inference(self):
        pass


class EvaluationTask(BaseTask):
    """

    Used to determine whether the results generated by the model are correct

    """
    def _parse_data(self, task_data: Dict[str, Any]) -> List[Instance]:
        return task_data

    def _get_choice_candidate(self, data: List[Instance]) -> List[str]:
        return ["None"]

    def save_predictions(self, audio_paths):
        results = []
        for gt, response, audio_path in zip(self.references, self.predictions, audio_paths):
            results.append({
                'gt': gt[0],
                'response': gt[1],
                'audio_path': audio_path,
                'llm_prediction': response,
            })
        time_prefix = time.strftime('%y%m%d%H%M%S', time.localtime())
        results_file = os.path.join(self.output_dir, f'{self.task_name }_{time_prefix}.json') if self.output_dir else f'{self.task_name }_{time_prefix}.json'
        json.dump(results, open(results_file, 'w'))

    def run_inference(self):
        audio_paths = []
        for inst in tqdm.tqdm(self.data):
            prompt = " will provide you with a Ground-truth label and a Prediction label. The label can either be a single string or a list of multiple labels. I need you to compare these two labels on a semantic level.\nSpecifically, I want you to evaluate whether the Prediction label semantically matches, is partially aligned, includes, or describes the Ground-truth label (or the semantic meaning represented by the list of labels). If any of these conditions are satisfied, consider it a match.\n\nHere are some examples of successful matches:\n\nGround-truth label: \"rain\"\nPrediction label: \"The sound in the audio is rain falling\"\n(This is considered a match.)\nGround-truth label: [\"decrease\", \"volume\", \"none\"]\nPrediction label: \"The intent in the audio is to adjust the volume\"(This is also considered a match.)\nIf the labels successfully match, assign a score of 1. If they do not match, assign a score of 0.**Imporant!!!, only output the score (0 or 1), no explanation.** \n\nGround-truth label:{}\nPrediction label:{}"
            gt = inst["gt"]
            response = inst["response"]
            prompt = prompt.format(gt, response)
            try:
                response = self.model.generate(prompt)
                # print(response)
            except Exception as e:
                response = "None"
                continue

            self.predictions.append(response)
            self.references.append([inst["gt"], inst["response"]])
            audio_paths.append(inst["audio_path"])
        self.save_predictions(audio_paths)

    def evaluate(self) -> Dict[str, float]:
        acc = evaluation_accuracy(self.predictions)
        return {"accuracy": acc}


class AccentSexClassification(BaseTask):
    def _parse_data(self, task_data: Dict[str, Any]) -> List[Instance]:
        return [Instance(input=d["input"], output=d["output"], id=d["id"]) 
                for d in task_data["data"]]

    def _get_choice_candidate(self, data: List[Instance]) -> List[str]:
        return ['female', 'male']

    def save_predictions(self, audio_paths):
        results = []
        for gt, response, audio_path in zip(self.references, self.predictions, audio_paths):
            results.append({
                'gt': gt,
                'response': response,
                'audio_path': audio_path,
            })
        time_prefix = time.strftime('%y%m%d%H%M%S', time.localtime())
        results_file = os.path.join(self.output_dir, f'{self.task_name }_{time_prefix}.json') if self.output_dir else f'{self.task_name }_{time_prefix}.json'
        json.dump(results, open(results_file, 'w'))

    def run_inference(self):
        self.predictions = []
        self.references = []
        audio_paths = []
        for inst in tqdm.tqdm(self.data):
            audio_path = os.path.join(self.audio_dir, inst.input["audio_file"])
            question = inst.input["prompt"]
            prompt = f"Please listen to the audio and then answer the question by directly choose a choice from choice candidates. Questions: {question}, Candidate choices: {self.choice_candidate}\nAnswer:"
            try:
                response = self.model.generate(prompt, audio_path=audio_path)
            except:
                print("error audio {}".format(inst.input["audio_file"]))
                continue
            self.predictions.append(response)
            self.references.append(inst.output["text"])
            audio_paths.append(inst.input["audio_file"])
        
        self.save_predictions(audio_paths)
    
    
    def evaluate(self) -> Dict[str, float]:
        acc = exact_match_accuracy(self.predictions, self.references)
        return {"accuracy": acc}


class AcousticSceneClassification(BaseTask):
    def _parse_data(self, task_data: Dict[str, Any]) -> List[Instance]:
        return [Instance(input=d["input"], output=d["output"], id=d["id"]) 
                for d in task_data["data"]]

    def _get_choice_candidate(self, data: List[Instance]) -> List[str]:
        choices = []
        for item in data['data']:
            choices.append(item['output']["text"].strip().lower())
        choices = list(set(choices))
        return choices

    def run_inference(self):
        print(f"Choice candidates: {self.choice_candidate}")
        audio_paths = []
        for inst in tqdm.tqdm(self.data):
            audio_path = os.path.join(self.audio_dir, inst.input["audio_file"])
            question = inst.input["prompt"]
            prompt = f"Please listen to the input music and then determine the category of the acoustic scene. The candidate scene category are {self.choice_candidate}. Please output **only one category** from the provided candidate categories, and **DO NOT** output any other words.\nQuestions: {question}\nAnswer:"
            try:
                response = self.model.generate(prompt, audio_path=audio_path)
            except Exception as e:
                print("Error audio: {}".format(inst.input["audio_file"]))
                response = "None"
                continue
            self.predictions.append(response)
            self.references.append(inst.output["text"].strip().lower())
            audio_paths.append(inst.input["audio_file"])
        self.save_predictions(audio_paths)
    
    def evaluate(self) -> Dict[str, float]:
        acc = exact_match_accuracy(self.predictions, self.references)
        return {"accuracy": acc}


class AnimalSoundDetection(BaseTask):
    def _parse_data(self, task_data: Dict[str, Any]) -> List[Instance]:
        return [Instance(input=d["input"], output=d["output"], id=d["id"]) 
                for d in task_data["data"]]

    def _get_choice_candidate(self, data) -> List[str]:
        choices = []
        for item in data['data']:
            choices.append(item['output']["text"].strip().lower())
        choices = list(set(choices))
        return choices

    def run_inference(self):
        print(f"Choice candidates: {self.choice_candidate}")
        audio_paths = []
        for inst in tqdm.tqdm(self.data):
            audio_path = os.path.join(self.audio_dir, inst.input["audio_file"])
            question = inst.input["prompt"]
            prompt = f"Please listen to the audio and then answer the question by directly choose a choice from choice candidates, without other words. Questions: {question}, Candidate choices: {self.choice_candidate}\nAnswer:"
            try:
                response = self.model.generate(prompt, audio_path=audio_path)
            except Exception as e:
                print("Error audio: {}".format(inst.input["audio_file"]))
                response = "None"
                continue
            self.predictions.append(response)
            self.references.append(inst.output["text"].strip().lower())
            audio_paths.append(inst.input["audio_file"])
        self.save_predictions(audio_paths)

    def evaluate(self) -> Dict[str, float]:
        acc = exact_match_accuracy(self.predictions, self.references)
        return {"accuracy": acc}


class AudioCaptions(BaseTask):
    def _parse_data(self, task_data: Dict[str, Any]) -> List[Instance]:
        return [Instance(input=d["input"], output=d["output"], id=d["id"]) 
                for d in task_data["data"]]

    def _get_choice_candidate(self, data: List[Instance]) -> List[str]:
        return ["None"]

    def run_inference(self):
        audio_paths = []
        for inst in tqdm.tqdm(self.data):
            audio_path = os.path.join(self.audio_dir, inst.input["audio_file"])
            question = inst.input["prompt"]
            prompt = f"Please listen to the audio and then answer the question. Questions: {question}\nAnswer:"
            try:
                response = self.model.generate(prompt, audio_path=audio_path)
            except Exception as e:
                print("Error audio: {}".format(inst.input["audio_file"]))
                response = "None"
                continue
            self.predictions.append(response)
            self.references.append(inst.output["text"])
            audio_paths.append(inst.input["audio_file"])
        self.save_predictions(audio_paths)

    def evaluate(self) -> Dict[str, float]:
        bleu = bleu_evaluation(self.predictions, self.references)
        return {"bleu1": bleu['bleu1']}


class AudioCaptionsClotho(BaseTask):
    def _parse_data(self, task_data: Dict[str, Any]) -> List[Instance]:
        return [Instance(input=d["input"], output=d["output"], id=d["id"]) 
                for d in task_data["data"]]

    def _get_choice_candidate(self, data: List[Instance]) -> List[str]:
        return ["None"]

    def run_inference(self):
        audio_paths = []
        for inst in tqdm.tqdm(self.data):
            audio_path = os.path.join(self.audio_dir, inst.input["audio_file"])
            question = inst.input["prompt"]
            prompt = f"Please listen to the audio and then answer the question. Questions: {question}\nAnswer:"
            try:
                response = self.model.generate(prompt, audio_path=audio_path)
            except Exception as e:
                print("Error audio: {}".format(inst.input["audio_file"]))
                response = "None"
                continue
            self.predictions.append(response)
            self.references.append(inst.output["text"])
            audio_paths.append(inst.input["audio_file"])
        self.save_predictions(audio_paths)

    def evaluate(self) -> Dict[str, float]:
        acc = bleu_evaluation(self.predictions, self.references)
        return {"accuracy": acc}


class AudioQA(BaseTask):
    def _parse_data(self, task_data: Dict[str, Any]) -> List[Instance]:
        return [Instance(input=d["input"], output=d["output"], id=d["id"]) 
                for d in task_data["data"]]

    def _get_choice_candidate(self, data) -> List[str]:
        choices = []
        for item in data['data']:
            choices.append(item['output']["text"].strip().lower())
        choices = list(set(choices))
        return choices

    def run_inference(self):
        audio_paths = []
        for inst in tqdm.tqdm(self.data):
            audio_path = os.path.join(self.audio_dir, inst.input["audio_file"])
            question = inst.input["prompt"]
            prompt = f"Please listen to the audio and then answer the question by directly choose a choice from choice candidates. Questions: {question}, Candidate choices: {self.choice_candidate}\nAnswer:"
            try:
                response = self.model.generate(prompt, audio_path=audio_path)
            except Exception as e:
                print("Error audio: {}".format(inst.input["audio_file"]))
                response = "None"
                continue
            self.predictions.append(response)
            self.references.append(inst.output["text"])
            audio_paths.append(inst.input["audio_file"])
        self.save_predictions(audio_paths)

    def evaluate(self) -> Dict[str, float]:
        acc = exact_match_accuracy(self.predictions, self.references)
        return {"accuracy": acc}


class BirdSoundDetection(BaseTask):

    def _parse_data(self, task_data: Dict[str, Any]) -> List[Instance]:
        return [Instance(input=d["input"], output=d["output"], id=d["id"]) 
                for d in task_data["data"]]

    def _get_choice_candidate(self, data: List[Instance]) -> List[str]:
        return ["Yes", "No"]

    def save_predictions(self, audio_paths):
        results = []
        for gt, response, audio_path in zip(self.references, self.predictions, audio_paths):
            results.append({
                'gt': gt,
                'response': response,
                'audio_path': audio_path,
            })
        time_prefix = time.strftime('%y%m%d%H%M%S', time.localtime())
        results_file = os.path.join(self.output_dir, f'{self.task_name }_{time_prefix}.json') if self.output_dir else f'{self.task_name }_{time_prefix}.json'
        json.dump(results, open(results_file, 'w'))

    def run_inference(self):
        self.predictions = []
        self.references = []
        audio_paths = []
        for inst in tqdm.tqdm(self.data):
            audio_path = os.path.join(self.audio_dir, inst.input["audio_file"])
            question = inst.input["prompt"]
            prompt = f"Please listen to the audio and then answer the question by directly choose a choice from choice candidates. Questions: {question}, Candidate choices: {self.choice_candidate}\nAnswer:"
            try:
                response = self.model.generate(prompt, audio_path=audio_path)
            except Exception as e:
                print("Error audio: {}".format(inst.input["audio_file"]))
                response = "None"
                continue
            self.predictions.append(response)
            self.references.append("Yes" if inst.output["text"] == 1 else "No")
            audio_paths.append(inst.input["audio_file"])
        self.save_predictions(audio_paths)

    def evaluate(self) -> Dict[str, float]:
        acc = exact_match_accuracy(self.predictions, self.references)
        return {"accuracy": acc}


class EnvironmentSoundRecognition(BaseTask):
    def _parse_data(self, task_data: Dict[str, Any]) -> List[Instance]:
        return [Instance(input=d["input"], output=d["output"], id=d["id"]) 
                for d in task_data["data"]]

    def _get_choice_candidate(self, data) -> List[str]:
        choices = []
        for item in data['data']:
            choices.append(item['output']["text"].strip().lower())
        choices = list(set(choices))
        return choices

    def run_inference(self):
        audio_paths = []
        for inst in tqdm.tqdm(self.data):
            audio_path = os.path.join(self.audio_dir, inst.input["audio_file"])
            question = inst.input["prompt"]
            prompt = f"Please listen to the audio and then answer the question by directly choose a choice from choice candidates. Questions: {question}, Candidate choices: {self.choice_candidate}\nAnswer:"
            try:
                response = self.model.generate(prompt, audio_path=audio_path)
            except Exception as e:
                print(f"error {e}")
                print("Error audio: {}".format(inst.input["audio_file"]))
                response = "None"
                continue
            self.predictions.append(response)
            self.references.append(inst.output["text"])
            audio_paths.append(inst.input["audio_file"])
        self.save_predictions(audio_paths)
    
    def evaluate(self) -> Dict[str, float]:
        acc = blur_match_accuracy(self.predictions, self.references)
        return {"accuracy": acc}


class IntentClassification(BaseTask):
    def _parse_data(self, task_data: Dict[str, Any]) -> List[Instance]:
        return [Instance(input=d["input"], output=d["output"], id=d["id"]) 
                for d in task_data["data"]]

    def _get_choice_candidate(self, data: Dict) -> Dict:
        intent_label = data['intent_label']
        return intent_label

    def run_inference(self):
        audio_paths = []
        candidate_actions = ','.join([k for k in self.choice_candidate['action'].keys() if not k[0].isdigit()])
        candidate_objects = ','.join([k for k in self.choice_candidate['object'].keys() if not k[0].isdigit()])
        candidate_locations = ','.join([k for k in self.choice_candidate['location'].keys() if not k[0].isdigit()])
        for inst in tqdm.tqdm(self.data):
            audio_path = os.path.join(self.audio_dir, inst.input["audio_file"])
            question = inst.input["prompt"]
            prompt = f"Please listen to the audio and then detect the intention. The intention triplet includes three parts: action, object, and location. The candicate actions are {candidate_actions}, candidate objects are {candidate_objects}, and candidate locations are {candidate_locations}. Please answer the questions only use the provided candidate actions, objects, and locations. Questions: {question}\nAnswer:"
            try:
                response = self.model.generate(prompt, audio_path=audio_path)
            except Exception as e:
                print("Error audio: {}".format(inst.input["audio_file"]))
                response = "None"
                continue
            self.predictions.append(response)
            self.references.append(' '.join([self.choice_candidate['action'][inst.output["text"].split()[0]], self.choice_candidate['action'][inst.output["text"].split()[1]], self.choice_candidate['action'][inst.output["text"].split()[2]]]))
            audio_paths.append(inst.input["audio_file"])
        self.save_predictions(audio_paths)

    def evaluate(self) -> Dict[str, float]:
        acc = exact_match_accuracy(self.predictions, self.references)
        return {"accuracy": acc}


def post_process_intent_output():
    data_path = '/m2v_intern/wushengqiong/model/audio-test/predictions/understanding/IntentClassification_250102204424.json'
    intent_label = read_json('/m2v_intern/wushengqiong/model/audio-test/understanding/IntentClassification/annotation.json')['intent_label']
    action = intent_label['action']
    object = intent_label['object']
    location = intent_label['location']

    data = read_json(data_path)

    results = []
    for d in data:
        results.append({
            'gt': [action[d['gt'].split()[0]], object[d['gt'].split()[1]], location[d['gt'].split()[2]]],
            'response': d['response'],
            'audio_path': d['audio_path'],
        })
    json.dump(results, open('/m2v_intern/wushengqiong/model/audio-test/predictions/understanding/IntentClassification_250102204424_1.json', 'w'))


class MusicGenreClassification(BaseTask):
    def _parse_data(self, task_data: Dict[str, Any]) -> List[Instance]:
        return [Instance(input=d["input"], output=d["output"], id=d["id"]) 
                for d in task_data["data"]]

    def _get_choice_candidate(self, data: Dict) -> Dict:
        choices = []
        for item in data['data']:
            choices.append(item['output']["text"].strip().lower())
        choices = list(set(choices))
        return choices


    def run_inference(self):
        audio_paths = []
        for inst in tqdm.tqdm(self.data):
            audio_path = os.path.join(self.audio_dir, inst.input["audio_file"].replace('\\', '/'))
            question = inst.input["prompt"]
            prompt = f"Please listen to the input music and then determine the genre of the music. The candidate genres are {self.choice_candidate}. Please output **only one genre** from the provided candidate genres, and **DO NOT** output any other words.\nQuestions: {question}\nAnswer:"
            try:
                response = self.model.generate(prompt, audio_path=audio_path)
            except Exception as e:
                print("Error audio: {}".format(inst.input["audio_file"]))
                response = "None"
                continue
            self.predictions.append(response)
            self.references.append(inst.output["text"])
            audio_paths.append(inst.input["audio_file"])
        self.save_predictions(audio_paths)

    def evaluate(self) -> Dict[str, float]:
        acc = exact_match_accuracy(self.predictions, self.references)
        return {"accuracy": acc}


class MusicInstrumentClassification(BaseTask):
    def _parse_data(self, task_data: Dict[str, Any]) -> List[Instance]:
        return [Instance(input=d["input"], output=d["output"], id=d["id"]) 
                for d in task_data["data"]]

    def _get_choice_candidate(self, data: Dict) -> Dict:
        choices = []
        for item in data['data']:
            choices.append(item['output']["text"].strip().lower())
        choices = list(set(choices))
        return choices

    def run_inference(self):
        audio_paths = []
        # candidate_instruments = ','.join([k for k in self.choice_candidate.keys() if not k[0].isdigit()])
        for inst in tqdm.tqdm(self.data):
            audio_path = os.path.join(self.audio_dir, inst.input["audio_file"])
            question = inst.input["prompt"]
            prompt = f"Please listen to the music and then detect the instrument of the music. The candidate instruments are {self.choice_candidate}. Please output **only the most appropriate music instrument** from the provided candidate music instruments, and **DO NOT** output any other words. Questions: {question}\nAnswer:"
            try:
                response = self.model.generate(prompt, audio_path=audio_path)
            except Exception as e:
                print("Error audio: {}".format(inst.input["audio_file"]))
                response = "None"
                continue
            self.predictions.append(response)
            self.references.append(inst.output["text"])
            audio_paths.append(inst.input["audio_file"])
        self.save_predictions(audio_paths)

    def evaluate(self) -> Dict[str, float]:
        acc = exact_match_accuracy(self.predictions, self.references)
        return {"accuracy": acc}


class MusicInstrumentSourceAnalysis(BaseTask):
    def _parse_data(self, task_data: Dict[str, Any]) -> List[Instance]:
        return [Instance(input=d["input"], output=d["output"], id=d["id"]) 
                for d in task_data["data"]]

    def _get_choice_candidate(self, data: Dict) -> Dict:
        choices = []
        for item in data['data']:
            choices.append(item['output']["text"].strip().lower())
        choices = list(set(choices))
        return choices

    def run_inference(self):
        audio_paths = []
        for inst in tqdm.tqdm(self.data):
            audio_path = os.path.join(self.audio_dir, inst.input["audio_file"])
            question = inst.input["prompt"]
            prompt = f"Please listen to the music and then detect the instrucment source of the music. The candidate sources are {self.choice_candidate}. Please output **only the most appropriate music source** from the provided candidate music sources, and **DO NOT** output any other words. Questions: {question}\nAnswer:"
            try:
                response = self.model.generate(prompt, audio_path=audio_path)
            except Exception as e:
                print("Error audio: {}".format(inst.input["audio_file"]))
                response = "None"
                continue
            self.predictions.append(response)
            self.references.append(inst.output["text"])
            audio_paths.append(inst.input["audio_file"].strip().lower())
        self.save_predictions(audio_paths)

    def evaluate(self) -> Dict[str, float]:
        acc = exact_match_accuracy(self.predictions, self.references)
        return {"accuracy": acc}


class MusicPitchAnalysis(BaseTask):
    def _parse_data(self, task_data: Dict[str, Any]) -> List[Instance]:
        return [Instance(input=d["input"], output=d["output"], id=d["id"]) 
                for d in task_data["data"]]

    def _get_choice_candidate(self, data: Dict) -> Dict:
        choices = []
        for item in data['data']:
            choices.append(item['output']["text"])
        choices = list(set(choices))
        return choices

    def run_inference(self):
        audio_paths = []
        for inst in tqdm.tqdm(self.data):
            audio_path = os.path.join(self.audio_dir, inst.input["audio_file"])
            question = inst.input["prompt"]
            prompt = f"Please listen to the music and then detect the pitch score of the music. The 0-based MIDI pitch is in the range [0, 127]. Please output **only the most appropriate pitch score in a number** from the provided range, and **DO NOT** output any other words. Questions: {question}\nAnswer:"
            try:
                response = self.model.generate(prompt, audio_path=audio_path)
            except Exception as e:
                print("Error audio: {}".format(inst.input["audio_file"]))
                response = "None"
                continue
            self.predictions.append(response)
            self.references.append(inst.output["text"])
            audio_paths.append(inst.input["audio_file"].strip().lower())
        self.save_predictions(audio_paths)
    
    def evaluate(self) -> Dict[str, float]:
        acc = exact_match_accuracy(self.predictions, self.references)
        return {"accuracy": acc}
    

class NoteQualitiesAnalysis(BaseTask):
    def _parse_data(self, task_data: Dict[str, Any]) -> List[Instance]:
        return [Instance(input=d["input"], output=d["output"], id=d["id"]) 
                for d in task_data["data"]]

    def _get_choice_candidate(self, data: Dict) -> Dict:
        choices = []
        for item in data['data']:
            choices.append(','.join(item['output']["text"]).strip().lower())
        choices = list(set(choices))
        return choices

    def run_inference(self):
        audio_paths = []
        for inst in tqdm.tqdm(self.data):  
            audio_path = os.path.join(self.audio_dir, inst.input["audio_file"])
            question = inst.input["prompt"]
            prompt = f"Please listen to the music and then detect the note quality of the given music. The candidate annotation is {self.choice_candidate}. Please output **the qualities which are present in this note** from the provided candidate music note quality candidate categories, and **DO NOT** output any other words. Questions: {question}\nAnswer:"
            try:
                response = self.model.generate(prompt, audio_path=audio_path)
            except Exception as e:
                print("Error audio: {}".format(inst.input["audio_file"]))
                response = "None"
                continue
            self.predictions.append(response)
            self.references.append(','.join(inst.output["text"]))
            audio_paths.append(inst.input["audio_file"].strip().lower())
        self.save_predictions(audio_paths)
    
    def evaluate(self) -> Dict[str, float]:
        acc = exact_match_accuracy(self.predictions, self.references)
        return {"accuracy": acc}


class OpenAQA(BaseTask):
    def _parse_data(self, task_data: Dict[str, Any]) -> List[Instance]:
        return [Instance(input=d["input"], output=d["output"], id=d["id"]) 
                for d in task_data["data"]]

    def _get_choice_candidate(self, data: Dict) -> Dict:
        choices = []
        for item in data['data']:
            choices.append(item['output']["text"].strip().lower())
        choices = list(set(choices))
        return choices

    def run_inference(self):
        audio_paths = []
        for inst in tqdm.tqdm(self.data):
            audio_path = os.path.join(self.audio_dir, inst.input["audio_file"])
            question = inst.input["prompt"]
            prompt = f"Please listen to the audio and then answer the question. Questions: {question}\nAnswer:"
            try:
                response = self.model.generate(prompt, audio_path=audio_path)
            except Exception as e:
                print("Error audio: {}".format(inst.input["audio_file"]))
                response = "None"
                continue
            self.predictions.append(response)
            self.references.append(inst.output["text"])
            audio_paths.append(inst.input["audio_file"])
        self.save_predictions(audio_paths)

    def evaluate(self) -> Dict[str, float]:
        acc = bleu_evaluation(self.predictions, self.references)
        return {"accuracy": acc}


class SoundEventClassification(BaseTask):
    def _parse_data(self, task_data: Dict[str, Any]) -> List[Instance]:
        return [Instance(input=d["input"], output=d["output"], id=d["id"]) 
                for d in task_data["data"]]

    def _get_choice_candidate(self, data: Dict) -> Dict:
        choices = []
        for item in data['data']:
            choices.append(item['output']["text"].strip().lower())
        choices = list(set(choices))
        return choices

    def run_inference(self):
        audio_paths = []
        for inst in tqdm.tqdm(self.data):
            audio_path = os.path.join(self.audio_dir, inst.input["audio_file"])
            question = inst.input["prompt"]
            prompt = f"Please listen to the music and then detect the happening event of the given audio. The candidate annotation is {self.choice_candidate}. Please output **only one event** from the provided candidate events,, and **DO NOT** output any other words. Questions: {question}\nAnswer:"
            try:
                response = self.model.generate(prompt, audio_path=audio_path)
            except Exception as e:
                print("Error audio: {}".format(inst.input["audio_file"]))
                response = "None"
                continue
            self.predictions.append(response)
            self.references.append(inst.output["text"])
            audio_paths.append(inst.input["audio_file"])
        self.save_predictions(audio_paths)

    def evaluate(self) -> Dict[str, float]:
        acc = exact_match_accuracy(self.predictions, self.references)
        return {"accuracy": acc}


class SpeechCommand(BaseTask):
    def _parse_data(self, task_data: Dict[str, Any]) -> List[Instance]:
        return [Instance(input=d["input"], output=d["output"], id=d["id"]) 
                for d in task_data["data"]]

    def _get_choice_candidate(self, data: Dict) -> Dict:
        choices = []
        for item in data['data']:
            choices.append(item['output']["text"].strip().lower())
        choices = list(set(choices))
        return choices

    def run_inference(self):
        audio_paths = []
        for inst in tqdm.tqdm(self.data):
            audio_path = os.path.join(self.audio_dir, inst.input["audio_file"].replace('\\', '/'))
            question = inst.input["prompt"]
            prompt = f"Please listen to the audio and then detect the speech command of the given audio. The candidate annotation is {self.choice_candidate}. Please output **only one command** from the provided candidate commands, and **DO NOT** output any other words. Questions: {question}\nAnswer:"
            try:
                response = self.model.generate(prompt, audio_path=audio_path)
            except Exception as e:
                print("Error audio: {}".format(inst.input["audio_file"]))
                response = "None"
                continue
            self.predictions.append(response)
            self.references.append(inst.output["text"].strip().lower())
            audio_paths.append(inst.input["audio_file"])
        self.save_predictions(audio_paths)

    def evaluate(self) -> Dict[str, float]:
        acc = exact_match_accuracy(self.predictions, self.references)
        return {"accuracy": acc}


class SpeechEmotionRecognition(BaseTask):
    def _parse_data(self, task_data: Dict[str, Any]) -> List[Instance]:
        return [Instance(input=d["input"], output=d["output"], id=d["id"]) 
                for d in task_data["data"]]

    def _get_choice_candidate(self, data: Dict) -> Dict:
        choices = []
        for item in data['data']:
            choices.append(item['output']["text"].strip().lower())
        choices = list(set(choices))
        return choices

    def run_inference(self):
        audio_paths = []
        for inst in tqdm.tqdm(self.data):
            audio_path = os.path.join(self.audio_dir, inst.input["audio_file"])
            question = inst.input["prompt"]
            prompt = f"Please listen to the audio and then detect the emotion of the given audio. The candidate annotation is {self.choice_candidate}. Please output **only one emotion** from the provided candidate emotions, and **DO NOT** output any other words. Questions: {question}\nAnswer:"
            try:
                response = self.model.generate(prompt, audio_path=audio_path)
            except Exception as e:
                print("Error audio: {}".format(inst.input["audio_file"]))
                response = "None"
                continue
            self.predictions.append(response)
            self.references.append(inst.output["text"].strip().lower())
            audio_paths.append(inst.input["audio_file"])
        self.save_predictions(audio_paths)

    def evaluate(self) -> Dict[str, float]:
        acc = exact_match_accuracy(self.predictions, self.references)
        return {"accuracy": acc}


class VocalSoundClassification(BaseTask):
    def _parse_data(self, task_data: Dict[str, Any]) -> List[Instance]:
        return [Instance(input=d["input"], output=d["output"], id=d["id"]) 
                for d in task_data["data"]]

    def _get_choice_candidate(self, data: Dict) -> Dict:
        choices = []
        for item in data['data']:
            choices.append(item['output']["text"].strip().lower())
        choices = list(set(choices))
        return choices

    def run_inference(self):
        audio_paths = []
        for inst in tqdm.tqdm(self.data):
            audio_path = os.path.join(self.audio_dir, inst.input["audio_file"])
            question = inst.input["prompt"]
            prompt = f"Please listen to the audio and then detect the vocal sound category of the given audio. The candidate annotation is {self.choice_candidate}. Please output **only one vocal sound category** from the provided candidate vocal sounds, and **DO NOT** output any other words. Questions: {question}\nAnswer:"
            try:
                response = self.model.generate(prompt, audio_path=audio_path)
            except Exception as e:
                print("Error audio: {}".format(inst.input["audio_file"]))
                response = "None"
                continue
            self.predictions.append(response)
            self.references.append(inst.output["text"].strip().lower())
            audio_paths.append(inst.input["audio_file"])
        self.save_predictions(audio_paths)

    def evaluate(self) -> Dict[str, float]:
        acc = exact_match_accuracy(self.predictions, self.references)
        return {"accuracy": acc}


class VocalTechniqueDetection(BaseTask):
    def _parse_data(self, task_data: Dict[str, Any]) -> List[Instance]:
        return [Instance(input=d["input"], output=d["output"], id=d["id"]) 
                for d in task_data["data"]]

    def _get_choice_candidate(self, data: Dict) -> Dict:
        choices = []
        for item in data['data']:
            choices.append(item['output']["text"].strip().lower())
        choices = list(set(choices))
        return choices

    def run_inference(self):
        audio_paths = []
        for inst in tqdm.tqdm(self.data):
            audio_path = os.path.join(self.audio_dir, inst.input["audio_file"].replace('\\', '/'))
            question = inst.input["prompt"]
            prompt = f"Please listen to the audio and then detect the vocal technique of the given audio. The candidate annotations are scales, arpeggios, long tones, and excerpts. Please output **only one vocal technique** from the provided candidate vocal techniques, and **DO NOT** output any other words. Questions: {question}\nAnswer:"
            try:
                response = self.model.generate(prompt, audio_path=audio_path)
            except Exception as e:
                print("Error audio: {}".format(inst.input["audio_file"]))
                response = "None"
                continue
            self.predictions.append(response)
            self.references.append(inst.output["text"].strip().lower())
            audio_paths.append(inst.input["audio_file"])
        self.save_predictions(audio_paths)

    def evaluate(self) -> Dict[str, float]:
        acc = exact_match_accuracy(self.predictions, self.references)
        return {"accuracy": acc}


def log_performance_csv(model_name, task_name, metric, score, root_path, output_file='prediction.json'):
    import csv
    file_exists = os.path.isfile(os.path.join(root_path, output_file))

    row_data = {
        'model': model_name,
        'task': task_name,
        'metric': metric,
        'score': str(score),
    }

    with open(os.path.join(root_path, output_file), mode='a', newline='', encoding='utf-8') as f:
        writer = csv.DictWriter(f, fieldnames=row_data.keys())
        if not file_exists:
            writer.writeheader()

        writer.writerow(row_data)


def log_performance_json(model_name, task_name, metric, score, root_path, output_file='prediction.json'):
    import json
    log_data = {
        'model': model_name,
        'task': task_name,
        'metric': metric,
        'score': str(score),
    }
    
    log_file_path = os.path.join(root_path, output_file)
    
    if os.path.exists(log_file_path):
        with open(log_file_path, 'r') as f:
            existing_data = json.load(f)
    else:
        existing_data = []

    existing_data.append(log_data)

    with open(log_file_path, 'w', encoding='utf-8') as f:
        json.dump(existing_data, f, indent=4)
    

def log_performance_detail(model_name, task_name, metrics, root_path, output_file='performance_log.csv'):
    import csv
    file_path = os.path.join(root_path, output_file)
    file_exists = os.path.isfile(file_path)
    
    # Retrieve the main indicator values from the metrics dictionary
    metric_value = None
    if isinstance(metrics, dict):
        # Select metrics based on priority
        for key in ['accuracy', 'f1', 'micro_f1', 'bleu4', 'rougeL', 'code_bleu', 'MAE']:
            if key in metrics:
                metric_value = metrics[key]
                break
        if metric_value is None and len(metrics) > 0:
            # If no priority metric is found, use the first metric
            metric_value = list(metrics.values())[0]
    else:
        metric_value = metrics

    # Simplify the file name, keeping only the last part
    model_name = model_name.split('/')[-1]
    
    if file_exists:
        # Read existing data
        rows = []
        tasks = set()
        with open(file_path, 'r', newline='', encoding='utf-8') as f:
            reader = csv.reader(f)
            header = next(reader, ['task', model_name])  # If the file is empty, use the default header
            if len(header) == 1:  # If there is only the task column, add the model column
                header.append(model_name)
            rows.append(header)

            # Read existing data and update
            for row in reader:
                if row[0] == task_name:  # If the same task is found, update the value
                    row = [task_name, str(metric_value)]
                tasks.add(row[0])
                rows.append(row)

            # If it is a new task, add a new row
            if task_name not in tasks:
                rows.append([task_name, str(metric_value)])
    else:
        # Create a new file
        rows = [
            ['task', model_name],
            [task_name, str(metric_value)]
        ]

    # Write all data
    with open(file_path, 'w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerows(rows)


if __name__ == "__main__":

    import argparse
    # Parse command line arguments
    parser = argparse.ArgumentParser(description="Run audio understanding tasks")
    parser.add_argument('-m', '--model_name', type=str, required=True, help='Name of the audio understanding model to use')
    parser.add_argument('-d', '--data_dir', type=str, default='./audio/understanding/', help='Directory containing task data')
    parser.add_argument('-o', '--output_dir', type=str, default='./audio/predictions/understanding/', help='Directory to save predictions')
    parser.add_argument('-r', '--root_path', type=str, default='./', help='Root path for logging performance')
    parser.add_argument('-t', '--task_names', type=str, nargs='+',
                        help='List of task names to run (default: AccentClassification AccentSexClassification AcousticSceneClassification)')
    args = parser.parse_args()

    # model_name = 'Qwen2-Audio-7B-Instruct'
    # data_dir = './understanding/'
    # output_dir = f'./predictions/understanding/{model_name}'
    # root_path = './'

    model = AudioComprehensionModel(model_name=args.model_name)


    task_name_list = [
        'AccentClassification', 'AccentSexClassification', 'AcousticSceneClassification',
        'AnimalSoundClassification', 'AudioCaptioning', 'AudioCaptioningClotho',
        'AudioQA', 'BirdSoundDetection', 'EnvironmentSoundRecognition',
        'IntentClassification', 'MusicGenreClassification',
        'MusicInstrumentClassification', 'MusicInstrumentSourceAnalysis',
        'MusicPitchAnalysis', 'NoteQualitiesAnalysis', 'OpenAQA',
        'SingerIdentification', 'SoundEventClassification',
        'SpeakerIdentification', 'SpeechCommand',
        'SpeechEmotionRecognition', 'VocalSoundClassification',
        'VocalTechniqueDetection'
    ]
    if args.task_names is None or len(args.task_names) == 0:
        args.task_names = task_name_list
    
    for task_name in args.task_names: # os.listdir(data_dir):

        # Dynamically get the class by its name
        if task_name in globals():  # Ensure the class is defined in the current scope
            task_class = globals()[task_name]
        else:
            # Optionally, handle cases where the class is not found
            print(f"Task {task_name} is not defined in the current scope.")
            continue

        # Initialize the task class
        import glob
        json_file_list = glob.glob(os.path.join(args.data_dir, task_name, "*.json"))
        if len(json_file_list) == 0:
            print(f"No JSON files found for task: {task_name}")
            continue
        elif len(json_file_list) > 1:
            print(f"Multiple JSON files found for task: {task_name}, using the first one: {json_file_list[0]}")
            task_annotation_data = json_file_list[0]
        else:
            task_annotation_data = json_file_list[0]
        task = task_class(
            task_data=task_annotation_data,
            model=model,
            audio_dir=os.path.join(args.data_dir, task_name, 'audios'),
            output_dir=args.output_dir
        )
        
        # Run inference for the task
        # This should generate audio files based on the task's data
        print(f"Running inference for task: {task_name}")
        task.run_inference()
        # if you want to save the predictions, you need to rewrite the save_predictions() in each Task class depending on your need, and call task.save_predictions() after task.run_inference() or inside the run_inference method.


        # Evaluate the task, return a dictionary of metrics
        # For example, {'FAD_score': 0.123}
        eval_results = task.evaluate()   
        print("Task name: ", task_name, "Evaluation results:", eval_results)
        log_performance_json(
            model_name=args.model_name, 
            task_name=task_name, 
            metric=list(eval_results.keys())[0].split('_')[0],   # CLAP_score
            score=eval_results[list(eval_results.keys())[0]],  # e.g., 0.123
            root_path=args.data_dir)

    # or you can run the tasks one by one like below:
    # task_name = 'AcousticSceneClassification'
    # task = AcousticSceneClassification(
    #     task_data=os.path.join(data_dir, f"{task_name}/annotation.json"),
    #     model=model,
    #     audio_dir=os.path.join(data_dir, f"{task_name}/audios"),
    #     output_dir=output_dir)
    # task.run_inference()
    # print(task.evaluate())