File size: 172,241 Bytes
11e4790
 
c567be4
 
9e3b21a
6530075
3bdba8e
 
 
 
 
 
d363c44
b7fa139
d363c44
3bdba8e
b7fa139
3c4e755
 
 
3bdba8e
 
 
8080a34
3bdba8e
3c4e755
330365b
8080a34
e9909ed
 
7ed5900
a69bace
02dd3ba
 
3bdba8e
 
 
 
 
 
 
 
 
 
 
 
 
2cf6264
3bdba8e
 
 
1d575bc
3bdba8e
 
 
8080a34
3bdba8e
2cf6264
 
4641328
2cf6264
 
 
3bdba8e
 
 
 
 
 
1d575bc
3bdba8e
1d575bc
3bdba8e
 
 
8080a34
3bdba8e
2cf6264
 
f2016da
2cf6264
 
 
3bdba8e
 
 
 
 
 
e9909ed
6afedbf
e1d77be
8080a34
11e4790
2cf6264
8080a34
3bdba8e
 
 
 
 
 
 
 
 
 
2cf6264
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4641328
 
 
 
 
 
 
 
 
 
 
 
 
 
2cf6264
 
 
 
 
 
 
 
4641328
2cf6264
 
 
3bdba8e
 
 
 
c282048
3bdba8e
c282048
1491bd4
a931b41
330365b
a931b41
 
 
 
 
 
 
7ed5900
66d6a91
7ed5900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a931b41
 
 
 
 
 
 
1ae05ec
 
 
 
143b0eb
 
 
 
 
 
1ae05ec
143b0eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ae05ec
38a8c25
 
 
d770843
 
20cf22c
d770843
 
 
38a8c25
 
 
 
 
 
 
a48473e
 
 
 
 
 
 
 
 
 
 
 
 
a931b41
b300db2
 
 
 
 
 
a028c47
f99c291
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bdba8e
 
 
 
8414f72
 
 
c567be4
 
8414f72
c567be4
 
 
 
 
f4b741f
ef94623
e8ac9fc
 
ef94623
30e87ad
 
81954df
30e87ad
 
 
 
 
81954df
30e87ad
915c63d
c567be4
 
 
 
 
 
 
 
 
3bdba8e
 
b0d34ae
 
 
 
 
 
 
 
 
 
 
 
e950bce
a11ae70
 
 
e950bce
a11ae70
e950bce
cf25313
 
 
 
 
 
 
 
 
 
 
 
 
901bdeb
10f0966
 
 
 
 
d363c44
 
 
7935a4b
 
 
d363c44
 
 
 
 
901bdeb
3bdba8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7935a4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bdba8e
 
 
 
 
 
998d544
 
2cf6264
 
 
 
 
 
 
 
998d544
1491bd4
 
1d575bc
 
 
 
 
3bdba8e
2e1a0a6
1d575bc
3bdba8e
 
 
 
 
 
 
 
 
 
 
 
 
 
1d575bc
 
 
 
 
 
 
 
 
c683e79
 
 
1d575bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c683e79
1d575bc
 
3bdba8e
1d575bc
 
 
 
 
 
 
 
3bdba8e
1d575bc
3bdba8e
7e9bce0
 
 
1eefa78
7e9bce0
 
7c98c01
 
 
 
7e9bce0
1d575bc
9b999c7
1d575bc
 
 
 
9b999c7
 
 
 
 
938aee2
7935a4b
a11ae70
ef2b19a
938aee2
e950bce
 
a41dfa9
3bdba8e
915c4c3
a11ae70
 
 
 
3c4e755
b6d28cd
a11ae70
 
ef2b19a
 
 
 
 
 
 
6a6dfe0
f99c291
1643087
1d575bc
6835560
1d575bc
901bdeb
c1d56d4
1d575bc
3bdba8e
7935a4b
3bdba8e
d56466d
af9f8f3
1d575bc
3ffa0fc
dddad30
1d575bc
901bdeb
3bdba8e
 
 
 
9594b3b
52d5702
cdaf4d8
6835560
7935a4b
901bdeb
cdaf4d8
7935a4b
3bdba8e
cdaf4d8
 
 
 
901bdeb
3bdba8e
 
 
cdaf4d8
7935a4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a41dfa9
b5201dc
 
 
 
 
a41dfa9
 
af9f8f3
 
 
 
 
 
b5201dc
a41dfa9
354502a
 
a41dfa9
c567be4
3c4e755
 
 
 
 
 
 
2cf6264
3c4e755
2cf6264
 
 
 
 
 
 
4ab6d4c
2cf6264
 
 
 
3c4e755
2cf6264
3c4e755
c05c5f9
d22eec5
d346e8c
d22eec5
 
 
d346e8c
 
3c4e755
3bdba8e
 
c683e79
 
 
 
 
c567be4
3bdba8e
 
aaa2911
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c0db57
1d575bc
5c0db57
 
 
 
8080a34
 
1d575bc
 
 
 
 
 
 
 
 
aaa2911
1d575bc
 
aaa2911
1d575bc
 
 
aaa2911
8080a34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aaa2911
5c0db57
1d575bc
aaa2911
8080a34
 
 
 
 
5c0db57
 
8080a34
aaa2911
 
 
 
 
 
1d575bc
3bdba8e
 
 
3a7f306
3bdba8e
 
 
 
1d575bc
3bdba8e
 
10f0966
3bdba8e
 
 
 
10f0966
3bdba8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d575bc
aaa2911
 
 
5c0db57
 
aaa2911
 
 
 
5c0db57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aaa2911
 
 
 
 
3bdba8e
 
 
 
 
 
 
1d575bc
ee689dc
 
3bdba8e
ee689dc
 
 
 
3bdba8e
ee689dc
1d575bc
ee689dc
 
10f0966
ee689dc
 
 
 
10f0966
ee689dc
3ffa0fc
ee689dc
 
 
 
 
 
 
 
 
 
1d575bc
ee689dc
 
 
 
 
 
 
 
 
3ffa0fc
 
 
1d575bc
aaa2911
 
 
 
 
 
 
 
 
 
 
5c0db57
aaa2911
3ffa0fc
aaa2911
 
 
3ffa0fc
dddad30
afee61a
dddad30
 
 
 
afee61a
dddad30
 
 
 
 
1d575bc
b872b89
 
 
3a7f306
b872b89
 
3bdba8e
b872b89
6835560
1d575bc
ee689dc
b872b89
10f0966
b872b89
 
 
 
10f0966
b872b89
 
 
 
 
 
 
 
 
 
 
 
6835560
1d575bc
b872b89
 
 
 
 
 
a766c13
b872b89
 
 
 
 
 
 
 
 
 
 
a766c13
 
1d575bc
aaa2911
6777045
6835560
 
 
 
 
 
 
 
 
aaa2911
 
6777045
aaa2911
 
 
 
 
 
6777045
aaa2911
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c0db57
aaa2911
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c0db57
aaa2911
 
915c63d
aaa2911
ef94623
1d575bc
1643087
 
 
3bdba8e
1643087
 
 
 
3bdba8e
1643087
1d575bc
1643087
10f0966
1643087
 
 
 
10f0966
1643087
 
f28acdd
1643087
 
 
 
 
 
 
 
 
 
1d575bc
1643087
 
 
 
 
 
 
 
2b5e430
 
 
 
 
 
 
 
 
 
f4b5a4c
1d575bc
aaa2911
3bdba8e
901bdeb
 
 
 
 
 
 
 
3bdba8e
 
aaa2911
 
 
 
 
 
 
 
 
 
1d575bc
5c0db57
1d575bc
3bdba8e
1d575bc
3bdba8e
 
1d575bc
3bdba8e
1d575bc
6835560
 
 
 
 
 
 
 
 
1d575bc
6835560
10f0966
6835560
 
 
 
10f0966
6835560
aaa2911
 
1d575bc
 
6835560
 
 
1d575bc
aaa2911
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6835560
5c0db57
aaa2911
 
6835560
aaa2911
 
 
6835560
aaa2911
6835560
3bdba8e
 
 
2b5e430
f5c871b
 
 
f207269
 
 
 
 
f5c871b
 
1d575bc
3bdba8e
 
 
 
 
 
 
 
1d575bc
3bdba8e
 
10f0966
3bdba8e
 
 
 
10f0966
3bdba8e
7935a4b
 
 
 
 
 
1d575bc
7935a4b
 
 
 
 
 
10f0966
 
7935a4b
8080a34
 
 
 
 
 
 
 
 
 
 
 
ef94623
3bdba8e
 
 
 
 
 
330365b
3bdba8e
 
 
1d575bc
3bdba8e
 
 
 
 
 
 
 
 
 
 
367ea1f
1d575bc
aaa2911
 
 
 
 
 
 
5c0db57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aaa2911
 
 
 
 
 
 
 
 
 
10f0966
5c0db57
aaa2911
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8080a34
 
 
 
 
 
 
aaa2911
 
 
3bdba8e
1d575bc
aaa2911
 
 
 
 
 
 
 
 
 
 
 
5c0db57
aaa2911
 
7935a4b
aaa2911
7935a4b
8080a34
 
 
 
 
 
 
 
 
 
 
 
 
5c0db57
 
 
8080a34
 
5c0db57
8080a34
 
 
5c0db57
 
 
 
 
8080a34
 
 
 
 
 
 
 
 
 
 
 
5c0db57
8080a34
 
 
 
 
 
 
3bdba8e
 
 
 
 
 
 
 
8bcb25f
3bdba8e
 
 
 
 
b5c6a12
3bdba8e
 
 
 
b5c6a12
 
3bdba8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
367ea1f
3bdba8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10f0966
3bdba8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef94623
3bdba8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c205271
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bdba8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c0db57
 
 
 
3bdba8e
57ecc14
3bdba8e
 
 
 
 
 
 
 
10f0966
3bdba8e
 
10f0966
3bdba8e
 
 
 
 
 
 
 
 
 
 
c205271
 
 
3bdba8e
 
 
 
 
 
 
 
 
 
c205271
 
 
 
 
3bdba8e
 
 
 
 
 
 
901bdeb
 
 
 
 
 
 
 
 
10f0966
901bdeb
3a7f306
901bdeb
3a7f306
901bdeb
c205271
 
 
901bdeb
 
 
 
 
 
3bdba8e
 
 
 
 
 
 
 
 
7935a4b
3bdba8e
 
10f0966
7935a4b
3bdba8e
 
 
 
 
 
 
 
3a7f306
901bdeb
 
3bdba8e
 
10f0966
901bdeb
3a7f306
3bdba8e
 
10f0966
901bdeb
3bdba8e
 
 
10f0966
7935a4b
 
 
 
 
 
 
 
 
c205271
 
 
7935a4b
 
 
 
 
 
 
10f0966
7935a4b
 
 
 
 
 
 
 
 
10f0966
7935a4b
6835560
 
 
 
 
 
 
 
10f0966
6835560
4ab6d4c
 
 
 
 
 
 
 
3bdba8e
 
7935a4b
3bdba8e
1d575bc
3bdba8e
7935a4b
 
3a7f306
1d575bc
7935a4b
3a7f306
6835560
1d575bc
7935a4b
3bdba8e
 
7935a4b
 
 
 
 
 
 
 
1d575bc
6835560
 
7935a4b
6835560
 
 
7935a4b
1d575bc
6835560
 
 
 
 
 
 
 
1d575bc
6835560
 
3bdba8e
 
 
89086d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10f0966
89086d1
 
 
 
 
09f6fb1
89086d1
 
 
 
 
 
 
 
 
 
 
b7a82ac
89086d1
 
 
 
 
 
 
 
 
 
 
 
 
 
10f0966
89086d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10f0966
89086d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7a82ac
89086d1
 
 
 
 
 
 
 
 
 
 
 
 
10f0966
89086d1
 
 
 
3bdba8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10f0966
3bdba8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8080a34
3bdba8e
 
 
 
 
 
 
 
 
 
 
 
10f0966
3bdba8e
 
 
10f0966
3bdba8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10f0966
3bdba8e
8080a34
 
 
 
3bdba8e
 
 
 
8080a34
 
 
 
 
 
 
 
 
 
 
 
 
3bdba8e
 
 
 
 
 
 
10f0966
 
 
 
 
 
 
 
 
3bdba8e
 
8080a34
3bdba8e
 
10f0966
 
 
 
 
8080a34
 
 
 
 
 
 
 
 
 
 
 
 
 
10f0966
3bdba8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2cf6264
 
 
 
 
 
7935a4b
 
 
 
6835560
7935a4b
2cf6264
7935a4b
 
2cf6264
7935a4b
901bdeb
7935a4b
 
 
 
cabf77a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7935a4b
 
 
4641328
 
 
 
 
 
 
 
 
 
 
 
2cf6264
 
 
8080a34
3bdba8e
2cf6264
3bdba8e
2cf6264
 
 
 
 
901bdeb
2cf6264
 
 
6835560
4641328
2cf6264
4641328
 
 
 
 
 
8080a34
 
 
 
 
 
 
 
 
 
 
 
 
 
4641328
 
8080a34
2cf6264
 
4641328
2cf6264
 
 
 
 
 
 
 
4641328
 
2cf6264
4641328
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6835560
2cf6264
 
 
6835560
8080a34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2cf6264
 
9e3b21a
2cf6264
10f0966
 
 
 
 
 
 
 
 
8080a34
 
 
 
 
10f0966
 
8080a34
 
10f0966
 
 
 
 
 
 
 
 
901bdeb
2cf6264
 
7935a4b
2cf6264
3bdba8e
7935a4b
 
 
 
 
 
 
 
901bdeb
7935a4b
 
2cf6264
7935a4b
3bdba8e
 
7935a4b
 
3bdba8e
 
 
10f0966
7935a4b
 
3bdba8e
7935a4b
2cf6264
 
8080a34
2cf6264
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7819025
2cf6264
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6835560
2cf6264
6835560
2cf6264
b7a82ac
2cf6264
 
 
 
 
6835560
2cf6264
 
0b9c276
8080a34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2cf6264
7935a4b
2cf6264
 
 
 
 
 
 
 
 
 
 
c5051e3
2cf6264
 
 
 
 
 
 
 
 
 
 
 
 
3bdba8e
2cf6264
3bdba8e
 
 
3a7f306
2cf6264
 
c5051e3
2cf6264
 
c5051e3
2cf6264
 
 
 
3bdba8e
2cf6264
3bdba8e
 
8080a34
3bdba8e
 
 
 
 
2cf6264
 
b7a82ac
2cf6264
 
 
 
 
 
 
 
 
 
c5051e3
2cf6264
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5051e3
3bdba8e
 
 
 
 
 
 
 
2cf6264
3bdba8e
 
 
 
 
2cf6264
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7a82ac
2cf6264
 
 
 
 
 
 
3bdba8e
 
 
 
 
a93f361
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5051e3
2cf6264
c683e79
 
901bdeb
 
 
6835560
c683e79
 
 
 
 
 
 
 
2cf6264
 
c683e79
4641328
 
 
 
c683e79
4641328
 
 
 
 
 
 
 
 
 
 
 
 
 
c683e79
4641328
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c683e79
4641328
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8080a34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c683e79
 
 
 
 
 
 
901bdeb
10f0966
 
901bdeb
2cf6264
10f0966
2cf6264
 
901bdeb
2cf6264
 
901bdeb
 
2cf6264
10f0966
2cf6264
 
 
 
901bdeb
2cf6264
 
 
10f0966
2cf6264
10f0966
 
2cf6264
10f0966
 
 
 
 
 
 
 
901bdeb
8080a34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c683e79
 
3bdba8e
 
 
 
 
 
 
 
 
 
 
 
 
 
901bdeb
 
 
 
 
2cf6264
 
3bdba8e
1d575bc
 
3bdba8e
 
 
 
 
 
 
 
 
c205271
3bdba8e
 
 
 
901bdeb
 
 
2cf6264
1d575bc
 
 
3bdba8e
901bdeb
 
 
1d575bc
 
bedad3b
6835560
c683e79
 
 
 
7935a4b
 
 
 
6835560
 
 
 
 
 
c683e79
 
 
 
7935a4b
 
c683e79
 
 
15e1a1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bdba8e
15e1a1f
3bdba8e
 
b7a82ac
 
 
 
 
 
 
c683e79
 
 
 
7935a4b
c683e79
16c7814
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bdba8e
 
901bdeb
3bdba8e
 
 
 
901bdeb
3bdba8e
 
 
16c7814
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bdba8e
16c7814
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bdba8e
16c7814
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bdba8e
 
b7a82ac
 
8080a34
7935a4b
 
 
901bdeb
7935a4b
901bdeb
7935a4b
3a7f306
7935a4b
 
901bdeb
 
89086d1
 
3a7f306
89086d1
3a7f306
89086d1
 
3a7f306
89086d1
3a7f306
901bdeb
3a7f306
901bdeb
 
89086d1
 
3a7f306
89086d1
3a7f306
89086d1
 
3a7f306
89086d1
3a7f306
901bdeb
3a7f306
7935a4b
 
 
901bdeb
7935a4b
901bdeb
7935a4b
3a7f306
7935a4b
 
 
 
 
901bdeb
7935a4b
901bdeb
7935a4b
6835560
7935a4b
 
6835560
 
 
 
 
 
 
 
 
 
4ab6d4c
 
 
 
 
 
 
 
 
 
3bdba8e
 
 
 
 
 
 
 
 
 
10f0966
2cf6264
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
901bdeb
 
 
10f0966
6835560
 
 
 
901bdeb
2cf6264
10f0966
 
 
 
 
901bdeb
c683e79
10f0966
 
 
 
 
 
c5051e3
2cf6264
 
 
 
 
 
 
 
 
 
8080a34
2cf6264
 
 
 
 
 
 
 
 
10f0966
 
2cf6264
 
 
 
 
 
3bdba8e
10f0966
 
3bdba8e
2cf6264
 
 
 
c683e79
915c63d
c567be4
1d575bc
c683e79
3bdba8e
6835560
3bdba8e
901bdeb
3bdba8e
7935a4b
3bdba8e
 
 
 
 
901bdeb
3bdba8e
 
 
 
c683e79
 
 
 
7935a4b
6835560
c683e79
 
 
 
7935a4b
 
c683e79
 
 
 
 
 
dddad30
 
c683e79
 
 
 
 
 
3bdba8e
c683e79
28092cb
 
c683e79
 
 
 
 
 
3bdba8e
c567be4
3bdba8e
10f0966
 
 
 
 
 
 
 
 
 
 
 
3bdba8e
10f0966
 
 
 
 
 
 
 
 
 
 
1d575bc
10f0966
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d575bc
10f0966
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d575bc
10f0966
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d575bc
10f0966
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d575bc
10f0966
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d575bc
10f0966
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ab6d4c
 
 
 
 
 
 
 
 
 
1d575bc
4ab6d4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10f0966
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8080a34
 
10f0966
 
8080a34
 
 
 
10f0966
 
8080a34
10f0966
8080a34
 
10f0966
 
8080a34
10f0966
8080a34
 
10f0966
 
 
 
 
8080a34
 
10f0966
 
8080a34
 
 
 
10f0966
 
8080a34
10f0966
8080a34
 
10f0966
 
8080a34
10f0966
8080a34
 
10f0966
 
 
 
 
8080a34
 
10f0966
 
8080a34
 
 
 
10f0966
 
8080a34
10f0966
8080a34
 
10f0966
 
8080a34
10f0966
8080a34
 
10f0966
 
 
3bdba8e
 
901bdeb
 
 
 
 
 
 
 
 
 
 
2cf6264
 
1d575bc
901bdeb
3bdba8e
 
 
901bdeb
3bdba8e
 
8080a34
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
import gradio as gr
import pandas as pd
import requests
from docx import Document
import os
from openai import OpenAI
from groq import Groq
import uuid
from gtts import gTTS
import math
from pydub import AudioSegment


from youtube_transcript_api import YouTubeTranscriptApi
from youtube_transcript_api._errors import NoTranscriptFound
import yt_dlp

from moviepy.editor import VideoFileClip
from pytube import YouTube
import os
import io
import time
import json
from datetime import datetime, timezone, timedelta
from urllib.parse import urlparse, parse_qs

from google.cloud import storage
from google.cloud import bigquery
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from googleapiclient.http import MediaIoBaseDownload
from googleapiclient.http import MediaIoBaseUpload

from educational_material import EducationalMaterial
from storage_service import GoogleCloudStorage

import boto3

from chatbot import Chatbot

is_env_local = os.getenv("IS_ENV_LOCAL", "false") == "true"
print(f"is_env_local: {is_env_local}")

print("===gr__version__===")
print(gr.__version__)

# KEY CONFIG
if is_env_local:
    with open("local_config.json") as f:
        config = json.load(f)
        IS_ENV_PROD = "False"
        PASSWORD = config["PASSWORD"] 
        GCS_KEY = json.dumps(config["GOOGLE_APPLICATION_CREDENTIALS_JSON"])
        DRIVE_KEY = json.dumps(config["GOOGLE_APPLICATION_CREDENTIALS_JSON"])
        GBQ_KEY = json.dumps(config["GOOGLE_APPLICATION_CREDENTIALS_JSON"])
        OPEN_AI_KEY = config["OPEN_AI_KEY"]
        OPEN_AI_ASSISTANT_ID_GPT4_BOT1 = config["OPEN_AI_ASSISTANT_ID_GPT4_BOT1"]
        OPEN_AI_ASSISTANT_ID_GPT3_BOT1 = config["OPEN_AI_ASSISTANT_ID_GPT3_BOT1"]
        OPEN_AI_MODERATION_BOT1 = config["OPEN_AI_MODERATION_BOT1"]
        OPEN_AI_KEY_BOT2 = config["OPEN_AI_KEY_BOT2"]
        OPEN_AI_ASSISTANT_ID_GPT4_BOT2 = config["OPEN_AI_ASSISTANT_ID_GPT4_BOT2"]
        OPEN_AI_ASSISTANT_ID_GPT3_BOT2 = config["OPEN_AI_ASSISTANT_ID_GPT3_BOT2"]
        GROQ_API_KEY = config["GROQ_API_KEY"]
        JUTOR_CHAT_KEY = config["JUTOR_CHAT_KEY"]
        AWS_ACCESS_KEY = config["AWS_ACCESS_KEY"]
        AWS_SECRET_KEY = config["AWS_SECRET_KEY"]
        AWS_REGION_NAME = config["AWS_REGION_NAME"]
        OUTPUT_PATH = config["OUTPUT_PATH"]
        
else:
    IS_ENV_PROD = os.getenv("IS_ENV_PROD", "False")
    PASSWORD = os.getenv("PASSWORD")
    GCS_KEY = os.getenv("GOOGLE_APPLICATION_CREDENTIALS_JSON")
    DRIVE_KEY = os.getenv("GOOGLE_APPLICATION_CREDENTIALS_JSON")
    GBQ_KEY = os.getenv("GOOGLE_APPLICATION_CREDENTIALS_JSON")
    OPEN_AI_KEY = os.getenv("OPEN_AI_KEY")
    OPEN_AI_ASSISTANT_ID_GPT4_BOT1 = os.getenv("OPEN_AI_ASSISTANT_ID_GPT4_BOT1")
    OPEN_AI_ASSISTANT_ID_GPT3_BOT1 = os.getenv("OPEN_AI_ASSISTANT_ID_GPT3_BOT1")
    OPEN_AI_MODERATION_BOT1 = os.getenv("OPEN_AI_MODERATION_BOT1", OPEN_AI_KEY)
    OPEN_AI_KEY_BOT2 = os.getenv("OPEN_AI_KEY_BOT2")
    OPEN_AI_ASSISTANT_ID_GPT4_BOT2 = os.getenv("OPEN_AI_ASSISTANT_ID_GPT4_BOT2")
    OPEN_AI_ASSISTANT_ID_GPT3_BOT2 = os.getenv("OPEN_AI_ASSISTANT_ID_GPT3_BOT2")
    GROQ_API_KEY = os.getenv("GROQ_API_KEY")
    JUTOR_CHAT_KEY = os.getenv("JUTOR_CHAT_KEY")
    AWS_ACCESS_KEY = os.getenv("AWS_ACCESS_KEY")
    AWS_SECRET_KEY = os.getenv("AWS_SECRET_KEY")
    AWS_REGION_NAME = 'us-west-2'
    OUTPUT_PATH = 'videos'

TRANSCRIPTS = []
CURRENT_INDEX = 0
CHAT_LIMIT = 5

# CLIENTS CONFIG
GBQ_CLIENT = bigquery.Client.from_service_account_info(json.loads(GBQ_KEY))
GROQ_CLIENT = Groq(api_key=GROQ_API_KEY)
GCS_SERVICE = GoogleCloudStorage(GCS_KEY)
GCS_CLIENT = GCS_SERVICE.client
BEDROCK_CLIENT = boto3.client(
    service_name="bedrock-runtime",
    aws_access_key_id=AWS_ACCESS_KEY,
    aws_secret_access_key=AWS_SECRET_KEY,
    region_name=AWS_REGION_NAME,
)

# check open ai access
def check_open_ai_access(open_ai_api_key):
    # set key in OpenAI client and run to check status, if it is work, return True
    client = OpenAI(api_key=open_ai_api_key)
    try:
        response = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "user", "content": "This is a test."},
            ],
        )
        if response.choices[0].message.content:
            return True
        else:
            return False
    except Exception as e:
        print(f"Error: {str(e)}")
        return False

open_ai_api_key_assistant_id_list = [
    {
        "account":"bot1", 
        "open_ai_api_key": OPEN_AI_KEY, 
        "assistant_gpt4_id": OPEN_AI_ASSISTANT_ID_GPT4_BOT1, 
        "assistant_gpt3_id": OPEN_AI_ASSISTANT_ID_GPT3_BOT1,
        "moderation": OPEN_AI_MODERATION_BOT1
    },
    {
        "account":"bot2", 
        "open_ai_api_key": OPEN_AI_KEY_BOT2, 
        "assistant_gpt4_id": OPEN_AI_ASSISTANT_ID_GPT4_BOT2, 
        "assistant_gpt3_id": OPEN_AI_ASSISTANT_ID_GPT3_BOT2,
        "moderation": OPEN_AI_MODERATION_BOT1
    },
]
for open_ai_api_key_assistant_id in open_ai_api_key_assistant_id_list:
    account = open_ai_api_key_assistant_id["account"]
    open_ai_api_key = open_ai_api_key_assistant_id["open_ai_api_key"]
    if check_open_ai_access(open_ai_api_key):
        OPEN_AI_CLIENT = OpenAI(api_key=open_ai_api_key)
        OPEN_AI_ASSISTANT_ID_GPT4 = open_ai_api_key_assistant_id["assistant_gpt4_id"]
        OPEN_AI_ASSISTANT_ID_GPT3 = open_ai_api_key_assistant_id["assistant_gpt3_id"]
        OPEN_AI_MODERATION_CLIENT = OpenAI(api_key=open_ai_api_key_assistant_id["moderation"])
        print(f"OpenAI access is OK, account: {account}")
        break

# 驗證 password
def verify_password(password):
    if password == PASSWORD:
        return True
    else:
        raise gr.Error("密碼錯誤")

# # ====drive====初始化
def init_drive_service():
    credentials_json_string = DRIVE_KEY
    credentials_dict = json.loads(credentials_json_string)
    SCOPES = ['https://www.googleapis.com/auth/drive']
    credentials = service_account.Credentials.from_service_account_info(
            credentials_dict, scopes=SCOPES)
    service = build('drive', 'v3', credentials=credentials)
    return service

def create_folder_if_not_exists(service, folder_name, parent_id):
    print("检查是否存在特定名称的文件夹,如果不存在则创建")
    query = f"mimeType='application/vnd.google-apps.folder' and name='{folder_name}' and '{parent_id}' in parents and trashed=false"
    response = service.files().list(q=query, spaces='drive', fields="files(id, name)").execute()
    folders = response.get('files', [])
    if not folders:
        # 文件夹不存在,创建新文件夹
        file_metadata = {
            'name': folder_name,
            'mimeType': 'application/vnd.google-apps.folder',
            'parents': [parent_id]
        }
        folder = service.files().create(body=file_metadata, fields='id').execute()
        return folder.get('id')
    else:
        # 文件夹已存在
        return folders[0]['id']

# 检查Google Drive上是否存在文件
def check_file_exists(service, folder_name, file_name):
    query = f"name = '{file_name}' and '{folder_name}' in parents and trashed = false"
    response = service.files().list(q=query).execute()
    files = response.get('files', [])
    return len(files) > 0, files[0]['id'] if files else None

def upload_content_directly(service, file_name, folder_id, content):
    """
    直接将内容上传到Google Drive中的新文件。
    """
    if not file_name:
        raise ValueError("文件名不能为空")
    if not folder_id:
        raise ValueError("文件夹ID不能为空")
    if content is None:  # 允许空字符串上传,但不允许None
        raise ValueError("内容不能为空")
    
    file_metadata = {'name': file_name, 'parents': [folder_id]}
    # 使用io.BytesIO为文本内容创建一个内存中的文件对象
    try:
        with io.BytesIO(content.encode('utf-8')) as fh:
            media = MediaIoBaseUpload(fh, mimetype='text/plain', resumable=True)
            
            print("==content==")
            print(content)
            print("==content==")

            print("==media==")
            print(media)
            print("==media==")
            # 执行上传
            file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
            return file.get('id')
    except Exception as e:
        print(f"上传文件时发生错误: {e}")
        raise  # 重新抛出异常,调用者可以根据需要处理或忽略

def upload_file_directly(service, file_name, folder_id, file_path):
    # 上傳 .json to Google Drive
    file_metadata = {'name': file_name, 'parents': [folder_id]}
    media = MediaFileUpload(file_path, mimetype='application/json')
    file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
    
    
    # return file.get('id')  # 返回文件ID
    return True

def upload_img_directly(service, file_name, folder_id, file_path):
    file_metadata = {'name': file_name, 'parents': [folder_id]}
    media = MediaFileUpload(file_path, mimetype='image/jpeg')
    file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
    return file.get('id')  # 返回文件ID

def download_file_as_string(service, file_id):
    """
    从Google Drive下载文件并将其作为字符串返回。
    """
    request = service.files().get_media(fileId=file_id)
    fh = io.BytesIO()
    downloader = MediaIoBaseDownload(fh, request)
    done = False
    while done is False:
        status, done = downloader.next_chunk()
    fh.seek(0)
    content = fh.read().decode('utf-8')
    return content

def set_public_permission(service, file_id):
    service.permissions().create(
        fileId=file_id,
        body={"type": "anyone", "role": "reader"},
        fields='id',
    ).execute()

def update_file_on_drive(service, file_id, file_content):
    """
    更新Google Drive上的文件内容。
    
    参数:
    - service: Google Drive API服务实例。
    - file_id: 要更新的文件的ID。
    - file_content: 新的文件内容,字符串格式。
    """
    # 将新的文件内容转换为字节流
    fh = io.BytesIO(file_content.encode('utf-8'))
    media = MediaIoBaseUpload(fh, mimetype='application/json', resumable=True)
    
    # 更新文件
    updated_file = service.files().update(
        fileId=file_id,
        media_body=media
    ).execute()
    
    print(f"文件已更新,文件ID: {updated_file['id']}")

# ---- Text file ----
def process_file(password, file):
    verify_password(password)
    
    # 读取文件
    if file.name.endswith('.csv'):
        df = pd.read_csv(file)
        text = df_to_text(df)
    elif file.name.endswith('.xlsx'):
        df = pd.read_excel(file)
        text = df_to_text(df)
    elif file.name.endswith('.docx'):
        text = docx_to_text(file)
    else:
        raise ValueError("Unsupported file type")

    df_string = df.to_string()
    # 宜蘭:移除@XX@符号 to |
    df_string = df_string.replace("@XX@", "|")

    # 根据上传的文件内容生成问题
    questions = generate_questions(df_string)
    summary = generate_summarise(df_string)

    # 返回按钮文本和 DataFrame 字符串
    return questions[0] if len(questions) > 0 else "", \
           questions[1] if len(questions) > 1 else "", \
           questions[2] if len(questions) > 2 else "", \
           summary, \
           df_string

def df_to_text(df):
    # 将 DataFrame 转换为纯文本
    return df.to_string()

def docx_to_text(file):
    # 将 Word 文档转换为纯文本
    doc = Document(file)
    return "\n".join([para.text for para in doc.paragraphs])


# ---- YouTube link ----
def parse_time(time_str):
    """將時間字符串 'HH:MM:SS' 或 'MM:SS' 轉換為 timedelta 物件。"""
    parts = list(map(int, time_str.split(':')))
    if len(parts) == 3:
        hours, minutes, seconds = parts
    elif len(parts) == 2:
        hours = 0  # 沒有小時部分時,將小時設為0
        minutes, seconds = parts
    else:
        raise ValueError("時間格式不正確,應為 'HH:MM:SS' 或 'MM:SS'")
    return timedelta(hours=hours, minutes=minutes, seconds=seconds)

def format_seconds_to_time(seconds):
    """将秒数格式化为 时:分:秒 的形式"""
    hours = int(seconds // 3600)
    minutes = int((seconds % 3600) // 60)
    seconds = int(seconds % 60)
    return f"{hours:02}:{minutes:02}:{seconds:02}"

def extract_youtube_id(url):
    parsed_url = urlparse(url)
    
    if "youtube.com" in parsed_url.netloc:
        # 对于标准链接,视频ID在查询参数'v'中
        query_params = parse_qs(parsed_url.query)
        return query_params.get("v")[0] if "v" in query_params else None
    elif "youtu.be" in parsed_url.netloc:
        # 对于短链接,视频ID是路径的一部分
        return parsed_url.path.lstrip('/')
    else:
        return None

def get_transcript_by_yt_api(video_id):
    transcript_list = YouTubeTranscriptApi.list_transcripts(video_id)
    languages = []
    for t in transcript_list:
        languages.append(t.language_code)
    
    for language in languages:
        try:
            transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=[language])
            print("===transcript===")
            print(transcript)
            print("===transcript===")
            return transcript  # 成功獲取字幕,直接返回結果
        except NoTranscriptFound:
            continue  # 當前語言的字幕沒有找到,繼續嘗試下一個語言
    return None  # 所有嘗試都失敗,返回None

def generate_transcription_by_whisper(video_id):
    youtube_url = f'https://www.youtube.com/watch?v={video_id}'
    codec_name = "mp3"
    outtmpl = f"{OUTPUT_PATH}/{video_id}.%(ext)s"
    ydl_opts = {
        'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': codec_name,
            'preferredquality': '192'
        }],
        'outtmpl': outtmpl,
    }

    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        ydl.download([youtube_url])

    audio_path = f"{OUTPUT_PATH}/{video_id}.{codec_name}"
    full_audio = AudioSegment.from_mp3(audio_path)

    max_part_duration = 10 * 60 * 1000  # 10 minutes
    full_duration = len(full_audio)  # in milliseconds
    parts = math.ceil(full_duration / max_part_duration)
    print(f"parts: {parts}")
    transcription = []

    for i in range(parts):
        print(f"== i: {i}==")
        start_time = i * max_part_duration
        end_time = min((i + 1) * max_part_duration, full_duration)
        print(f"time: {start_time/1000} - {end_time/1000}")
        chunk = full_audio[start_time:end_time]
        chunk_path = f"{OUTPUT_PATH}/{video_id}_part_{i}.{codec_name}"
        chunk.export(chunk_path, format=codec_name)

        try:
            with open(chunk_path, "rb") as chunk_file:
                response = OPEN_AI_CLIENT.audio.transcriptions.create(
                    model="whisper-1",
                    file=chunk_file,
                    response_format="verbose_json",
                    timestamp_granularities=["segment"],
                    prompt="Transcribe the following audio file. if content is chinese, please using 'language: zh-TW' ",
                )
                
                # Adjusting the timestamps for the chunk based on its position in the full audio
                adjusted_segments = [{
                    'text': segment['text'],
                    'start': math.ceil(segment['start'] + start_time / 1000.0),  # Converting milliseconds to seconds
                    'end': math.ceil(segment['end'] + start_time / 1000.0),
                    'duration': math.ceil(segment['end'] - segment['start'])
                } for segment in response.segments]

                transcription.extend(adjusted_segments)
        except Exception as e:
            print(f"Error processing chunk {i}: {str(e)}")

        # Remove temporary chunk files after processing
        os.remove(chunk_path)

    return transcription
 
def get_video_duration(video_id):
    yt = YouTube(f'https://www.youtube.com/watch?v={video_id}')
    try:
        video_duration = yt.length
    except:
        video_duration = None

    print(f"video_duration: {video_duration}")
    
    return video_duration

def process_transcript_and_screenshots_on_gcs(video_id):
    print("====process_transcript_and_screenshots_on_gcs====")
    transcript, exists = get_transcript_from_gcs(video_id)
    if not exists:
        print("Transcript file does not exist, creating new transcript...")
        transcript = generate_transcription_by_whisper(video_id)
        upload_transcript_to_gcs(video_id, transcript)

    # 處理截圖
    is_new_transcript = False
    for entry in transcript:
        if 'img_file_id' not in entry:
            # 檢查 OUTPUT_PATH 是否存在 video_id.mp4
            video_path = f'{OUTPUT_PATH}/{video_id}.mp4'
            if not os.path.exists(video_path):
                # try 5 times 如果都失敗就 raise
                for i in range(5):
                    try:
                        download_youtube_video(video_id)
                        break
                    except Exception as e:
                        if i == 4:
                            raise gr.Error(f"下载视频失败: {str(e)}")
                        time.sleep(5)
            try:
                screenshot_path = screenshot_youtube_video(video_id, entry['start'])
                screenshot_blob_name = f"{video_id}/{video_id}_{entry['start']}.jpg"
                img_file_id = GCS_SERVICE.upload_image_and_get_public_url('video_ai_assistant', screenshot_blob_name, screenshot_path)
                entry['img_file_id'] = img_file_id
                print(f"截图已上传到GCS: {img_file_id}")
                is_new_transcript = True
            except Exception as e:
                print(f"Error processing screenshot: {str(e)}")
    
    if is_new_transcript:
        print("===更新逐字稿文件===")
        upload_transcript_to_gcs(video_id, transcript)

    return transcript

def get_transcript(video_id):
    print("====get_transcript====")
    transcript, exists = get_transcript_from_gcs(video_id)
    if not exists:
        raise gr.Error("逐字稿文件不存在於GCS中。")

    if any('img_file_id' not in entry for entry in transcript):
        raise gr.Error("Some entries in the transcript do not have an associated img_file_id.")

    print("Transcript is verified with all necessary images.")
    return transcript

def get_transcript_from_gcs(video_id):
    print("Checking for transcript in GCS...")
    bucket_name = 'video_ai_assistant'
    transcript_file_name = f'{video_id}_transcript.json'
    transcript_blob_name = f"{video_id}/{transcript_file_name}"
    # Check if the transcript exists in GCS
    is_transcript_exists = GCS_SERVICE.check_file_exists(bucket_name, transcript_blob_name)
    if is_transcript_exists:
        # Download the transcript if it exists
        transcript_text = GCS_SERVICE.download_as_string(bucket_name, transcript_blob_name)
        return json.loads(transcript_text), True
    else:
        print("No transcript found for video ID:", video_id)
        return None, False

def upload_transcript_to_gcs(video_id, transcript):
    print("Uploading updated transcript to GCS...")
    bucket_name = 'video_ai_assistant'
    transcript_file_name = f'{video_id}_transcript.json'
    transcript_blob_name = f"{video_id}/{transcript_file_name}"
    transcript_text = json.dumps(transcript, ensure_ascii=False, indent=2)
    GCS_SERVICE.upload_json_string(bucket_name, transcript_blob_name, transcript_text)
    print("Transcript uploaded successfully.")

def process_youtube_link(password, link, LLM_model=None):
    verify_password(password)

    print("===link===")
    print(link)
    print(LLM_model)
    print("===link===")

    if "youtube.com" in link:
        video_id = extract_youtube_id(link)
    else:
        video_id = link
    print(f"video_id: {video_id}")

    try:
        if IS_ENV_PROD == "True":
            transcript = get_transcript(video_id)
        else:    
            transcript = process_transcript_and_screenshots_on_gcs(video_id)
    except Exception as e:
        error_msg = f" {video_id} 逐字稿錯誤: {str(e)}"
        print("===process_youtube_link error===")
        print(error_msg)
        raise gr.Error(error_msg)

    original_transcript = json.dumps(transcript, ensure_ascii=False, indent=2)
    formatted_transcript = []
    formatted_simple_transcript =[]
    for entry in transcript:
        start_time = format_seconds_to_time(entry['start'])
        end_time = format_seconds_to_time(entry['start'] + entry['duration'])
        embed_url = get_embedded_youtube_link(video_id, entry['start'])
        img_file_id = entry['img_file_id']
        screenshot_path = img_file_id
        line = {
            "start_time": start_time,
            "end_time": end_time,
            "text": entry['text'],
            "embed_url": embed_url,
            "screenshot_path": screenshot_path
        }
        formatted_transcript.append(line)
        # formatted_simple_transcript 只要 start_time, end_time, text
        simple_line = {
            "start_time": start_time,
            "end_time": end_time,
            "text": entry['text']
        }
        formatted_simple_transcript.append(simple_line)

    # 基于逐字稿生成其他所需的输出
    source = "gcs"
    questions_answers = get_questions_answers(video_id, formatted_simple_transcript, source, LLM_model)
    questions_answers_json = json.dumps(questions_answers, ensure_ascii=False, indent=2)
    summary_json = get_video_id_summary(video_id, formatted_simple_transcript, source, LLM_model)
    summary_text = summary_json["summary"]
    summary = summary_json["summary"]
    key_moments_json = get_key_moments(video_id, formatted_simple_transcript, formatted_transcript, source, LLM_model)
    key_moments = key_moments_json["key_moments"]
    key_moments_text = json.dumps(key_moments, ensure_ascii=False, indent=2)
    key_moments_html = get_key_moments_html(key_moments)
    html_content = format_transcript_to_html(formatted_transcript)
    simple_html_content = format_simple_transcript_to_html(formatted_simple_transcript)
    mind_map_json = get_mind_map(video_id, formatted_simple_transcript, source, LLM_model)
    mind_map = mind_map_json["mind_map"]
    mind_map_html = get_mind_map_html(mind_map)
    reading_passage_json = get_reading_passage(video_id, formatted_simple_transcript, source, LLM_model)
    reading_passage_text = reading_passage_json["reading_passage"]
    reading_passage = reading_passage_json["reading_passage"]
    meta_data = get_meta_data(video_id)
    subject = meta_data["subject"]
    grade = meta_data["grade"]

    # 确保返回与 UI 组件预期匹配的输出
    return video_id, \
        questions_answers_json, \
        original_transcript, \
        summary_text, \
        summary, \
        key_moments_text, \
        key_moments_html, \
        mind_map, \
        mind_map_html, \
        html_content, \
        simple_html_content, \
        reading_passage_text, \
        reading_passage, \
        subject, \
        grade
            
def create_formatted_simple_transcript(transcript):
    formatted_simple_transcript = []
    for entry in transcript:
        start_time = format_seconds_to_time(entry['start'])
        end_time = format_seconds_to_time(entry['start'] + entry['duration'])
        line = {
            "start_time": start_time,
            "end_time": end_time,
            "text": entry['text']
        }
        formatted_simple_transcript.append(line)
    return formatted_simple_transcript

def create_formatted_transcript(video_id, transcript):
    formatted_transcript = []
    for entry in transcript:
        start_time = format_seconds_to_time(entry['start'])
        end_time = format_seconds_to_time(entry['start'] + entry['duration'])
        embed_url = get_embedded_youtube_link(video_id, entry['start'])
        img_file_id = entry['img_file_id']
        screenshot_path = img_file_id
        line = {
            "start_time": start_time,
            "end_time": end_time,
            "text": entry['text'],
            "embed_url": embed_url,
            "screenshot_path": screenshot_path
        }
        formatted_transcript.append(line)
    return formatted_transcript

def format_transcript_to_html(formatted_transcript):
    html_content = ""
    for entry in formatted_transcript:
        html_content += f"<h3>{entry['start_time']} - {entry['end_time']}</h3>"
        html_content += f"<p>{entry['text']}</p>"
        html_content += f"<img src='{entry['screenshot_path']}' width='500px' />"
    return html_content

def format_simple_transcript_to_html(formatted_transcript):
    html_content = ""
    for entry in formatted_transcript:
        html_content += f"<h3>{entry['start_time']} - {entry['end_time']}</h3>"
        html_content += f"<p>{entry['text']}</p>"
    return html_content

def get_embedded_youtube_link(video_id, start_time):
    int_start_time = int(start_time)
    embed_url = f"https://www.youtube.com/embed/{video_id}?start={int_start_time}&autoplay=1"
    return embed_url

def download_youtube_video(youtube_id, output_path=OUTPUT_PATH):
    # Construct the full YouTube URL
    youtube_url = f'https://www.youtube.com/watch?v={youtube_id}'

    # Create the output directory if it doesn't exist
    if not os.path.exists(output_path):
        os.makedirs(output_path)
    
    # Download the video
    try:
        yt = YouTube(youtube_url)
        video_stream = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first()
        video_stream.download(output_path=output_path, filename=youtube_id+".mp4")
        print(f"[Pytube] Video downloaded successfully: {output_path}/{youtube_id}.mp4")
    except Exception as e:
        ydl_opts = {
            'format': "bestvideo[height<=720][ext=mp4]",
            'outtmpl': os.path.join(output_path, f'{youtube_id}.mp4'),  # Output filename template
        }
        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            ydl.download([youtube_url])

        print(f"[yt_dlp] Video downloaded successfully: {output_path}/{youtube_id}.mp4")

def screenshot_youtube_video(youtube_id, snapshot_sec):    
    video_path = f'{OUTPUT_PATH}/{youtube_id}.mp4'
    file_name = f"{youtube_id}_{snapshot_sec}.jpg"
    with VideoFileClip(video_path) as video:
        screenshot_path = f'{OUTPUT_PATH}/{file_name}'
        video.save_frame(screenshot_path, snapshot_sec)
    
    return screenshot_path


# ---- Web ----
# def process_web_link(link):
#     # 抓取和解析网页内容
#     response = requests.get(link)
#     soup = BeautifulSoup(response.content, 'html.parser')
#     return soup.get_text()


# ---- LLM Generator ----
def split_data(df_string, word_base=100000):
    """Split the JSON string based on a character length base and then chunk the parsed JSON array."""
    if isinstance(df_string, str):
        data_str_cnt = len(df_string)
        data = json.loads(df_string)
    else:
        data_str_cnt = len(str(df_string))
        data = df_string
        
    # Calculate the number of parts based on the length of the string
    n_parts = data_str_cnt // word_base + (1 if data_str_cnt % word_base != 0 else 0)
    print(f"Number of Parts: {n_parts}")
    
    # Calculate the number of elements each part should have
    part_size = len(data) // n_parts if n_parts > 0 else len(data)
    
    segments = []
    for i in range(n_parts):
        start_idx = i * part_size
        end_idx = min((i + 1) * part_size, len(data))
        # Serialize the segment back to a JSON string
        segment = json.dumps(data[start_idx:end_idx])
        segments.append(segment)
    
    return segments

def generate_content_by_open_ai(sys_content, user_content, response_format=None, model_name=None):
    print("LLM using OPEN AI")
    if model_name == "gpt-4-turbo":
        model = "gpt-4-turbo"
    else:
        model = "gpt-4o"
    print(f"model: {model}")

    messages = [
        {"role": "system", "content": sys_content},
        {"role": "user", "content": user_content}
    ]
    request_payload = {
        "model": model,
        "messages": messages,
        "max_tokens": 4000,
    }

    if response_format is not None:
        request_payload["response_format"] = response_format

    response = OPEN_AI_CLIENT.chat.completions.create(**request_payload)
    content = response.choices[0].message.content.strip()
    return content

# def generate_content_by_bedrock(sys_content, user_content):
#     print("LLM using REDROCK")
#     messages = [
#         {"role": "user", "content": user_content +"(如果是 JSON 格式,value 的引號,請用單引號,或是用反斜線+雙引號,避免 JSON Decoder error )"}
#     ]
#     model_id = "anthropic.claude-3-sonnet-20240229-v1:0"
#     print(f"model_id: {model_id}")
#     # model_id = "anthropic.claude-3-haiku-20240307-v1:0"
#     kwargs = {
#         "modelId": model_id,
#         "contentType": "application/json",
#         "accept": "application/json",
#         "body": json.dumps({
#             "anthropic_version": "bedrock-2023-05-31",
#             "max_tokens": 4000,
#             "system": sys_content,
#             "messages": messages
#         })
#     }
#     response = BEDROCK_CLIENT.invoke_model(**kwargs)
#     response_body = json.loads(response.get('body').read())
#     content = response_body.get('content')[0].get('text')
#     return content

def generate_content_by_LLM(sys_content, user_content, response_format=None, LLM_model=None, model_name=None):
    # 使用 OpenAI 生成基于上传数据的问题

    # if LLM_model == "anthropic-claude-3-sonnet":
    #     print(f"LLM: {LLM_model}")
    #     content = generate_content_by_bedrock(sys_content, user_content)
    # else:
    print(f"LLM: {LLM_model}")
    print(f"model_name: {model_name}")
    content = generate_content_by_open_ai(sys_content, user_content, response_format, model_name=model_name)

    print("=====content=====")
    print(content)
    print("=====content=====")

    return content

def get_reading_passage(video_id, df_string, source, LLM_model=None):
    if source == "gcs":
        print("===get_reading_passage on gcs===")
        bucket_name = 'video_ai_assistant'
        file_name = f'{video_id}_reading_passage_latex.json'
        blob_name = f"{video_id}/{file_name}"
        # 检查 reading_passage 是否存在
        is_file_exists = GCS_SERVICE.check_file_exists(bucket_name, blob_name)
        if not is_file_exists:
            reading_passage = generate_reading_passage(df_string, LLM_model)
            reading_passage_json = {"reading_passage": str(reading_passage)}
            reading_passage_text = json.dumps(reading_passage_json, ensure_ascii=False, indent=2)
            GCS_SERVICE.upload_json_string(bucket_name, blob_name, reading_passage_text)
            print("reading_passage已上传到GCS")
        else:
            # reading_passage已存在,下载内容
            print("reading_passage已存在于GCS中")
            reading_passage_text = GCS_SERVICE.download_as_string(bucket_name, blob_name)
            reading_passage_json = json.loads(reading_passage_text)

    elif source == "drive":
        print("===get_reading_passage on drive===")
        service = init_drive_service()
        parent_folder_id = '1GgI4YVs0KckwStVQkLa1NZ8IpaEMurkL'
        folder_id = create_folder_if_not_exists(service, video_id, parent_folder_id)
        file_name = f'{video_id}_reading_passage.json'

        # 检查 reading_passage 是否存在
        exists, file_id = check_file_exists(service, folder_id, file_name)
        if not exists:
            reading_passage = generate_reading_passage(df_string)
            reading_passage_json = {"reading_passage": str(reading_passage)}
            reading_passage_text = json.dumps(reading_passage_json, ensure_ascii=False, indent=2)
            upload_content_directly(service, file_name, folder_id, reading_passage_text)
            print("reading_passage已上傳到Google Drive")
        else:
            # reading_passage已存在,下载内容
            print("reading_passage已存在于Google Drive中")
            reading_passage_text = download_file_as_string(service, file_id)

    return reading_passage_json

def generate_reading_passage(df_string, LLM_model=None):
    print("===generate_reading_passage===")
    segments = split_data(df_string, word_base=100000)
    all_content = []
    model_name = "gpt-4-turbo"
    # model_name = "gpt-4o"

    for segment in segments:
        sys_content = "你是一個擅長資料分析跟影片教學的老師,user 為學生,請精讀資料文本,自行判斷資料的種類,使用 zh-TW"
        user_content = f"""
          # 文本 {segment}

          # rules:
          - 根據文本,抓取重點
          - 去除人類講課時口語的問答句,重新拆解成文章,建立適合閱讀語句通順的 Reading Passage
          - 只需要專注提供 Reading Passage,字數在 500 字以內
          - 敘述中,請把數學或是專業術語,用 Latex 包覆($...$)
          - 加減乘除、根號、次方等等的運算式口語也換成 LATEX 數學符號
          
          # restrictions:
          - 請一定要使用繁體中文 zh-TW,這很重要
          - 產生的結果不要前後文解釋,也不要敘述這篇文章怎麼產生的
          - 請直接給出文章,不用介紹怎麼處理的或是文章字數等等
          - 字數在 500 字以內  
        """
        content = generate_content_by_LLM(sys_content, user_content, response_format=None, LLM_model=LLM_model, model_name=model_name)
        all_content.append(content + "\n")

    # 將所有生成的閱讀理解段落合併成一個完整的文章
    final_content = "\n".join(all_content)
    return final_content

def text_to_speech(video_id, text):
    tts = gTTS(text, lang='en')
    filename = f'{video_id}_reading_passage.mp3'
    tts.save(filename)
    return filename

def get_mind_map(video_id, df_string, source, LLM_model=None):
    if source == "gcs":
        print("===get_mind_map on gcs===")
        gcs_client = GCS_CLIENT
        bucket_name = 'video_ai_assistant'
        file_name = f'{video_id}_mind_map.json'
        blob_name = f"{video_id}/{file_name}"
        # 检查檔案是否存在
        is_file_exists = GCS_SERVICE.check_file_exists(bucket_name, blob_name)
        if not is_file_exists:
            mind_map = generate_mind_map(df_string, LLM_model)
            mind_map_json = {"mind_map": str(mind_map)}
            mind_map_text = json.dumps(mind_map_json, ensure_ascii=False, indent=2)
            GCS_SERVICE.upload_json_string(bucket_name, blob_name, mind_map_text)
            print("mind_map已上傳到GCS")
        else:
            # mindmap已存在,下载内容
            print("mind_map已存在于GCS中")
            mind_map_text = GCS_SERVICE.download_as_string(bucket_name, blob_name)
            mind_map_json = json.loads(mind_map_text)

    elif source == "drive":
        print("===get_mind_map on drive===")
        service = init_drive_service()
        parent_folder_id = '1GgI4YVs0KckwStVQkLa1NZ8IpaEMurkL'
        folder_id = create_folder_if_not_exists(service, video_id, parent_folder_id)
        file_name = f'{video_id}_mind_map.json'

        # 检查檔案是否存在
        exists, file_id = check_file_exists(service, folder_id, file_name)
        if not exists:
            mind_map = generate_mind_map(df_string, LLM_model)
            mind_map_json = {"mind_map": str(mind_map)}
            mind_map_text = json.dumps(mind_map_json, ensure_ascii=False, indent=2)
            upload_content_directly(service, file_name, folder_id, mind_map_text)
            print("mind_map已上傳到Google Drive")
        else:
            # mindmap已存在,下载内容
            print("mind_map已存在于Google Drive中")
            mind_map_text = download_file_as_string(service, file_id)
            mind_map_json = json.loads(mind_map_text)

    return mind_map_json

def generate_mind_map(df_string, LLM_model=None):
    print("===generate_mind_map===")
    segments = split_data(df_string, word_base=100000)
    all_content = []

    for segment in segments:
        sys_content = "你是一個擅長資料分析跟影片教學的老師,user 為學生,請精讀資料文本,自行判斷資料的種類,使用 zh-TW"
        user_content = f"""
            請根據 {segment} 文本建立 markdown 心智圖
            注意:不需要前後文敘述,直接給出 markdown 文本即可
            這對我很重要
        """
        content = generate_content_by_LLM(sys_content, user_content, response_format=None, LLM_model=LLM_model, model_name=None)
        all_content.append(content + "\n")

    # 將所有生成的閱讀理解段落合併成一個完整的文章
    final_content = "\n".join(all_content)
    return final_content

def get_mind_map_html(mind_map):
    mind_map_markdown = mind_map.replace("```markdown", "").replace("```", "")

    mind_map_html = f"""
    <div class="markmap">
        <script type="text/template">
            {mind_map_markdown}
        </script>
    </div>
    """
    return mind_map_html

def get_video_id_summary(video_id, df_string, source, LLM_model=None):
    if source == "gcs":
        print("===get_video_id_summary on gcs===")
        bucket_name = 'video_ai_assistant'
        file_name = f'{video_id}_summary_markdown.json'
        summary_file_blob_name = f"{video_id}/{file_name}"
        # 检查 summary_file 是否存在
        is_summary_file_exists = GCS_SERVICE.check_file_exists(bucket_name, summary_file_blob_name)
        if not is_summary_file_exists:
            meta_data = get_meta_data(video_id)
            summary = generate_summarise(df_string, meta_data, LLM_model)
            summary_json = {"summary": str(summary)}
            summary_text = json.dumps(summary_json, ensure_ascii=False, indent=2)
            GCS_SERVICE.upload_json_string(bucket_name, summary_file_blob_name, summary_text)
            print("summary已上传到GCS")
        else:
            # summary已存在,下载内容
            print("summary已存在于GCS中")
            summary_text = GCS_SERVICE.download_as_string(bucket_name, summary_file_blob_name)
            summary_json = json.loads(summary_text)

    elif source == "drive":
        print("===get_video_id_summary===")
        service = init_drive_service()
        parent_folder_id = '1GgI4YVs0KckwStVQkLa1NZ8IpaEMurkL'
        folder_id = create_folder_if_not_exists(service, video_id, parent_folder_id)
        file_name = f'{video_id}_summary.json'

        # 检查逐字稿是否存在
        exists, file_id = check_file_exists(service, folder_id, file_name)
        if not exists:
            meta_data = get_meta_data(video_id)
            summary = generate_summarise(df_string, meta_data, LLM_model)
            summary_json = {"summary": str(summary)}
            summary_text = json.dumps(summary_json, ensure_ascii=False, indent=2)
            
            try:
                upload_content_directly(service, file_name, folder_id, summary_text)
                print("summary已上傳到Google Drive")

            except Exception as e:
                error_msg = f" {video_id} 摘要錯誤: {str(e)}"
                print("===get_video_id_summary error===")
                print(error_msg)
                print("===get_video_id_summary error===")
        else:
            # 逐字稿已存在,下载逐字稿内容
            print("summary已存在Google Drive中")
            summary_text = download_file_as_string(service, file_id)
            summary_json = json.loads(summary_text)
        
    return summary_json
    
def generate_summarise(df_string, metadata=None, LLM_model=None):
    print("===generate_summarise===")
    # 使用 OpenAI 生成基于上传数据的问题
    if metadata:
        title = metadata.get("title", "")
        subject = metadata.get("subject", "")
        grade = metadata.get("grade", "")
    else:
        title = ""
        subject = ""
        grade = ""

    segments = split_data(df_string, word_base=100000)
    all_content = []

    for segment in segments:
        sys_content = "你是一個擅長資料分析跟影片教學的老師,user 為學生,請精讀資料文本,自行判斷資料的種類,使用 zh-TW"
        user_content = f"""
            課程名稱:{title}
            科目:{subject}
            年級:{grade}

            請根據內文: {segment}
            
            格式為 Markdown
            如果有課程名稱,請圍繞「課程名稱」為學習重點,進行重點整理,不要整理跟情境故事相關的問題
            整體摘要在一百字以內
            重點概念列出 bullet points,至少三個,最多五個
            以及可能的結論與結尾延伸小問題提供學生作反思
            敘述中,請把數學或是專業術語,用 Latex 包覆($...$)
            加減乘除、根號、次方等等的運算式口語也換成 LATEX 數學符號

            整體格式為:
            ## 🌟 主題:{{title}} (如果沒有 title 就省略)
            ## 📚 整體摘要
                - (一個 bullet point....)

            ## 🔖 重點概念
                - xxx
                - xxx
                - xxx
            
            ## 💡 為什麼我們要學這個?
                - (一個 bullet point....)
            
            ## ❓ 延伸小問題
                - (一個 bullet point....請圍繞「課程名稱」為學習重點,進行重點整理,不要整理跟情境故事相關的問題)
        """
        content = generate_content_by_LLM(sys_content, user_content, response_format=None, LLM_model=LLM_model, model_name=None)
        all_content.append(content + "\n")

    if len(all_content) > 1:
        all_content_cnt = len(all_content)
        all_content_str = json.dumps(all_content)
        sys_content = "你是一個擅長資料分析跟影片教學的老師,user 為學生,請精讀賛料文本,自行判斷賛料的種類,使用 zh-TW"
        user_content = f"""
            課程名稱:{title}
            科目:{subject}
            年級:{grade}

            請根據內文: {all_content_str}
            共有 {all_content_cnt} 段,請縱整成一篇摘要
            
            格式為 Markdown
            如果有課程名稱,請圍繞「課程名稱」為學習重點,進行重點整理,不要整理跟情境故事相關的問題
            整體摘要在 {all_content_cnt} 百字以內
            重點概念列出 bullet points,至少三個,最多十個
            以及可能的結論與結尾延伸小問題提供學生作反思
            敘述中,請把數學或是專業術語,用 Latex 包覆($...$)
            加減乘除、根號、次方等等的運算式口語也換成 LATEX 數學符號

            整體格式為:
            ## 🌟 主題:{{title}} (如果沒有 title 就省略)
            ## 📚 整體摘要
                - ( {all_content_cnt} 個 bullet point....)

            ## 🔖 重點概念
                - xxx
                - xxx
                - xxx
            
            ## 💡 為什麼我們要學這個?
                - ( {all_content_cnt}  個 bullet point....)
            
            ## ❓ 延伸小問題
                - ( {all_content_cnt}  個 bullet point....請圍繞「課程名稱」為學習重點,進行重點整理,不要整理跟情境故事相關的問題)
        """
        final_content = generate_content_by_LLM(sys_content, user_content, response_format=None, LLM_model=LLM_model, model_name=None)
    else:
        final_content = all_content[0]

    return final_content

def get_questions(video_id, df_string, source="gcs", LLM_model=None):
    if source == "gcs":
        # 去 gcs 確認是有有 video_id_questions.json
        print("===get_questions on gcs===")
        gcs_client = GCS_CLIENT
        bucket_name = 'video_ai_assistant'
        file_name = f'{video_id}_questions.json'
        blob_name = f"{video_id}/{file_name}"
        # 检查檔案是否存在
        is_questions_exists = GCS_SERVICE.check_file_exists(bucket_name, blob_name)
        if not is_questions_exists:
            questions = generate_questions(df_string, LLM_model)
            questions_text = json.dumps(questions, ensure_ascii=False, indent=2)
            GCS_SERVICE.upload_json_string(bucket_name, blob_name, questions_text)
            print("questions已上傳到GCS")
        else:
            # 逐字稿已存在,下载逐字稿内容
            print("questions已存在于GCS中")
            questions_text = GCS_SERVICE.download_as_string(bucket_name, blob_name)
            questions = json.loads(questions_text)
    
    elif source == "drive":
        # 去 g drive 確認是有有 video_id_questions.json
        print("===get_questions===")
        service = init_drive_service()
        parent_folder_id = '1GgI4YVs0KckwStVQkLa1NZ8IpaEMurkL'
        folder_id = create_folder_if_not_exists(service, video_id, parent_folder_id)
        file_name = f'{video_id}_questions.json'

        # 检查檔案是否存在
        exists, file_id = check_file_exists(service, folder_id, file_name)
        if not exists:
            questions = generate_questions(df_string, LLM_model)
            questions_text = json.dumps(questions, ensure_ascii=False, indent=2)
            upload_content_directly(service, file_name, folder_id, questions_text)
            print("questions已上傳到Google Drive")
        else:
            # 逐字稿已存在,下载逐字稿内容
            print("questions已存在于Google Drive中")
            questions_text = download_file_as_string(service, file_id)
            questions = json.loads(questions_text)

    q1 = questions[0] if len(questions) > 0 else ""
    q2 = questions[1] if len(questions) > 1 else ""
    q3 = questions[2] if len(questions) > 2 else ""
    print("=====get_questions=====")
    print(f"q1: {q1}")
    print(f"q2: {q2}")
    print(f"q3: {q3}")
    print("=====get_questions=====")
    return q1, q2, q3

def generate_questions(df_string, LLM_model=None):
    print("===generate_questions===")
    # 使用 OpenAI 生成基于上传数据的问题
    if isinstance(df_string, str):
        df_string_json = json.loads(df_string)
    else:
        df_string_json = df_string
    content_text = ""

    for entry in df_string_json:
        content_text += entry["text"] + ","

    sys_content = "你是一個擅長資料分析跟影片教學的老師,user 為學生,請精讀資料文本,自行判斷資料的種類,並用既有資料為本質猜測用戶可能會問的問題,使用 zh-TW"
    user_content = f"""
        請根據 {content_text} 生成三個問題,並用 JSON 格式返回
        一定要使用 zh-TW,這非常重要!
        
        EXAMPLE:
        {{
            questions:
            [q1的敘述text, q2的敘述text, q3的敘述text]
        }}
    """
    response_format = { "type": "json_object" }
    questions = generate_content_by_LLM(sys_content, user_content, response_format, LLM_model, model_name=None)
    questions_list = json.loads(questions)["questions"]
    print("=====json_response=====")
    print(questions_list)
    print("=====json_response=====")

    return questions_list

def get_questions_answers(video_id, df_string, source="gcs", LLM_model=None):
    if source == "gcs":
        try:
            print("===get_questions_answers on gcs===")
            bucket_name = 'video_ai_assistant'
            file_name = f'{video_id}_questions_answers.json'
            blob_name = f"{video_id}/{file_name}"
            # 检查檔案是否存在
            is_questions_answers_exists = GCS_SERVICE.check_file_exists(bucket_name, blob_name)
            if not is_questions_answers_exists:
                questions_answers = generate_questions_answers(df_string, LLM_model)
                questions_answers_text = json.dumps(questions_answers, ensure_ascii=False, indent=2)
                GCS_SERVICE.upload_json_string(bucket_name, blob_name, questions_answers_text)
                print("questions_answers已上傳到GCS")
            else:
                # questions_answers已存在,下载内容
                print("questions_answers已存在于GCS中")
                questions_answers_text = GCS_SERVICE.download_as_string(bucket_name, blob_name)
                questions_answers = json.loads(questions_answers_text)
        except Exception as e:
            print(f"Error getting questions_answers: {str(e)}")
            questions_list = get_questions(video_id, df_string, source, LLM_model)
            questions_answers = [{"question": q, "answer": ""} for q in questions_list]

    return questions_answers

def generate_questions_answers(df_string, LLM_model=None):
    print("===generate_questions_answers===")
    segments = split_data(df_string, word_base=100000)
    all_content = []

    for segment in segments:
        sys_content = "你是一個擅長資料分析跟影片教學的老師,user 為學生,請精讀資料文本,自行判斷資料的種類,使用 zh-TW"
        user_content = f"""
            請根據 {segment} 生成三個問題跟答案,主要與學科有關,不要問跟情節故事相關的問題
            答案要在最後標示出處【參考:00:01:05】,請根據時間軸 start_time 來標示
            請確保問題跟答案都是繁體中文 zh-TW
            答案不用是標準答案,而是帶有啟發性的蘇格拉底式問答,讓學生思考本來的問題,以及該去參考的時間點
            並用 JSON 格式返回 list ,請一定要給三個問題跟答案,且要裝在一個 list 裡面
            k-v pair 的 key 是 question, value 是 answer

            EXAMPLE:
            {{
            "questions_answers":
            [
                {{question: q1的敘述text, answer: q1的答案text【參考:00:01:05】}}, 
                {{question: q2的敘述text, answer: q2的答案text【參考:00:32:05】}},
                {{question: q3的敘述text, answer: q3的答案text【參考:01:03:35】}}
            ]
            }}
        """
        response_format = { "type": "json_object" }
        content = generate_content_by_LLM(sys_content, user_content, response_format, LLM_model, model_name=None)
        content_json = json.loads(content)["questions_answers"]
        all_content += content_json

        print("=====all_content=====")
        print(all_content)
        print("=====all_content=====")

    return all_content

def change_questions(password, df_string):
    verify_password(password)

    questions = generate_questions(df_string)
    q1 = questions[0] if len(questions) > 0 else ""
    q2 = questions[1] if len(questions) > 1 else ""
    q3 = questions[2] if len(questions) > 2 else ""
    print("=====get_questions=====")
    print(f"q1: {q1}")
    print(f"q2: {q2}")
    print(f"q3: {q3}")
    print("=====get_questions=====")
    return q1, q2, q3

def get_key_moments(video_id, formatted_simple_transcript, formatted_transcript, source, LLM_model=None):
    if source == "gcs":
        print("===get_key_moments on gcs===")
        bucket_name = 'video_ai_assistant'
        file_name = f'{video_id}_key_moments.json'
        blob_name = f"{video_id}/{file_name}"
        # 检查檔案是否存在
        is_key_moments_exists = GCS_SERVICE.check_file_exists(bucket_name, blob_name)
        if not is_key_moments_exists:
            key_moments = generate_key_moments(formatted_simple_transcript, formatted_transcript, LLM_model)
            key_moments_json = {"key_moments": key_moments}
            key_moments_text = json.dumps(key_moments_json, ensure_ascii=False, indent=2)
            GCS_SERVICE.upload_json_string(bucket_name, blob_name, key_moments_text)
            print("key_moments已上傳到GCS")
        else:
            # key_moments已存在,下载内容
            print("key_moments已存在于GCS中")
            key_moments_text = GCS_SERVICE.download_as_string(bucket_name, blob_name)
            key_moments_json = json.loads(key_moments_text)
             # 檢查 key_moments 是否有 keywords
            print("===檢查 key_moments 是否有 keywords===")
            has_keywords_added = False
            for key_moment in key_moments_json["key_moments"]:
                if "keywords" not in key_moment:
                    transcript = key_moment["transcript"]
                    key_moment["keywords"] = generate_key_moments_keywords(transcript, LLM_model)
                    print("===keywords===")
                    print(key_moment["keywords"])
                    print("===keywords===")
                    has_keywords_added = True
            if has_keywords_added:
                key_moments_text = json.dumps(key_moments_json, ensure_ascii=False, indent=2)
                GCS_SERVICE.upload_json_string(bucket_name, blob_name, key_moments_text)
                key_moments_text = GCS_SERVICE.download_as_string(bucket_name, blob_name)
                key_moments_json = json.loads(key_moments_text)
            # 檢查 key_moments 是否有 suggested_images
            print("===檢查 key_moments 是否有 suggested_images===")
            has_suggested_images_added = False
            for key_moment in key_moments_json["key_moments"]:
                if "suggested_images" not in key_moment:
                    key_moment["suggested_images"] = generate_key_moments_suggested_images(key_moment)
                    has_suggested_images_added = True
            if has_suggested_images_added:
                key_moments_text = json.dumps(key_moments_json, ensure_ascii=False, indent=2)
                GCS_SERVICE.upload_json_string(bucket_name, blob_name, key_moments_text)
                key_moments_text = GCS_SERVICE.download_as_string(bucket_name, blob_name)
                key_moments_json = json.loads(key_moments_text)

    elif source == "drive":
        print("===get_key_moments on drive===")
        service = init_drive_service()
        parent_folder_id = '1GgI4YVs0KckwStVQkLa1NZ8IpaEMurkL'
        folder_id = create_folder_if_not_exists(service, video_id, parent_folder_id)
        file_name = f'{video_id}_key_moments.json'

        # 检查檔案是否存在
        exists, file_id = check_file_exists(service, folder_id, file_name)
        if not exists:
            key_moments = generate_key_moments(formatted_simple_transcript, formatted_transcript, LLM_model)
            key_moments_json = {"key_moments": key_moments}
            key_moments_text = json.dumps(key_moments_json, ensure_ascii=False, indent=2)
            upload_content_directly(service, file_name, folder_id, key_moments_text)
            print("key_moments已上傳到Google Drive")
        else:
            # key_moments已存在,下载内容
            print("key_moments已存在于Google Drive中")
            key_moments_text = download_file_as_string(service, file_id)
            key_moments_json = json.loads(key_moments_text)
    
    return key_moments_json

def generate_key_moments(formatted_simple_transcript, formatted_transcript, LLM_model=None):
    print("===generate_key_moments===")
    segments = split_data(formatted_simple_transcript, word_base=100000)
    all_content = []

    for segment in segments:
        sys_content = "你是一個擅長資料分析跟影片教學的老師,user 為學生,請精讀資料文本,自行判斷資料的種類,使用 zh-TW"
        user_content = f"""
            # 文本:{segment} 

            # Rule
            1. 請根據文本,提取出 5 段重點摘要,並給出對應的時間軸,每一段重點的時間軸範圍大於1分鐘,但小於 1/3 總逐字稿長度
            2. 內容當中,如果有列舉方法、模式或是工具,就用 bulletpoint 或是 編號方式 列出,並在列舉部分的頭尾用[]匡列(example: FAANG 是以下五間公司: [1. A公司 2.B公司 3.C公司 4.D公司 5.E公司 ],...)
            3. 注意不要遺漏任何一段時間軸的內容 從零秒開始,以這種方式分析整個文本,從零秒開始分析,直到結束。這很重要
            4. 結尾的時間如果有總結性的話,也要擷取
            5. 如果頭尾的情節不是重點,特別是打招呼或是介紹自己是誰、或是finally say goodbye 就是不重要的情節,就不用擷取
            6. 關鍵字從transcript extract to keyword,保留專家名字、專業術語、年份、數字、期刊名稱、地名、數學公式
            7. 最後再檢查一遍,text, keywords please use or transfer to zh-TW, it's very important

            # restrictions
            1. 請一定要用 zh-TW,這非常重要!
            2. 如果是疑似主播、主持人的圖片場景,且沒有任何有用的資訊,請不要選取
            3. 如果頭尾的情節不是重點,特別是打招呼或是介紹自己是誰、或是finally say goodbye 就是不重要的情節,就不用擷取

            Example: retrun JSON 
            {{key_moments:[{{
                "start": "00:00", 
                "end": "01:00", 
                "text": "逐字稿的重點摘要",
                "keywords": ["關鍵字", "關鍵字"]
                }}]
            }}
        """
        response_format = { "type": "json_object" }
        content = generate_content_by_LLM(sys_content, user_content, response_format, LLM_model, model_name=None)
        key_moments = json.loads(content)["key_moments"]

        # "transcript": get text from formatted_simple_transcript
        for moment in key_moments:
            start_time = parse_time(moment['start'])
            end_time = parse_time(moment['end'])
            # 使用轉換後的 timedelta 物件進行時間
            moment['transcript'] = ",".join([entry['text'] for entry in formatted_simple_transcript
                                            if start_time <= parse_time(entry['start_time']) <= end_time])

        print("=====key_moments=====")
        print(key_moments)
        print("=====key_moments=====")
        image_links = {entry['start_time']: entry['screenshot_path'] for entry in formatted_transcript}

        for moment in key_moments:
            start_time = parse_time(moment['start'])
            end_time = parse_time(moment['end'])
            # 使用轉換後的 timedelta 物件進行時間比較
            moment_images = [image_links[time] for time in image_links 
                            if start_time <= parse_time(time) <= end_time]
            moment['images'] = moment_images

            # 檢查是否有 suggested_images
            if "suggested_images" not in moment:
                moment["suggested_images"] = generate_key_moments_suggested_images(moment, LLM_model)
                print("===moment_suggested_images===")
                print(moment["suggested_images"])
                print("===moment_suggested_images===")

        all_content += key_moments

    return all_content

def generate_key_moments_keywords(transcript, LLM_model=None):
    print("===generate_key_moments_keywords===")
    segments = split_data(transcript, word_base=100000)
    all_content = []

    for segment in segments:
        sys_content = "你是一個擅長資料分析跟影片教學的老師,user 為學生,請精讀資料文本,自行判斷資料的種類,使用 zh-TW"
        user_content = f"""
            transcript  extract to keyword
            保留專家名字、專業術語、年份、數字、期刊名稱、地名、數學公式、數學表示式、物理化學符號,
            不用給上下文,直接給出關鍵字,使用 zh-TW,用逗號分隔, example: 關鍵字1, 關鍵字2
            transcript:{segment}
        """
        content = generate_content_by_LLM(sys_content, user_content, response_format=None, LLM_model=LLM_model, model_name=None)
        keywords = content.strip().split(",")
        all_content += keywords
    
    return all_content

def generate_key_moments_suggested_images(key_moment, LLM_model=None):
    # Prepare the text and keywords
    text = key_moment["text"]
    keywords = ', '.join(key_moment["keywords"])
    images = key_moment["images"]

    images_list_prompt = ""
    for i, image_url in enumerate(images):
        images_list_prompt += f"\n圖片 {i+1}: {image_url}"

    # Prepare the user prompt with text and keywords
    sys_content = "你是一個擅長資料分析跟影片教學的老師,user 為學生,請精讀資料文本,自行判斷資料的種類,使用 zh-TW"
    user_content = f"""
    - 文本: {text}
    - 關鍵字: {keywords}
    
    # Rule:
    1. 保留有圖表或是數據的圖片
    2. 根據文本和關鍵字,選擇出最合適的圖片。
    3. 總是保留最後一張,除非他是一張空白圖片,或是一張沒有任何內容的圖片
    
    # Restrictions: 
    1. 如果是疑似主播、主持人的圖片場景,且沒有任何有用的資訊,請不要選取,這很重要
    2. 不要有相似或是概念重複的圖片
    3. 移除整張圖片是黑色、藍色或是白色的圖片
    4. 移除沒有任何內容的圖片
    5. 不需要理會字幕的差益,只需要看圖片的內容

    請根據這些信息,圖片列表如下:
    {images_list_prompt}

    回傳 JSON LIST 就好,不用回傳任何敘述脈絡,也不要 ```json 包覆
    EXAMPLE:
    {{
        "suggested_images": ["圖片1的 image_url", "圖片2 的 image_url", "圖片3的 image_url"]
    }}
    """

    response_format = { "type": "json_object" }
    response = generate_content_by_LLM(sys_content, user_content, response_format, LLM_model, model_name=None)
    print("===generate_key_moments_suggested_images===")
    print(response)
    print("===generate_key_moments_suggested_images===")
    suggested_images = json.loads(response)["suggested_images"]

    return suggested_images

def get_key_moments_html(key_moments):
    css = """
    <style>
    #gallery-main {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
    }

    #gallery {
        position: relative;
        width: 50%;
        flex: 1;
    }

    #text-content {
        flex: 2;
        margin-left: 20px;
    }


    #gallery #gallery-container{
        position: relative;
        width: 100%;
        height: 0px;
        padding-bottom: 56.7%; /* 16/9 ratio */
        background-color: blue;
    }
    #gallery #gallery-container #gallery-content{
        position: absolute;
        top: 0px;
        right: 0px;
        bottom: 0px;
        left: 0px;
        height: 100%;
        display: flex;
        scroll-snap-type: x mandatory;
        overflow-x: scroll;
        scroll-behavior: smooth;
    }
    #gallery #gallery-container #gallery-content .gallery__item{
        width: 100%;
        height: 100%;
        flex-shrink: 0;
        scroll-snap-align: start;
        scroll-snap-stop: always;
        position: relative;
    }
    #gallery #gallery-container #gallery-content .gallery__item img{
        display: block;
        width: 100%;
        height: 100%;
        object-fit: contain;
        background-color: white;
    }

    .click-zone{
        position: absolute;
        width: 20%;
        height: 100%;
        z-index: 3;
    }
    .click-zone.click-zone-prev{
        left: 0px;
    }
    .click-zone.click-zone-next{
        right: 0px;
    }
    #gallery:not(:hover) .arrow{
        opacity: 0.8;
    }
    .arrow{
        text-align: center;
        z-index: 3;
        position: absolute;
        display: block;
        width: 25px;
        height: 25px;
        line-height: 25px;
        background-color: black;
        border-radius: 50%;
        text-decoration: none;
        color: white !important;
        opacity: 0.8; 
        transition: opacity 200ms ease;
    }
    .arrow:hover{
        opacity: 1;
    }
    .arrow span{
        position: relative;
        top: 2px;
    }
    .arrow.arrow-prev{
        top: 50%;
        left: 5px;
    }
    .arrow.arrow-next{
        top: 50%;
        right: 5px;
    }
    .arrow.arrow-disabled{
        opacity:0.8;
    }

    #text-content {
        padding: 0px 36px;
    }
    #text-content p {
        margin-top: 10px;
    }

    body{
        font-family: sans-serif;
        margin: 0px;
        padding: 0px;
    }
    main{
        padding: 0px;
        margin: 0px;
        max-width: 900px;
        margin: auto;
    }
    .hidden{
        border: 0;
        clip: rect(0 0 0 0);
        height: 1px;
        margin: -1px;
        overflow: hidden;
        padding: 0;
        position: absolute;
        width: 1px;
    }
    .keyword-label {
        display: inline-block;
        padding: 5px 10px;
        margin: 2px;
        border: 2px solid black;
        border-radius: 5px;
        font-size: 0.9em;
    }
    details {
        border-radius: 5px;
        padding: 10px;
        border: 2px solid black;
    }

    summary {
        font-weight: bold;
        cursor: pointer;
        outline: none;
    }

    summary::-webkit-details-marker {
        display: none;
    }

    @media (max-width: 768px) {
        #gallery-main {
            flex-direction: column; /* 在小屏幕上堆叠元素 */
        }

        #gallery {
            width: 100%; /* 让画廊占满整个容器宽度 */
        }

        #text-content {
            margin-left: 0; /* 移除左边距,让文本内容占满宽度 */
            margin-top: 20px; /* 为文本内容添加顶部间距 */
        }

        #gallery #gallery-container {
            height: 350px; /* 或者你可以设置一个固定的高度,而不是用 padding-bottom */
            padding-bottom: 0; /* 移除底部填充 */
        }
    }
    </style>
    """

    key_moments_html = css

    for i, moment in enumerate(key_moments):
        if "suggested_images" in moment:
            images = moment['suggested_images']
        else:
            images = moment['images']
        image_elements = ""
        
        for j, image in enumerate(images):
            current_id = f"img_{i}_{j}"
            prev_id = f"img_{i}_{j-1}" if j-1 >= 0 else f"img_{i}_{len(images)-1}"
            next_id = f"img_{i}_{j+1}" if j+1 < len(images) else f"img_{i}_0"

            image_elements += f"""
                <div id="{current_id}" class="gallery__item">
                    <a href="#{prev_id}" class="click-zone click-zone-prev">
                        <div class="arrow arrow-disabled arrow-prev"> ◀︎ </div>
                    </a> 
                    <a href="#{next_id}" class="click-zone click-zone-next">
                        <div class="arrow arrow-next"> ▶︎ </div>
                    </a>
                    <img src="{image}">
                </div>
            """

        gallery_content = f"""
            <div id="gallery-content">
                {image_elements}
            </div>
        """

        keywords_html = ' '.join([f'<span class="keyword-label">{keyword}</span>' for keyword in moment['keywords']])


        key_moments_html += f"""
        <div class="gallery-container" id="gallery-main">
            <div id="gallery"><!-- gallery start -->
                <div id="gallery-container">
                    {gallery_content}
                </div>
            </div>
            <div id="text-content">
                <h3>{moment['start']} - {moment['end']}</h3>
                <p><strong>摘要: {moment['text']} </strong></p>
                <details>
                    <summary>逐字稿</summary>
                    <p><strong>內容: </strong> {moment['transcript']} </p>
                </details>
                <p><strong>關鍵字:</strong> {keywords_html}</p>
            </div>
        </div>
        """

    return key_moments_html

# ---- LLM CRUD ----
def get_LLM_content(video_id, kind):
    print(f"===get_{kind}===")
    gcs_client = GCS_CLIENT
    bucket_name = 'video_ai_assistant'
    file_name = f'{video_id}_{kind}.json'
    blob_name = f"{video_id}/{file_name}"
    # 检查 file 是否存在
    is_file_exists = GCS_SERVICE.check_file_exists(bucket_name, blob_name)
    if is_file_exists:
        content = GCS_SERVICE.download_as_string(bucket_name, blob_name)
        content_json = json.loads(content)
        if kind == "reading_passage_latex":
            content_text = content_json["reading_passage"]
        elif kind == "summary_markdown":
            content_text = content_json["summary"]
        elif kind == "key_moments":
            content_text = content_json["key_moments"]
            content_text = json.dumps(content_text, ensure_ascii=False, indent=2)
        else:
            content_text = json.dumps(content_json, ensure_ascii=False, indent=2)
    else:
        content_text = ""
    return content_text

def enable_edit_mode():
    return gr.update(interactive=True)

def delete_LLM_content(video_id, kind):
    print(f"===delete_{kind}===")
    gcs_client = GCS_CLIENT
    bucket_name = 'video_ai_assistant'
    file_name = f'{video_id}_{kind}.json'
    blob_name = f"{video_id}/{file_name}"
    # 检查 file 是否存在
    is_file_exists = GCS_SERVICE.check_file_exists(bucket_name, blob_name)
    if is_file_exists:
        GCS_SERVICE.delete_blob(bucket_name, blob_name)
        print(f"{file_name}已从GCS中删除")
    return gr.update(value="", interactive=False)

def update_LLM_content(video_id, new_content, kind):
    print(f"===upfdate kind on gcs===")
    bucket_name = 'video_ai_assistant'
    file_name = f'{video_id}_{kind}.json'
    blob_name = f"{video_id}/{file_name}"

    if kind == "reading_passage_latex":
        print("=========reading_passage=======")
        print(new_content)
        reading_passage_json = {"reading_passage": str(new_content)}
        reading_passage_text = json.dumps(reading_passage_json, ensure_ascii=False, indent=2)
        GCS_SERVICE.upload_json_string(bucket_name, blob_name, reading_passage_text)
        updated_content = new_content
    elif kind == "summary_markdown":
        summary_json = {"summary": str(new_content)}
        summary_text = json.dumps(summary_json, ensure_ascii=False, indent=2)
        GCS_SERVICE.upload_json_string(bucket_name, blob_name, summary_text)
        updated_content = new_content
    elif kind == "mind_map":
        mind_map_json = {"mind_map": str(new_content)}
        mind_map_text = json.dumps(mind_map_json, ensure_ascii=False, indent=2)
        GCS_SERVICE.upload_json_string(bucket_name, blob_name, mind_map_text)
        updated_content = mind_map_text
    elif kind == "key_moments":
        # from update_LLM_btn  -> new_content is a string
        # create_LLM_content -> new_content is a list
        if isinstance(new_content, str):
            key_moments_list = json.loads(new_content)
        else:
            key_moments_list = new_content
        key_moments_json = {"key_moments": key_moments_list}
        key_moments_json_text = json.dumps(key_moments_json, ensure_ascii=False, indent=2)
        GCS_SERVICE.upload_json_string(bucket_name, blob_name, key_moments_json_text)
        key_moments_text = json.dumps(key_moments_list, ensure_ascii=False, indent=2)
        updated_content = key_moments_text
    elif kind == "transcript":
        if isinstance(new_content, str):
            transcript_json = json.loads(new_content)
        else:
            transcript_json = new_content
        transcript_text = json.dumps(transcript_json, ensure_ascii=False, indent=2)
        GCS_SERVICE.upload_json_string(bucket_name, blob_name, transcript_text)
        updated_content = transcript_text
    elif kind == "questions":
        # from update_LLM_btn  -> new_content is a string
        # create_LLM_content -> new_content is a list
        if isinstance(new_content, str):
            questions_json = json.loads(new_content)
        else:
            questions_json = new_content
        questions_text = json.dumps(questions_json, ensure_ascii=False, indent=2)
        GCS_SERVICE.upload_json_string(bucket_name, blob_name, questions_text)
        updated_content = questions_text
    elif kind == "questions_answers":
        # from update_LLM_btn  -> new_content is a string
        # create_LLM_content -> new_content is a list
        if isinstance(new_content, str):
            questions_answers_json = json.loads(new_content)
        else:
            questions_answers_json = new_content
        questions_answers_text = json.dumps(questions_answers_json, ensure_ascii=False, indent=2)
        GCS_SERVICE.upload_json_string(bucket_name, blob_name, questions_answers_text)
        updated_content = questions_answers_text
    elif kind == "ai_content_list":
        if isinstance(new_content, str):
            ai_content_json = json.loads(new_content)
        else:
            ai_content_json = new_content
        ai_content_text = json.dumps(ai_content_json, ensure_ascii=False, indent=2)
        GCS_SERVICE.upload_json_string(bucket_name, blob_name, ai_content_text)
        updated_content = ai_content_text

    print(f"{kind} 已更新到GCS")
    return gr.update(value=updated_content, interactive=False)

def create_LLM_content(video_id, df_string, kind, LLM_model=None):
    print(f"===create_{kind}===")
    print(f"video_id: {video_id}")

    if kind == "reading_passage_latex":
        content = generate_reading_passage(df_string, LLM_model)
        update_LLM_content(video_id, content, kind)
    elif kind == "summary_markdown":
        meta_data = get_meta_data(video_id)
        content = generate_summarise(df_string, meta_data, LLM_model)
        update_LLM_content(video_id, content, kind)
    elif kind == "mind_map":
        content = generate_mind_map(df_string)
        update_LLM_content(video_id, content, kind)
    elif kind == "key_moments":
        if isinstance(df_string, str):
            transcript = json.loads(df_string)
        else:
            transcript = df_string
        formatted_simple_transcript = create_formatted_simple_transcript(transcript)
        formatted_transcript = create_formatted_transcript(video_id, transcript)
        gen_content = generate_key_moments(formatted_simple_transcript, formatted_transcript, LLM_model)
        update_LLM_content(video_id, gen_content, kind)
        content = json.dumps(gen_content, ensure_ascii=False, indent=2)
    elif kind == "transcript":
        gen_content = process_transcript_and_screenshots_on_gcs(video_id)
        update_LLM_content(video_id, gen_content, kind)
        content = json.dumps(gen_content, ensure_ascii=False, indent=2)
    elif kind == "questions":
        gen_content = generate_questions(df_string, LLM_model)
        update_LLM_content(video_id, gen_content, kind)
        content = json.dumps(gen_content, ensure_ascii=False, indent=2)
    elif kind == "questions_answers":
        if isinstance(df_string, str):
            transcript = json.loads(df_string)
        else:
            transcript = df_string
        formatted_simple_transcript = create_formatted_simple_transcript(transcript)
        gen_content = generate_questions_answers(formatted_simple_transcript, LLM_model)
        update_LLM_content(video_id, gen_content, kind)
        content = json.dumps(gen_content, ensure_ascii=False, indent=2)

    return gr.update(value=content, interactive=False)

# ---- LLM refresh CRUD ----
def reading_passage_add_latex_version(video_id):
    # 確認 GCS 是否有 reading_passage.json
    print("===reading_passage_convert_to_latex===")
    bucket_name = 'video_ai_assistant'
    file_name = f'{video_id}_reading_passage.json'
    blob_name = f"{video_id}/{file_name}"
    print(f"blob_name: {blob_name}")

    # 检查檔案是否存在
    is_file_exists = GCS_SERVICE.check_file_exists(bucket_name, blob_name)
    if not is_file_exists:
        raise gr.Error("reading_passage 不存在!")
        
    # 逐字稿已存在,下载逐字稿内容
    print("reading_passage 已存在于GCS中,轉換 Latex 模式")
    reading_passage_text = GCS_SERVICE.download_as_string(bucket_name, blob_name)
    reading_passage_json = json.loads(reading_passage_text)
    original_reading_passage = reading_passage_json["reading_passage"]
    sys_content = "你是一個擅長資料分析跟影片教學的老師,user 為學生,請精讀資料文本,自行判斷資料的種類,使用 zh-TW"
    user_content = f"""
        請根據 {original_reading_passage} 
        敘述中,請把數學或是專業術語,用 Latex 包覆($...$),盡量不要去改原本的文章
        加減乘除、根號、次方、化學符號、物理符號等等的運算式口語也換成 LATEX 符號
        請一定要使用繁體中文 zh-TW,並用台灣人的口語
        產生的結果不要前後文解釋,也不要敘述這篇文章怎麼產生的
        只需要專注提供 Reading Passage,字數在 200~500 字以內
    """
    messages = [
        {"role": "system", "content": sys_content},
        {"role": "user", "content": user_content}
    ]

    request_payload = {
        "model": "gpt-4o",
        "messages": messages,
        "max_tokens": 4000,
    }

    response = OPEN_AI_CLIENT.chat.completions.create(**request_payload)
    new_reading_passage = response.choices[0].message.content.strip()
    print("=====new_reading_passage=====")
    print(new_reading_passage)
    print("=====new_reading_passage=====")
    reading_passage_json["reading_passage"] = new_reading_passage
    reading_passage_text = json.dumps(reading_passage_json, ensure_ascii=False, indent=2)
    # 另存為 reading_passage_latex.json
    new_file_name = f'{video_id}_reading_passage_latex.json'
    new_blob_name = f"{video_id}/{new_file_name}"
    GCS_SERVICE.upload_json_string(bucket_name, new_blob_name, reading_passage_text)
    
    return new_reading_passage

def summary_add_markdown_version(video_id):
    # 確認 GCS 是否有 summary.json
    print("===summary_convert_to_markdown===")
    bucket_name = 'video_ai_assistant'
    file_name = f'{video_id}_summary.json'
    blob_name = f"{video_id}/{file_name}"
    print(f"blob_name: {blob_name}")

    # 检查檔案是否存在
    is_file_exists = GCS_SERVICE.check_file_exists(bucket_name, blob_name)
    if not is_file_exists:
        raise gr.Error("summary 不存在!")
        
    # 逐字稿已存在,下载逐字稿内容
    print("summary 已存在于GCS中,轉換 Markdown 模式")
    summary_text = GCS_SERVICE.download_as_string(bucket_name, blob_name)
    summary_json = json.loads(summary_text)
    original_summary = summary_json["summary"]
    sys_content = "你是一個擅長資料分析跟影片教學的老師,user 為學生,請精讀資料文本,自行判斷資料的種類,使用 zh-TW"
    user_content = f"""
        請根據 {original_summary} 
        轉換格式為 Markdown
        只保留:📚 整體摘要、🔖 重點概念、💡 為什麼我們要學這個、❓ 延伸小問題
        其他的不要保留
        整體摘要在一百字以內
        重點概念轉成 bullet points
        以及可能的結論與結尾延伸小問題提供學生作反思
        敘述中,請把數學或是專業術語,用 Latex 包覆($...$)
        加減乘除、根號、次方等等的運算式口語也換成 LATEX 數學符號

        整體格式為:
        ## 📚 整體摘要
            - (一個 bullet point....)

        ## 🔖 重點概念
            - xxx
            - xxx
            - xxx
        
        ## 💡 為什麼我們要學這個?
            - (一個 bullet point....)
        
        ## ❓ 延伸小問題
            - (一個 bullet point....)
    """
    messages = [
        {"role": "system", "content": sys_content},
        {"role": "user", "content": user_content}
    ]
    request_payload = {
        "model": "gpt-4o",
        "messages": messages,
        "max_tokens": 4000,
    }
    response = OPEN_AI_CLIENT.chat.completions.create(**request_payload)
    new_summary = response.choices[0].message.content.strip()
    print("=====new_summary=====")
    print(new_summary)
    print("=====new_summary=====")
    summary_json["summary"] = new_summary
    summary_text = json.dumps(summary_json, ensure_ascii=False, indent=2)
    # 另存為 summary_markdown.json
    new_file_name = f'{video_id}_summary_markdown.json'
    new_blob_name = f"{video_id}/{new_file_name}"
    GCS_SERVICE.upload_json_string(bucket_name, new_blob_name, summary_text)

    return new_summary


# AI 生成教學素材
def get_meta_data(video_id, source="gcs"):
    if source == "gcs":
        print("===get_meta_data on gcs===")
        gcs_client = GCS_CLIENT
        bucket_name = 'video_ai_assistant'
        file_name = f'{video_id}_meta_data.json'
        blob_name = f"{video_id}/{file_name}"
        # 检查檔案是否存在
        is_file_exists = GCS_SERVICE.check_file_exists(bucket_name, blob_name)
        if not is_file_exists:
            meta_data_json = {
                "subject": "",
                "grade": "",
            }
            print("meta_data empty return")
        else:
            # meta_data已存在,下载内容
            print("meta_data已存在于GCS中")
            meta_data_text = GCS_SERVICE.download_as_string(bucket_name, blob_name)
            meta_data_json = json.loads(meta_data_text)

    # meta_data_json grade 數字轉換成文字
    grade = meta_data_json["grade"]
    case = {
        1: "一年級",
        2: "二年級",
        3: "三年級",
        4: "四年級",
        5: "五年級",
        6: "六年級",
        7: "七年級",
        8: "八年級",
        9: "九年級",
        10: "十年級",
        11: "十一年級",
        12: "十二年級",
    }
    grade_text = case.get(grade, "")
    meta_data_json["grade"] = grade_text

    return meta_data_json

def get_ai_content(password, user_data, video_id, df_string, topic, grade, level, specific_feature, content_type, source="gcs"):
    verify_password(password)
    if source == "gcs":
        print("===get_ai_content on gcs===")
        bucket_name = 'video_ai_assistant'
        file_name = f'{video_id}_ai_content_list.json'
        blob_name = f"{video_id}/{file_name}"
        # 检查檔案是否存在
        is_file_exists = GCS_SERVICE.check_file_exists(bucket_name, blob_name)
        if not is_file_exists: 
            # 先建立一個 ai_content_list.json
            ai_content_list = []
            ai_content_text = json.dumps(ai_content_list, ensure_ascii=False, indent=2)
            GCS_SERVICE.upload_json_string(bucket_name, blob_name, ai_content_text)
            print("ai_content_list [] 已上傳到GCS")

        # 此時 ai_content_list 已存在
        ai_content_list_string = GCS_SERVICE.download_as_string(bucket_name, blob_name)
        ai_content_list = json.loads(ai_content_list_string)
        # by key 找到 ai_content (topic, grade, level, specific_feature, content_type)
        target_kvs = {
            "video_id": video_id,
            "level": level,
            "specific_feature": specific_feature,
            "content_type": content_type
        }
        ai_content_json = [
            item for item in ai_content_list
            if all(item[k] == v for k, v in target_kvs.items())
        ]         
            
        if len(ai_content_json) == 0:
            ai_content, prompt = generate_ai_content(password, df_string, topic, grade, level, specific_feature, content_type)
            ai_content_json = {
                "video_id": video_id,
                "content": str(ai_content),
                "prompt": prompt,
                "level": level,
                "specific_feature": specific_feature,
                "content_type": content_type
            }

            ai_content_list.append(ai_content_json)
            ai_content_text = json.dumps(ai_content_list, ensure_ascii=False, indent=2)
            GCS_SERVICE.upload_json_string(bucket_name, blob_name, ai_content_text)
            print("ai_content已上傳到GCS")

            # insert_log_to_bigquery usage
            data_endpoint = "chat_completions"

        else:
            ai_content_json = ai_content_json[-1]
            ai_content = ai_content_json["content"]
            prompt = ai_content_json["prompt"]
            # insert_log_to_bigquery usage
            data_endpoint = "gcs"

         # send data to GBQ
        user_id = user_data
        route = "get_ai_content"
        endpoint = data_endpoint
        event_response = {"event_response": str(ai_content)}
        event_response_json = json.dumps(event_response)
        prompt = ai_content_json
        prompt_json = json.dumps(prompt)
        feature = content_type
        insert_log_to_bigquery(user_id, route, endpoint, event_response_json, prompt_json, feature)

    return ai_content, ai_content, prompt, prompt

def generate_ai_content(password, df_string, topic, grade, level, specific_feature, content_type):
    verify_password(password)
    material = EducationalMaterial(df_string, topic, grade, level, specific_feature, content_type)
    prompt = material.generate_content_prompt()
    try:
        ai_content = material.get_ai_content(OPEN_AI_CLIENT, ai_type="openai")
    except Exception as e:
        error_msg = f" {video_id} OPEN AI 生成教學素材錯誤: {str(e)}"
        print("===generate_ai_content error===")
        print(error_msg)
        print("===generate_ai_content error===")
        ai_content = material.get_ai_content(BEDROCK_CLIENT, ai_type="bedrock")

    return ai_content, prompt

def generate_ai_content_fine_tune_result(password, user_data, exam_result_prompt , df_string_output, exam_result, exam_result_fine_tune_prompt, content_type):
    verify_password(password)
    material = EducationalMaterial(df_string_output, "", "", "", "", "")
    try:
        fine_tuned_ai_content = material.get_fine_tuned_ai_content(OPEN_AI_CLIENT, "openai", exam_result_prompt, exam_result, exam_result_fine_tune_prompt)
    except:
        fine_tuned_ai_content = material.get_fine_tuned_ai_content(BEDROCK_CLIENT, "bedrock", exam_result_prompt, exam_result, exam_result_fine_tune_prompt)

     # send data to GBQ
    user_id = user_data
    route = "generate_ai_content_fine_tune_result"
    endpoint = "chat_completions"
    event_response = {"event_response": str(fine_tuned_ai_content)}
    event_response_json = json.dumps(event_response)
    prompt = {
        "exam_result_prompt": exam_result_prompt,
        "exam_result_fine_tune_prompt": exam_result_fine_tune_prompt
    }
    prompt_json = json.dumps(prompt)
    feature = content_type
    insert_log_to_bigquery(user_id, route, endpoint, event_response_json, prompt_json, feature)

    return fine_tuned_ai_content

def return_original_exam_result(exam_result_original):
    return exam_result_original

def create_word(content):
    unique_filename = str(uuid.uuid4())
    word_file_path = f"/tmp/{unique_filename}.docx"
    doc = Document()
    doc.add_paragraph(content)
    doc.save(word_file_path)
    return word_file_path

def download_exam_result(content):
    word_path = create_word(content)
    return word_path

# ---- Chatbot ----
def get_instructions(content_subject, content_grade, key_moments, socratic_mode=True):
    if socratic_mode:
        method = "Socratic style, guide thinking, no direct answers. this is very important, please be seriously following."
    else:
        method = "direct answers, but encourage user to think more."

    instructions = f"""
        subject: {content_subject}
        grade: {content_grade}
        context: {key_moments}
        Assistant Role: you are a {content_subject} assistant. you can call yourself as  {content_subject} 學伴
        User Role: {content_grade} th-grade student.
        Method: {method}
        Language: Traditional Chinese ZH-TW (it's very important), suitable for {content_grade} th-grade level.
        Response: 
        - if user say hi or hello or any greeting, just say hi back and introduce yourself. Then tell user to ask question in context.
        - Single question, under 100 characters
        - include math symbols (use LaTeX $ to cover before and after, ex: $x^2$)
        - hint with video timestamp which format 【參考:00:00:00】. 
        - Sometimes encourage user by Taiwanese style with relaxing atmosphere.
        - if user ask questions not include in context, 
        - just tell them to ask the question in context and give them example question.
        Restrictions: 
        - Answer within video content, no external references
        - don't repeat user's question, guide them to think more.
        - don't use simple-chinese words, use ZH-TW words. such as below:
            - intead of 視頻, use 影片.
            - instead of 宇航員, use 太空人
            - instead of 計算機, use 電腦
            - instead of 鼠標, use 滑鼠
            - instead of 城鐵, use 捷運
            - instead of 屏幕, use 螢幕
            - instead of 初中, use 國中
            - instead of 領導, use 長官
            - instead of 軟件, use 軟體
            - instead of 硬件, use 硬體
            - instead of 公安, use 警察
            - instead of 渠道, use 通路
            - instead of 信息, use 資訊
            - instead of 网络, use 網路
            - instead of 网站, use 網站
            - instead of 电视, use 電視
            - instead of 电影, use 電影
            - instead of 电脑, use 電腦
            - instead of 电话, use 電話
            - instead of 文本, use 文件
            - instead of 行业, use 產業
            - instead of 企业, use 公司
            - instead of 产品, use 產品
            - instead of 服务, use 服務
    """
    return instructions

def get_chat_moderation(user_content):
    # response = client.moderations.create(input=text)
    response = OPEN_AI_MODERATION_CLIENT.moderations.create(input=user_content)
    response_dict = response.model_dump()
    is_flagged = response_dict['results'][0]['flagged']
    print("========get_chat_moderation==========")
    print(f"is_flagged: {is_flagged}")
    print(response_dict)
    print("========get_chat_moderation==========")

    return is_flagged, response_dict

def chat_with_any_ai(ai_type, password, video_id, user_data, transcript_state, key_moments, user_message, chat_history, content_subject, content_grade, questions_answers_json, socratic_mode=False, thread_id=None, ai_name=None):
    print(f"ai_type: {ai_type}")
    print(f"user_data: {user_data}")
    print(f"===thread_id:{thread_id}===")
    verify_password(password)
    verify_message_length(user_message, max_length=1500)

    is_questions_answers_exists, question_message, answer_message = check_questions_answers(user_message, questions_answers_json)
    if is_questions_answers_exists:
        chat_history = update_chat_history(question_message, answer_message, chat_history)
        send_btn_update, send_feedback_btn_update = update_send_and_feedback_buttons(chat_history, CHAT_LIMIT)
        time.sleep(3)

        return "", chat_history, send_btn_update, send_feedback_btn_update, thread_id
    
    verify_chat_limit(chat_history, CHAT_LIMIT)

    is_flagged, response_dict = get_chat_moderation(user_message)
    if ai_type == "chat_completions":
        if is_flagged:
            response_text = "您的留言已被標記為不當內容,請重新發送。"
        else:
            chatbot_config = get_chatbot_config(ai_name, transcript_state, key_moments, content_subject, content_grade, video_id, socratic_mode)
            chatbot = Chatbot(chatbot_config)
            response_text = chatbot.chat(user_message, chat_history)
        # if thread_id is none, create random thread_id + timestamp
        if thread_id is None or thread_id == "":
            thread_id = "thread_" + str(uuid.uuid4()) + str(int(time.time()))
        
        print(f"===thread_id:{thread_id}===")
        
        metadata = {
            "video_id": video_id,
            "user_data": user_data,
            "content_subject": content_subject,
            "content_grade": content_grade,
            "socratic_mode": str(socratic_mode),
            "assistant_id": ai_name,
            "is_streaming": "false",
            "moderation_is_flagged": str(is_flagged),
            "moderation_response_dict": str(response_dict)
        }
    elif ai_type == "assistant":
        client = OPEN_AI_CLIENT
        assistant_id = OPEN_AI_ASSISTANT_ID_GPT4
        metadata={
            "video_id": video_id,
            "user_data": user_data,
            "content_subject": content_subject,
            "content_grade": content_grade,
            "socratic_mode": str(socratic_mode),
            "assistant_id": assistant_id,
            "is_streaming": "false",
            "moderation_is_flagged": str(is_flagged),
            "moderation_response_dict": str(response_dict)
        }

        if is_flagged:
            response_text = "您的留言已被標記為不當內容,請重新發送。"
        else:
            if isinstance(key_moments, str):
                key_moments_json = json.loads(key_moments)
            else:
                key_moments_json = key_moments
            # key_moments_json remove images
            for moment in key_moments_json:
                moment.pop('images', None)
                moment.pop('end', None)
                moment.pop('transcript', None)
            key_moments_text = json.dumps(key_moments_json, ensure_ascii=False)
            instructions = get_instructions(content_subject, content_grade, key_moments_text, socratic_mode)
            print(f"=== instructions:{instructions} ===")
            user_message_note = "/n 請嚴格遵循instructions,擔任一位蘇格拉底家教,絕對不要重複 user 的問句,請用引導的方式指引方向,請一定要用繁體中文回答 zh-TW,並用台灣人的禮貌口語表達,回答時不要特別說明這是台灣人的語氣,請在回答的最後標註【參考:(時):(分):(秒)】,(如果是反問學生,就只問一個問題,請幫助學生更好的理解資料,字數在100字以內,回答時如果講到數學專有名詞,請用數學符號代替文字(Latex 用 $ 字號 render, ex: $x^2$)"
            user_content = user_message + user_message_note
            response_text, thread_id = handle_conversation_by_open_ai_assistant(client, user_content, instructions, assistant_id, thread_id, metadata, fallback=True)

    # 更新聊天历史
    chat_history = update_chat_history(user_message, response_text, chat_history)
    send_btn_update, send_feedback_btn_update = update_send_and_feedback_buttons(chat_history, CHAT_LIMIT)

    user_id = user_data
    route = "chat_with_any_ai"
    endpoint = ai_type #chat_completions or assistant
    event_response = {
        "event_response": str(response_text),
    }
    event_response_json = json.dumps(event_response)
    prompt = {
        "thread_id": thread_id,
        "metadata": metadata,
        "user_message": user_message
    }
    prompt_json = json.dumps(prompt)

    feature = "vaitor_chatbot"
    insert_log_to_bigquery(user_id, route, endpoint, event_response_json, prompt_json, feature)

    # 返回聊天历史和空字符串清空输入框
    return "", chat_history, send_btn_update, send_feedback_btn_update, thread_id

def get_chatbot_config(ai_name, transcript_state, key_moments, content_subject, content_grade, video_id, socratic_mode=True):
    if not ai_name in ["foxcat", "lili", "maimai"]:
        ai_name = "foxcat"

    ai_name_clients_model = {
        "foxcat": {
            "ai_name": "foxcat",
            "ai_client": GROQ_CLIENT,
            "ai_model_name": "groq_llama3",
        },
        # "lili": {
        #     "ai_name": "lili",
        #     "ai_client": BEDROCK_CLIENT,
        #     "ai_model_name": "claude3",
        # },
        "lili": {
            "ai_name": "lili",
            "ai_client": GROQ_CLIENT,
            "ai_model_name": "groq_llama3",
        },
        "maimai": {
            "ai_name": "maimai",
            "ai_client": GROQ_CLIENT,
            "ai_model_name": "groq_mixtral",
        }
    }
    ai_client = ai_name_clients_model.get(ai_name, "foxcat")["ai_client"]
    ai_model_name = ai_name_clients_model.get(ai_name, "foxcat")["ai_model_name"]

    if isinstance(transcript_state, str):
        simple_transcript = json.loads(transcript_state)
    else:
        simple_transcript = transcript_state
  
    if isinstance(key_moments, str):
        key_moments_json = json.loads(key_moments)
    else:
        key_moments_json = key_moments
    # key_moments_json remove images
    for moment in key_moments_json:
        moment.pop('images', None)
        moment.pop('end', None)
        moment.pop('transcript', None)
    key_moments_text = json.dumps(key_moments_json, ensure_ascii=False)

    instructions = get_instructions(content_subject, content_grade, key_moments_text, socratic_mode)

    chatbot_config = {
        "video_id": video_id,
        "transcript": simple_transcript,
        "key_moments": key_moments,
        "content_subject": content_subject,
        "content_grade": content_grade,
        "jutor_chat_key": JUTOR_CHAT_KEY,
        "ai_model_name": ai_model_name,
        "ai_client": ai_client,
        "instructions": instructions
    }

    return chatbot_config

def feedback_with_ai(user_data, ai_type, chat_history, thread_id=None):
    # prompt: 請依據以上的對話(chat_history),總結我的「提問力」,並給予我是否有「問對問題」的回饋和建議
    system_content = """
        你是一個擅長引導問答素養的老師,user 為學生的提問跟回答,請精讀對話過程,針對 user 給予回饋就好,根據以下 Rule:
        - 請使用繁體中文 zh-TW 總結 user 的提問力,並給予是否有問對問題的回饋和建議
        - 不採計【預設提問】的問題,如果 user 的提問都來自【預設提問】,表達用戶善於使用系統,請給予回饋並鼓勵 user 親自提問更具體的問題
        - 如果用戶提問都相當簡短,甚至就是一個字或都是一個數字(像是 user: 1, user:2),請給予回饋並建議 user 提問更具體的問題
        - 如果用戶提問內容只有符號或是亂碼,像是?,!, ..., 3bhwbqhfw2vve2 等,請給予回饋並建議 user 提問更具體的問題
        - 如果用戶提問內容有色情、暴力、仇恨、不當言論等,請給予嚴厲的回饋並建議 user 提問更具體的問題
        - 並用第二人稱「你」來代表 user
        - 請禮貌,並給予鼓勵
    """
    chat_history_conversation = ""
    # 標註 user and assistant as string
    # chat_history 第一組不採計
    for chat in chat_history[1:]:
        user_message = chat[0]
        assistant_message = chat[1]
        chat_history_conversation += f"User: {user_message}\nAssistant: {assistant_message}\n"
    
    feedback_request_message = "請依據以上的對話,總結我的「提問力」,並給予我是否有「問對問題」的回饋和建議"
    user_content = f"""conversation: {chat_history_conversation}
        {feedback_request_message}
        最後根據提問力表現,給予提問建議、提問表現,並用 emoji 來表示評分:
        🟢:(表現很好的回饋,給予正向肯定)
        🟡:(還可以加油的的回饋,給予明確的建議)
        🔴:(非常不懂提問的回饋,給予鼓勵並給出明確示範)

        example:
        另一方面,你表達「我不想學了」這個情感,其實也是一種重要的反饋。這顯示你可能感到挫折或疲倦。在這種情況下,表達出你的感受是好的,但如果能具體說明是什麼讓你感到這樣,或是有什麼具體的學習障礙,會更有助於找到解決方案。
        給予你的建議是,嘗試在提問時更明確一些,這樣不僅能幫助你獲得更好的學習支持,也能提高你的問題解決技巧。
        ......
        提問建議:在提問時,試著具體並清晰地表達你的需求和疑惑,這樣能更有效地得到幫助。
        提問表現:【🟡】加油,持續練習,你的提問力會越來越好!
    """

    client = OPEN_AI_CLIENT

    if ai_type == "chat_completions":
        model_name = "gpt-4o"
        response_text = handle_conversation_by_open_ai_chat_completions(client, model_name, user_content, system_content)
    elif ai_type == "assistant":
        assistant_id = OPEN_AI_ASSISTANT_ID_GPT4 #GPT 4 turbo
        # assistant_id = OPEN_AI_ASSISTANT_ID_GPT3 #GPT 3.5 turbo
        response_text, thread_id = handle_conversation_by_open_ai_assistant(client, user_content, system_content, assistant_id, thread_id, metadata=None, fallback=True)
    
    chat_history = update_chat_history(feedback_request_message, response_text, chat_history)
    feedback_btn_update = gr.update(value="已回饋", interactive=False, variant="secondary")

    user_id = user_data
    route = "feedback_with_ai"
    endpoint = ai_type #chat_completions or assistant
    event_response = {
        "event_response": str(response_text),
    }
    event_response_json = json.dumps(event_response)
    prompt = {
        "thread_id": thread_id,
        "metadata": None,
        "user_message": user_content
    }
    prompt_json = json.dumps(prompt)
    feature = "vaitor_chatbot"
    insert_log_to_bigquery(user_id, route, endpoint, event_response_json, prompt_json, feature)

    return chat_history, feedback_btn_update

def handle_conversation_by_open_ai_chat_completions(client, model_name, user_content, system_content):
    response = client.chat.completions.create(
        model=model_name,
        messages=[
            {"role": "system", "content": system_content},
            {"role": "user", "content": user_content}
        ],
        max_tokens=4000,
    )
    response_text = response.choices[0].message.content.strip()
    return response_text

def handle_conversation_by_open_ai_assistant(client, user_message, instructions, assistant_id, thread_id=None, metadata=None, fallback=False):
    """
    Handles the creation and management of a conversation thread.
    :param client: The OpenAI client object.
    :param thread_id: The existing thread ID, if any.
    :param user_message: The message from the user.
    :param instructions: System instructions for the assistant.
    :param assistant_id: ID of the assistant to use.
    :param metadata: Additional metadata to add to the thread.
    :param fallback: Whether to use a fallback method in case of failure.
    :return: A string with the response text or an error message.
    """
    try:
        if not thread_id:
            thread = client.beta.threads.create()
            thread_id = thread.id
        else:
            thread = client.beta.threads.retrieve(thread_id)

        if metadata:
            client.beta.threads.update(thread_id=thread.id, metadata=metadata)

        # Send the user message to the thread
        client.beta.threads.messages.create(thread_id=thread.id, role="user", content=user_message)

        # Run the assistant
        run = client.beta.threads.runs.create(thread_id=thread.id, assistant_id=assistant_id, instructions=instructions)
        
        # Wait for the response
        run_status = poll_run_status(run.id, thread.id, timeout=30)
        
        if run_status == "completed":
            messages = client.beta.threads.messages.list(thread_id=thread.id)
            response = messages
            response_text = messages.data[0].content[0].text.value
        else:
            response_text = "學習精靈有點累,請稍後再試!"

    except Exception as e:
        if fallback:
            response = client.chat.completions.create(
                model="gpt-4o",
                messages=[
                    {"role": "system", "content": instructions},
                    {"role": "user", "content": user_message}
                ],
                max_tokens=4000,
            )
            response_text = response.choices[0].message.content.strip()
        else:
            print(f"Error: {e}")
            raise gr.Error(f"Error: {e}")

    return response_text, thread_id

def verify_message_length(user_message, max_length=500):
    # 驗證用戶消息的長度
    if len(user_message) > max_length:
        error_msg = "你的訊息太長了,請縮短訊息長度至五百字以內"
        raise gr.Error(error_msg)

def check_questions_answers(user_message, questions_answers_json):
    """檢查問答是否存在,並處理相關邏輯"""
    is_questions_answers_exists = False
    answer = ""
    # 解析問答數據
    if isinstance(questions_answers_json, str):
        qa_data = json.loads(questions_answers_json)
    else:
        qa_data = questions_answers_json
    
    question_message = ""
    answer_message = ""
    for qa in qa_data:
        if user_message == qa["question"] and qa["answer"]:
            is_questions_answers_exists = True
            question_message = f"【預設問題】{user_message}"
            answer_message = qa["answer"]
            print("=== in questions_answers_json==")
            print(f"question: {qa['question']}")
            print(f"answer: {answer_message}")
            break  # 匹配到答案後退出循環

    return is_questions_answers_exists, question_message, answer_message

def verify_chat_limit(chat_history, chat_limit):
    if chat_history is not None and len(chat_history) > chat_limit:
        error_msg = "此次對話超過上限(對話一輪10次)"
        raise gr.Error(error_msg)

def update_chat_history(user_message, response, chat_history):
    # 更新聊天歷史的邏輯
    new_chat_history = (user_message, response)
    if chat_history is None:
        chat_history = [new_chat_history]
    else:
        chat_history.append(new_chat_history)
    
    return chat_history

def update_send_and_feedback_buttons(chat_history, chat_limit):
    # 计算发送次数
    send_count = len(chat_history) - 1

    # 根据聊天历史长度更新发送按钮和反馈按钮
    if len(chat_history) > chat_limit:
        send_btn_value = f"對話上限 ({send_count}/{chat_limit})"
        send_btn_update = gr.update(value=send_btn_value, interactive=False)
        send_feedback_btn_update = gr.update(visible=True)
    else:
        send_btn_value = f"發送 ({send_count}/{chat_limit})"
        send_btn_update = gr.update(value=send_btn_value, interactive=True)
        send_feedback_btn_update = gr.update(visible=False)

    return send_btn_update, send_feedback_btn_update

def process_open_ai_audio_to_chatbot(password, audio_url):
    verify_password(password)
    if audio_url:
        with open(audio_url, "rb") as audio_file:
            file_size = os.path.getsize(audio_url)
            if file_size > 2000000:
                raise gr.Error("檔案大小超過,請不要超過 60秒")
            else:
                transcription = OPEN_AI_CLIENT.audio.transcriptions.create(
                    model="whisper-1",
                    file=audio_file,
                    response_format="text"
                )   
                # response 拆解 dict
                print("=== transcription ===")
                print(transcription)
                print("=== transcription ===")
                # 確認 response 是否有數學符號,prompt to LATEX $... $, ex: $x^2$
                
        if transcription:
            system_message = """你是專業的 LATEX 轉換師,擅長將數學符號、公式轉換成 LATEX 格式,並用 LATEX 符號 $...$ 包裹,ex: $x^2$
            範例:
            transcription: x的平方加 2x 加 1 等於 0
            轉成 LATEX 格式:$x^2 + 2x + 1 = 0$ 
            """
            user_message = f"""transcription: {transcription}
            請將 transcription 內的數學、公式、運算式、化學式、物理 formula 內容轉換成 LATEX 格式
            其他文字都保留原樣
            也不要給出多餘的敘述            
            """
            request = OPEN_AI_CLIENT.chat.completions.create(
                model="gpt-4o",
                messages=[
                    {"role": "system", "content": system_message},
                    {"role": "user", "content": user_message}
                ],
                max_tokens=4000,
            )
            response = request.choices[0].message.content.strip()
    else:
        response = ""

    return response

def poll_run_status(run_id, thread_id, timeout=600, poll_interval=5):
    """
    Polls the status of a Run and handles different statuses appropriately.

    :param run_id: The ID of the Run to poll.
    :param thread_id: The ID of the Thread associated with the Run.
    :param timeout: Maximum time to wait for the Run to complete, in seconds.
    :param poll_interval: Time to wait between each poll, in seconds.
    """
    client = OPEN_AI_CLIENT
    start_time = time.time()
    while time.time() - start_time < timeout:
        run = client.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run_id)

        if run.status in ["completed", "cancelled", "failed"]:
            print(f"Run completed with status: {run.status}")
            break
        elif run.status == "requires_action":
            print("Run requires action. Performing required action...")
            # Here, you would perform the required action, e.g., running functions
            # and then submitting the outputs. This is simplified for this example.
            # After performing the required action, you'd complete the action:
            # OPEN_AI_CLIENT.beta.threads.runs.complete_required_action(...)
        elif run.status == "expired":
            print("Run expired. Exiting...")
            break
        else:
            print(f"Run status is {run.status}. Waiting for updates...")
        
        time.sleep(poll_interval)
    else:
        print("Timeout reached. Run did not complete in the expected time.")

    # Once the Run is completed, handle the result accordingly
    if run.status == "completed":
        # Retrieve and handle messages or run steps as needed
        messages = client.beta.threads.messages.list(thread_id=thread_id)
        for message in messages.data:
            if message.role == "assistant":
                print(f"Assistant response: {message.content}")
    elif run.status in ["cancelled", "failed"]:
        # Handle cancellation or failure
        print(f"Run ended with status: {run.status}")
    elif run.status == "expired":
        # Handle expired run
        print("Run expired without completion.")
    
    return run.status

def chat_with_opan_ai_assistant_streaming(user_message, chat_history, password, video_id, user_data, thread_id, trascript, key_moments, content_subject, content_grade, socratic_mode=True):
    verify_password(password)

    print("=====user_data=====")
    print(f"user_data: {user_data}")

    print("===chat_with_opan_ai_assistant_streaming===")
    print(thread_id)
    
    # 先計算 user_message 是否超過 500 個字
    if len(user_message) > 1500:
        error_msg = "你的訊息太長了,請縮短訊息長度至五百字以內"
        raise gr.Error(error_msg)
    
    # 如果 chat_history 超過 10 則訊息,直接 return "對話超過上限"
    if chat_history is not None and len(chat_history) > CHAT_LIMIT:
        error_msg = f"此次對話超過上限(對話一輪{CHAT_LIMIT}次)"
        raise gr.Error(error_msg)
    
    print("===chat_with_opan_ai_assistant_streaming===")
    print(user_message)
    

    is_flagged, response_dict = get_chat_moderation(user_message)
    assistant_id = OPEN_AI_ASSISTANT_ID_GPT4 #GPT 4 turbo
    # assistant_id = OPEN_AI_ASSISTANT_ID_GPT3 #GPT 3.5 turbo
    client = OPEN_AI_CLIENT
    metadata = {
        "youtube_id": video_id,
        "user_data": user_data,
        "content_subject": content_subject,
        "content_grade": content_grade,
        "assistant_id": assistant_id,
        "is_streaming": "true",
        "moderation_is_flagged": str(is_flagged),
        # "moderation_response_dict": str(response_dict)
    }

    if is_flagged:
        partial_messages = "您的留言已被標記為不當內容,請重新發送。"
        yield partial_messages
    else:
        try:
            if isinstance(key_moments, str):
                key_moments_json = json.loads(key_moments)
            else:
                key_moments_json = key_moments
            # key_moments_json remove images
            for moment in key_moments_json:
                moment.pop('images', None)
                moment.pop('end', None)
                moment.pop('transcript', None)
            key_moments_text = json.dumps(key_moments_json, ensure_ascii=False)

            instructions = get_instructions(content_subject, content_grade, key_moments_text, socratic_mode)
            # 创建线程
            if not thread_id:
                thread = client.beta.threads.create()
                thread_id = thread.id
                print(f"new thread_id: {thread_id}")
            else:
                thread = client.beta.threads.retrieve(thread_id)
                print(f"old thread_id: {thread_id}")
            
            client.beta.threads.update(
                thread_id=thread_id,
                metadata=metadata
            )    
            
            # 向线程添加用户的消息
            client.beta.threads.messages.create(
                thread_id=thread.id,
                role="user",
                content=user_message + "/n 請嚴格遵循instructions,擔任一位蘇格拉底家教,請一定要用繁體中文回答 zh-TW,並用台灣人的禮貌口語表達,回答時不要特別說明這是台灣人的語氣,不用提到「逐字稿」這個詞,用「內容」代替)),請在回答的最後標註【參考資料:(時):(分):(秒)】,(如果是反問學生,就只問一個問題,請幫助學生更好的理解資料,字數在100字以內)"
            )

            with client.beta.threads.runs.stream(
                thread_id=thread.id,
                assistant_id=assistant_id,
                instructions=instructions,
            ) as stream:
                partial_messages = ""
                for event in stream:
                    if event.data and event.data.object == "thread.message.delta":
                        message = event.data.delta.content[0].text.value
                        partial_messages += message
                        yield partial_messages
        except Exception as e:
            print(f"Error: {e}")
            raise gr.Error(f"Error: {e}")
        
    user_id = user_data
    route = "chat_with_opan_ai_assistant_streaming"
    endpoint = "assistant_streaming"
    event_response = {
        "event_response": partial_messages
    }
    event_response_json = json.dumps(event_response)
    prompt = {
        "thread_id": thread_id,
        "metadata": metadata,
        "user_message": user_message
    }
    prompt_json = json.dumps(prompt)
    feature = "vaitor_chatbot"
    insert_log_to_bigquery(user_id, route, endpoint, event_response_json, prompt_json, feature)

def create_thread_id():
    thread = OPEN_AI_CLIENT.beta.threads.create()
    thread_id = thread.id
    print(f"create new thread_id: {thread_id}")
    return thread_id

def chatbot_select(chatbot_name):
    chatbot_select_accordion_visible = gr.update(visible=False)
    all_chatbot_select_btn_visible = gr.update(visible=True)
    chatbot_open_ai_streaming_visible = gr.update(visible=False)
    chatbot_ai_visible = gr.update(visible=False)
    ai_name_update = gr.update(value="foxcat")
    ai_chatbot_thread_id_update = gr.update(value="")
    
    if chatbot_name == "chatbot_open_ai":
        chatbot_ai_visible = gr.update(visible=True)
        ai_chatbot_ai_type_update = gr.update(value="assistant")
    elif chatbot_name == "chatbot_open_ai_streaming":
        chatbot_open_ai_streaming_visible = gr.update(visible=True)
        ai_chatbot_ai_type_update = gr.update(value="assistant_streaming")
    else:
        chatbot_ai_visible = gr.update(visible=True)
        ai_chatbot_ai_type_update = gr.update(value="chat_completions")
    
    ai_name_update = gr.update(value=chatbot_name) 
        
    return chatbot_select_accordion_visible, all_chatbot_select_btn_visible, \
        chatbot_open_ai_streaming_visible, chatbot_ai_visible, \
        ai_name_update, ai_chatbot_ai_type_update, ai_chatbot_thread_id_update

def update_avatar_images(avatar_images, chatbot_description_value):
    value = [[
        "請問你是誰?",
        chatbot_description_value
    ]]
    ai_chatbot_update = gr.update(avatar_images=avatar_images, value=value)
    return ai_chatbot_update

def show_all_chatbot_accordion():
    chatbot_select_accordion_visible = gr.update(visible=True)
    all_chatbot_select_btn_visible = gr.update(visible=False)
    return chatbot_select_accordion_visible, all_chatbot_select_btn_visible

def insert_log_to_bigquery(user_id, route, endpoint, event_response_json, prompt_json, feature):
    table_id = "junyiacademy.streaming_log.log_video_ai_usage"    
    rows_to_insert = [
        {
            "user_id": user_id,
            "route": route,
            "endpoint": endpoint,
            "event_response": event_response_json,
            "event_timestamp": datetime.now(timezone.utc).isoformat(),
            "prompt": prompt_json,
            "feature": feature
        }
    ]

    errors = GBQ_CLIENT.insert_rows_json(table_id, rows_to_insert)
    if errors:
        print(f"Encountered errors while inserting rows: {errors}")
    else:
        print("Rows have been successfully inserted.")


# --- Init params ---
def init_params(text, request: gr.Request):
    if request:
        print("Request headers dictionary:", request.headers)
        print("IP address:", request.client.host)
        print("Query parameters:", dict(request.query_params))
        # url = request.url
        print("Request URL:", request.url)

        youtube_link = ""
        password_text = ""
        admin = gr.update(visible=True)
        reading_passage_admin = gr.update(visible=True)
        summary_admin = gr.update(visible=True)
        see_detail = gr.update(visible=True)
        worksheet_accordion = gr.update(visible=True)
        lesson_plan_accordion = gr.update(visible=True)
        exit_ticket_accordion = gr.update(visible=True)

        chatbot_open_ai_streaming = gr.update(visible=False)
        chatbot_ai = gr.update(visible=False)
        ai_chatbot_params = gr.update(visible=True)

        is_env_prod = gr.update(value=False)

        # if youtube_link in query_params
        if "youtube_id" in request.query_params:
            youtube_id = request.query_params["youtube_id"]
            youtube_link = f"https://www.youtube.com/watch?v={youtube_id}"
            print(f"youtube_link: {youtube_link}")

        # check if origin is from junyiacademy
        origin = request.headers.get("origin", "")
        if "junyiacademy" in origin:
            password_text = PASSWORD
            admin = gr.update(visible=False)
            reading_passage_admin = gr.update(visible=False)
            summary_admin = gr.update(visible=False)
            see_detail = gr.update(visible=False)
            worksheet_accordion = gr.update(visible=False)
            lesson_plan_accordion = gr.update(visible=False)
            exit_ticket_accordion = gr.update(visible=False)
            ai_chatbot_params = gr.update(visible=False)
        
        if IS_ENV_PROD == "True":
            is_env_prod = gr.update(value=True)

    return admin, reading_passage_admin, summary_admin, see_detail, \
        worksheet_accordion, lesson_plan_accordion, exit_ticket_accordion, \
        password_text, youtube_link, \
        chatbot_open_ai_streaming, chatbot_ai, ai_chatbot_params, \
        is_env_prod

def update_state(content_subject, content_grade, trascript, key_moments, questions_answers):
    # inputs=[content_subject, content_grade, df_string_output],
    # outputs=[content_subject_state, content_grade_state, trascript_state]
    content_subject_state = content_subject
    content_grade_state = content_grade
    trascript_json = json.loads(trascript)
    formatted_simple_transcript = create_formatted_simple_transcript(trascript_json)
    trascript_state = formatted_simple_transcript
    key_moments_state = key_moments

    streaming_chat_thread_id_state = ""
    questions_answers_json = json.loads(questions_answers)
    question_1 = questions_answers_json[0]["question"]
    question_2 = questions_answers_json[1]["question"]
    question_3 = questions_answers_json[2]["question"]
    ai_chatbot_question_1 = question_1
    ai_chatbot_question_2 = question_2
    ai_chatbot_question_3 = question_3

    return content_subject_state, content_grade_state, trascript_state, key_moments_state, \
        streaming_chat_thread_id_state, \
        ai_chatbot_question_1, ai_chatbot_question_2, ai_chatbot_question_3


HEAD = """
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
    svg.markmap {{
        width: 100%;
        height: 100vh;
    }}
    </style>
    <script src="https://cdn.jsdelivr.net/npm/markmap-autoloader@0.15.2"></script>

    <script>
        const mind_map_tab_button = document.querySelector("#mind_map_tab-button");
        
        if (mind_map_tab_button) {
            mind_map_tab_button.addEventListener('click', function() {
                const mind_map_markdown = document.querySelector("#mind_map_markdown > label > textarea");
                if (mind_map_markdown) {
                // 当按钮被点击时,打印当前的textarea的值
                console.log('Value changed to: ' + mind_map_markdown.value);
                markmap.autoLoader.renderAll();
                }
            });
        }
    </script>
"""

with gr.Blocks(theme=gr.themes.Base(primary_hue=gr.themes.colors.orange, secondary_hue=gr.themes.colors.amber, text_size = gr.themes.sizes.text_lg), head=HEAD) as demo:
    with gr.Row() as admin:
        password = gr.Textbox(label="Password", type="password", elem_id="password_input", visible=True)
        youtube_link = gr.Textbox(label="Enter YouTube Link", elem_id="youtube_link_input", visible=True)
        video_id = gr.Textbox(label="video_id", visible=True)
        # file_upload = gr.File(label="Upload your CSV or Word file", visible=False)
        # web_link = gr.Textbox(label="Enter Web Page Link", visible=False)
        user_data = gr.Textbox(label="User Data", elem_id="user_data_input", visible=True)
        youtube_link_btn = gr.Button("Submit_YouTube_Link", elem_id="youtube_link_btn", visible=True)
    with gr.Row() as data_state:
        content_subject_state = gr.State()  # 使用 gr.State 存储 content_subject
        content_grade_state = gr.State()  # 使用 gr.State 存储 content_grade
        trascript_state = gr.State()  # 使用 gr.State 存储 trascript
        key_moments_state = gr.State()  # 使用 gr.State 存储 key_moments
        streaming_chat_thread_id_state = gr.State()  # 使用 gr.State 存储 streaming_chat_thread_id
    with gr.Tab("AI小精靈"):
        with gr.Row():
            all_chatbot_select_btn = gr.Button("選擇 AI 小精靈 👈", elem_id="all_chatbot_select_btn", visible=False, variant="secondary", size="sm")
        with gr.Row() as ai_chatbot_params:
            ai_name = gr.Dropdown(
                label="選擇 AI 助理", 
                choices=[
                    ("飛特精靈","chatbot_open_ai"), 
                    ("飛特音速","chatbot_open_ai_streaming"), 
                    ("梨梨","lili"), 
                    ("麥麥","maimai"), 
                    ("狐狸貓","foxcat")
                ], 
                value="foxcat",
                visible=True
            )
            ai_chatbot_ai_type = gr.Textbox(value="chat_completions", visible=True)
            ai_chatbot_thread_id = gr.Textbox(label="thread_id", visible=True)
            ai_chatbot_socratic_mode_btn = gr.Checkbox(label="蘇格拉底家教助理模式", value=True, visible=True)
            latex_delimiters = [{"left": "$", "right": "$", "display": False}]
        with gr.Accordion("選擇 AI 小精靈", elem_id="chatbot_select_accordion") as chatbot_select_accordion:
            with gr.Row():
                user_avatar = "https://em-content.zobj.net/source/google/263/flushed-face_1f633.png"
                # 飛特精靈
                with gr.Column(scale=1, variant="panel", visible=True):
                    vaitor_chatbot_avatar_url = "https://junyitopicimg.s3.amazonaws.com/s4byy--icon.jpe?v=20200513013523726"
                    vaitor_chatbot_avatar_images = gr.State([user_avatar, vaitor_chatbot_avatar_url])
                    vaitor_chatbot_description = """Hi,我是你的AI學伴【飛特精靈】,\n
                    我可以陪你一起學習本次的內容,有什麼問題都可以問我喔!\n
                    🤔 如果你不知道怎麼發問,可以點擊左下方的問題一、問題二、問題三,我會幫你生成問題!\n
                    🗣️ 也可以點擊右下方用語音輸入,我會幫你轉換成文字,厲害吧!\n
                    🔠 或是直接鍵盤輸入你的問題,我會盡力回答你的問題喔!\n
                    💤 但我還在成長,體力有限,每一次學習只能回答十個問題,請讓我休息一下再問問題喔!\n
                    🦄 如果達到上限,或是遇到精靈很累,請問問其他朋友,像是飛特音速說話的速度比較快,你是否跟得上呢?你也可以和其他精靈互動看看喔!\n
                    """
                    chatbot_open_ai_name = gr.State("chatbot_open_ai")
                    gr.Image(value=vaitor_chatbot_avatar_url, height=100, width=100, show_label=False, show_download_button=False)
                    vaitor_chatbot_select_btn = gr.Button("👆選擇【飛特精靈】", elem_id="chatbot_btn", visible=True, variant="primary")
                    with gr.Accordion("🦄 飛特精靈 敘述", open=False):
                        vaitor_chatbot_description_value = gr.Markdown(value=vaitor_chatbot_description, visible=True)
                # 狐狸貓
                with gr.Column(scale=1, variant="panel"):
                    foxcat_chatbot_avatar_url = "https://storage.googleapis.com/wpassets.junyiacademy.org/1/2020/06/%E7%A7%91%E5%AD%B8%E5%BE%BD%E7%AB%A0-2-150x150.png"
                    foxcat_avatar_images = gr.State([user_avatar, foxcat_chatbot_avatar_url])
                    foxcat_chatbot_description = """Hi,我是【狐狸貓】,可以陪你一起學習本次的內容,有什麼問題都可以問我喔!\n
                    🤔 三年級學生|10 歲|男\n
                    🗣️ 口頭禪:「感覺好好玩喔!」「咦?是這樣嗎?」\n
                    🔠 興趣:看知識型書籍、熱血的動漫卡通、料理、爬山、騎腳踏車。因為太喜歡吃魚了,正努力和爸爸學習釣魚、料理魚及各種有關魚的知識,最討厭的食物是青椒。\n
                    💤 個性:喜歡學習新知,擁有最旺盛的好奇心,家裡堆滿百科全書,例如:國家地理頻道出版的「終極魚百科」,雖都沒有看完,常常被梨梨唸是三分鐘熱度,但是也一點一點學習到不同領域的知識。雖然有時會忘東忘西,但認真起來也是很可靠,答應的事絕對使命必達。遇到挑戰時,勇於跳出舒適圈,追求自我改變,視困難為成長的機會。
                    """
                    foxcat_chatbot_name = gr.State("foxcat")
                    gr.Image(value=foxcat_chatbot_avatar_url, height=100, width=100, show_label=False, show_download_button=False)
                    foxcat_chatbot_select_btn = gr.Button("👆選擇【狐狸貓】", visible=True, variant="primary", elem_classes="chatbot_select_btn")
                    with gr.Accordion("💜 狐狸貓 敘述", open=False):
                        foxcat_chatbot_description_value = gr.Markdown(value=foxcat_chatbot_description, visible=True)
                # 梨梨
                with gr.Column(scale=1, variant="panel"): 
                    lili_chatbot_avatar_url = "https://junyitopicimg.s3.amazonaws.com/live/v1283-new-topic-44-icon.png?v=20230529071206714"
                    lili_avatar_images = gr.State([user_avatar, lili_chatbot_avatar_url])
                    lili_chatbot_description = """你好,我是溫柔的【梨梨】,很高興可以在這裡陪伴你學習。如果你有任何疑問,請隨時向我提出哦! \n
                        🤔 三年級學生|10 歲|女\n
                        🗣️ 口頭禪:「真的假的?!」「讓我想一想喔」「你看吧!大問題拆解成小問題,就變得簡單啦!」「混混噩噩的生活不值得過」\n
                        🔠 興趣:烘焙餅乾(父母開糕餅店)、畫畫、聽流行音樂、收納。\n
                        💤 個性:
                        - 內向害羞,比起出去玩更喜歡待在家(除非是跟狐狸貓出去玩)
                        - 數理邏輯很好;其實覺得麥麥連珠炮的提問有點煩,但還是會耐心地回答
                        - 有驚人的眼力,總能觀察到其他人沒有察覺的細節
                        - 喜歡整整齊齊的環境,所以一到麥麥家就受不了
                    """
                    lili_chatbot_name = gr.State("lili")
                    gr.Image(value=lili_chatbot_avatar_url, height=100, width=100, show_label=False, show_download_button=False)
                    lili_chatbot_select_btn = gr.Button("👆選擇【梨梨】", visible=True, variant="primary", elem_classes="chatbot_select_btn")
                    with gr.Accordion("🧡 梨梨 敘述", open=False):
                        lili_chatbot_description_value = gr.Markdown(value=lili_chatbot_description, visible=True)
                # 麥麥
                with gr.Column(scale=1, variant="panel"): 
                    maimai_chatbot_avatar_url = "https://storage.googleapis.com/wpassets.junyiacademy.org/1/2020/07/%E6%80%9D%E8%80%83%E5%8A%9B%E8%B6%85%E4%BA%BA%E5%BE%BD%E7%AB%A0_%E5%B7%A5%E4%BD%9C%E5%8D%80%E5%9F%9F-1-%E8%A4%87%E6%9C%AC-150x150.png"
                    maimai_avatar_images = gr.State([user_avatar, maimai_chatbot_avatar_url])
                    maimai_chatbot_description = """Hi,我是迷人的【麥麥】,我在這裡等著和你一起探索新知,任何疑問都可以向我提出!\n
                        🤔 三年級學生|10 歲|男\n
                        🗣️ 口頭禪:「Oh My God!」「好奇怪喔!」「喔!原來是這樣啊!」\n
                        🔠 興趣:最愛去野外玩耍(心情好時會順便捕魚送給狐狸貓),喜歡講冷笑話、惡作劇。因為太喜歡玩具,而開始自己做玩具,家裡就好像他的遊樂場。\n
                        💤 個性:喜歡問問題,就算被梨梨ㄘㄟ,也還是照問|憨厚,外向好動,樂天開朗,不會被難題打敗|喜歡收集各式各樣的東西;房間只有在整理的那一天最乾淨
                    """
                    maimai_chatbot_name = gr.State("maimai")
                    gr.Image(value=maimai_chatbot_avatar_url, height=100, width=100, show_label=False, show_download_button=False)
                    maimai_chatbot_select_btn = gr.Button("👆選擇【麥麥】", visible=True, variant="primary", elem_classes="chatbot_select_btn")
                    with gr.Accordion("💙 麥麥 敘述", open=False):
                        maimai_chatbot_description_value = gr.Markdown(value=maimai_chatbot_description, visible=True)
                # 飛特音速
                with gr.Column(scale=1, variant="panel", visible=True):
                    streaming_chatbot_avatar_url = "https://storage.googleapis.com/wpassets.junyiacademy.org/1/2020/11/1-%E6%98%9F%E7%A9%BA%E9%A0%AD%E8%B2%BC-%E5%A4%AA%E7%A9%BA%E7%8B%90%E7%8B%B8%E8%B2%93-150x150.png"
                    streaming_chatbot_description = """Hi,我是【飛特音速】, \n
                    說話比較快,但有什麼問題都可以問我喔! \n
                    🚀 我沒有預設問題、也沒有語音輸入,適合快問快答,一起練習問出好問題吧 \n
                    🔠 擅長用文字表達的你,可以用鍵盤輸入你的問題,我會盡力回答你的問題喔\n
                    💤 我還在成長,體力有限,每一次學習只能回答十個問題,請讓我休息一下再問問題喔~
                    """
                    chatbot_open_ai_streaming_name = gr.State("chatbot_open_ai_streaming")
                    gr.Image(value=streaming_chatbot_avatar_url, height=100, width=100, show_label=False, show_download_button=False)
                    chatbot_open_ai_streaming_select_btn = gr.Button("👆選擇【飛特音速】", elem_id="streaming_chatbot_btn", visible=True, variant="primary")
                    with gr.Accordion("🚀 飛特音速 敘述", open=False):
                        gr.Markdown(value=streaming_chatbot_description, visible=True)
                # 尚未開放
                with gr.Column(scale=1, variant="panel"): 
                    gr.Markdown(value="### 尚未開放", visible=True)

        with gr.Row("飛特音速") as chatbot_open_ai_streaming:
            with gr.Column():
                streaming_chat_greeting = """
                Hi,我是【飛特音速】,說話比較快,但有什麼問題都可以問我喔! \n
                    🚀 我沒有預設問題、也沒有語音輸入,適合快問快答的你 \n
                    🔠 鍵盤輸入你的問題,我會盡力回答你的問題喔!\n
                    💤 我還在成長,體力有限,每一次學習只能回答十個問題,請讓我休息一下再問問題喔!
                    """
                additional_inputs = [password, video_id, user_data, streaming_chat_thread_id_state, trascript_state, key_moments_state, content_subject_state, content_grade_state, ai_chatbot_socratic_mode_btn]
                streaming_chat = gr.ChatInterface(
                    fn=chat_with_opan_ai_assistant_streaming,
                    additional_inputs=additional_inputs,
                    submit_btn="送出",
                    retry_btn=None,
                    undo_btn="⏪ 上一步",
                    clear_btn="🗑️ 清除全部",
                    stop_btn=None,
                    description=streaming_chat_greeting
                )
        with gr.Row("一般精靈") as chatbot_ai:   
            with gr.Column():
                ai_chatbot_greeting = [[
                    "請問你是誰?",
                    """Hi,我是飛特精靈的朋友們【梨梨、麥麥、狐狸貓】,也可以陪你一起學習本次的內容,有什麼問題都可以問我喔!
                    🤔 如果你不知道怎麼發問,可以點擊左下方的問題一、問題二、問題三,我會幫你生成問題!
                    🗣️ 也可以點擊右下方用語音輸入,我會幫你轉換成文字,厲害吧!
                    🔠 或是直接鍵盤輸入你的問題,我會盡力回答你的問題喔!
                    💤 精靈們體力都有限,每一次學習只能回答十個問題,請讓我休息一下再問問題喔!
                    """,
                ]]
                with gr.Row():
                    ai_chatbot = gr.Chatbot(label="ai_chatbot", show_share_button=False, likeable=True, show_label=False, latex_delimiters=latex_delimiters, value=ai_chatbot_greeting)                    
                with gr.Row():
                    with gr.Accordion("你也有類似的問題想問嗎? 請按下 ◀︎", open=False) as ask_questions_accordion_2:
                        ai_chatbot_question_1 = gr.Button("問題一")
                        ai_chatbot_question_2 = gr.Button("問題一")
                        ai_chatbot_question_3 = gr.Button("問題一")
                        create_questions_btn = gr.Button("生成問題", variant="primary")
                    ai_chatbot_audio_input = gr.Audio(sources=["microphone"], type="filepath", max_length=60, label="語音輸入")
                with gr.Row():
                    ai_msg = gr.Textbox(label="訊息輸入",scale=3)
                    ai_send_button = gr.Button("送出", variant="primary",scale=1)
                    ai_send_feedback_btn = gr.Button("提問力回饋", variant="primary", scale=1, visible=False)          
    with gr.Tab("文章模式"):
        with gr.Row():
            reading_passage = gr.Markdown(show_label=False, latex_delimiters = [{"left": "$", "right": "$", "display": False}])
            reading_passage_speak_button = gr.Button("Speak", visible=False)
            reading_passage_audio_output = gr.Audio(label="Audio Output", visible=False) 
    with gr.Tab("重點摘要"):
        with gr.Row():
            df_summarise = gr.Markdown(show_label=False, latex_delimiters = [{"left": "$", "right": "$", "display": False}])
    with gr.Tab("關鍵時刻"):
        with gr.Row():
            key_moments_html = gr.HTML(value="")
    with gr.Tab("教學備課"):
        with gr.Row():
            content_subject = gr.Dropdown(label="選擇主題", choices=["數學", "自然", "國文", "英文", "社會","物理", "化學", "生物", "地理", "歷史", "公民"], value="", visible=False)             
            content_grade = gr.Dropdown(label="選擇年級", choices=["一年級", "二年級", "三年級", "四年級", "五年級", "六年級", "七年級", "八年級", "九年級", "十年級", "十一年級", "十二年級"], value="", visible=False)
            content_level = gr.Dropdown(label="差異化教學", choices=["基礎", "中級", "進階"], value="基礎")
        with gr.Row():
            with gr.Tab("學習單"):
                with gr.Row():
                    with gr.Column(scale=1):
                        with gr.Row():
                            worksheet_content_type_name = gr.Textbox(value="worksheet", visible=False)
                            worksheet_algorithm = gr.Dropdown(label="選擇教學策略或理論", choices=["Bloom認知階層理論", "Polya數學解題法", "CRA教學法"], value="Bloom認知階層理論", visible=False)
                            worksheet_content_btn = gr.Button("生成學習單 📄", variant="primary", visible=True)
                        with gr.Accordion("微調", open=False):
                            worksheet_result_fine_tune_prompt = gr.Textbox(label="根據結果,輸入你想更改的想法")
                            worksheet_result_fine_tune_btn = gr.Button("微調結果", variant="primary")
                            worksheet_result_retrun_original = gr.Button("返回原始結果")
                        with gr.Accordion("prompt", open=False) as worksheet_accordion:
                            worksheet_prompt = gr.Textbox(label="worksheet_prompt", show_copy_button=True, lines=40)
                    with gr.Column(scale=2):
                        # 生成對應不同模式的結果
                        worksheet_result_prompt = gr.Textbox(visible=False)
                        worksheet_result_original = gr.Textbox(visible=False)
                        worksheet_result = gr.Markdown(label="初次生成結果", latex_delimiters = [{"left": "$", "right": "$", "display": False}])
                        worksheet_download_button = gr.Button("轉成 word,完成後請點擊右下角 download 按鈕", variant="primary")
                        worksheet_result_word_link = gr.File(label="Download Word")
            with gr.Tab("教案"):
                with gr.Row():
                    with gr.Column(scale=1):
                        with gr.Row():
                            lesson_plan_content_type_name = gr.Textbox(value="lesson_plan", visible=False)                    
                            lesson_plan_time = gr.Slider(label="選擇課程時間(分鐘)", minimum=10, maximum=120, step=5, value=40)
                            lesson_plan_btn = gr.Button("生成教案 📕", variant="primary", visible=True)
                        with gr.Accordion("微調", open=False):
                            lesson_plan_result_fine_tune_prompt = gr.Textbox(label="根據結果,輸入你想更改的想法")
                            lesson_plan_result_fine_tune_btn = gr.Button("微調結果", variant="primary")
                            lesson_plan_result_retrun_original = gr.Button("返回原始結果")
                        with gr.Accordion("prompt", open=False) as lesson_plan_accordion:
                            lesson_plan_prompt = gr.Textbox(label="worksheet_prompt", show_copy_button=True, lines=40)
                    with gr.Column(scale=2):
                        # 生成對應不同模式的結果
                        lesson_plan_result_prompt = gr.Textbox(visible=False)
                        lesson_plan_result_original = gr.Textbox(visible=False)
                        lesson_plan_result = gr.Markdown(label="初次生成結果", latex_delimiters = [{"left": "$", "right": "$", "display": False}])
                        
                        lesson_plan_download_button = gr.Button("轉成 word,完成後請點擊右下角 download 按鈕", variant="primary")
                        lesson_plan_result_word_link = gr.File(label="Download Word")
            with gr.Tab("出場券"):
                with gr.Row():
                    with gr.Column(scale=1):
                        with gr.Row():
                            exit_ticket_content_type_name = gr.Textbox(value="exit_ticket", visible=False)
                            exit_ticket_time = gr.Slider(label="選擇出場券時間(分鐘)", minimum=5, maximum=10, step=1, value=8)
                            exit_ticket_btn = gr.Button("生成出場券 🎟️", variant="primary", visible=True)
                        with gr.Accordion("微調", open=False):
                            exit_ticket_result_fine_tune_prompt = gr.Textbox(label="根據結果,輸入你想更改的想法")
                            exit_ticket_result_fine_tune_btn = gr.Button("微調結果", variant="primary")
                            exit_ticket_result_retrun_original = gr.Button("返回原始結果")
                        with gr.Accordion("prompt", open=False) as exit_ticket_accordion:
                            exit_ticket_prompt = gr.Textbox(label="worksheet_prompt", show_copy_button=True, lines=40)
                    with gr.Column(scale=2):
                        # 生成對應不同模式的結果
                        exit_ticket_result_prompt = gr.Textbox(visible=False)
                        exit_ticket_result_original = gr.Textbox(visible=False)
                        exit_ticket_result = gr.Markdown(label="初次生成結果", latex_delimiters = [{"left": "$", "right": "$", "display": False}])
                        
                        exit_ticket_download_button = gr.Button("轉成 word,完成後請點擊右下角 download 按鈕", variant="primary")
                        exit_ticket_result_word_link = gr.File(label="Download Word")


                # with gr.Tab("素養導向閱讀題組"):
                #     literacy_oriented_reading_content = gr.Textbox(label="輸入閱讀材料")
                #     literacy_oriented_reading_content_btn = gr.Button("生成閱讀理解題")

                # with gr.Tab("自我評估"):
                #     self_assessment_content = gr.Textbox(label="輸入自評問卷或檢查表")
                #     self_assessment_content_btn = gr.Button("生成自評問卷")
                # with gr.Tab("自我反思評量"):
                #     self_reflection_content = gr.Textbox(label="輸入自我反思活動")
                #     self_reflection_content_btn = gr.Button("生成自我反思活動")
                # with gr.Tab("後設認知"):
                #     metacognition_content = gr.Textbox(label="輸入後設認知相關問題")
                #     metacognition_content_btn = gr.Button("生成後設認知問題")

    with gr.Accordion("See Details", open=False) as see_details:
        with gr.Row():
            is_env_prod = gr.Checkbox(value=False, label="is_env_prod")
            LLM_model = gr.Dropdown(label="LLM Model", choices=["open-ai-gpt-4o", "anthropic-claude-3-sonnet"], value="open-ai-gpt-4o", visible=True, interactive=True)
        with gr.Tab("逐字稿本文"):
            with gr.Row() as transcript_admmin:
                transcript_kind = gr.Textbox(value="transcript", show_label=False)
                transcript_get_button = gr.Button("取得", size="sm", variant="primary")
                transcript_edit_button = gr.Button("編輯", size="sm", variant="primary")
                transcript_update_button = gr.Button("儲存", size="sm", variant="primary")
                transcript_delete_button = gr.Button("刪除", size="sm", variant="primary")
                transcript_create_button = gr.Button("重建", size="sm", variant="primary")
            with gr.Row():
                df_string_output = gr.Textbox(lines=40, label="Data Text", interactive=False, show_copy_button=True)
        with gr.Tab("文章本文"):
            with gr.Row() as reading_passage_admin:
                with gr.Column():
                    with gr.Row():
                        reading_passage_kind = gr.Textbox(value="reading_passage_latex", show_label=False)
                    with gr.Row():
                        # reading_passage_text_to_latex = gr.Button("新增 LaTeX", size="sm", variant="primary")
                        reading_passage_get_button = gr.Button("取得", size="sm", variant="primary")
                        reading_passage_edit_button = gr.Button("編輯", size="sm", variant="primary")
                        reading_passage_update_button = gr.Button("儲存", size="sm", variant="primary")
                        reading_passage_delete_button = gr.Button("刪除", size="sm", variant="primary")
                        reading_passage_create_button = gr.Button("重建", size="sm", variant="primary")
            with gr.Row():
                reading_passage_text = gr.Textbox(label="reading_passage_latex", lines=40, interactive=False, show_copy_button=True)
        with gr.Tab("重點摘要本文"):
            with gr.Row() as summary_admmin:
                with gr.Column():
                    with gr.Row():
                        summary_kind = gr.Textbox(value="summary_markdown", show_label=False)
                    with gr.Row():
                        # summary_to_markdown = gr.Button("新增 Markdown", size="sm", variant="primary")
                        summary_get_button = gr.Button("取得", size="sm", variant="primary")
                        summary_edit_button = gr.Button("編輯", size="sm", variant="primary")
                        summary_update_button = gr.Button("儲存", size="sm", variant="primary")
                        summary_delete_button = gr.Button("刪除", size="sm", variant="primary")
                        summary_create_button = gr.Button("重建", size="sm", variant="primary")
            with gr.Row():
                summary_text = gr.Textbox(label="summary_markdown", lines=40, interactive=False, show_copy_button=True)
        with gr.Tab("關鍵時刻本文"):
            with gr.Row() as key_moments_admin:
                key_moments_kind = gr.Textbox(value="key_moments", show_label=False)
                key_moments_get_button = gr.Button("取得", size="sm", variant="primary")
                key_moments_edit_button = gr.Button("編輯", size="sm", variant="primary")
                key_moments_update_button = gr.Button("儲存", size="sm", variant="primary")
                key_moments_delete_button = gr.Button("刪除", size="sm", variant="primary")
                key_moments_create_button = gr.Button("重建", size="sm", variant="primary")
            with gr.Row():
                key_moments = gr.Textbox(label="Key Moments", lines=40, interactive=False, show_copy_button=True)
        with gr.Tab("問題本文"):
            with gr.Row() as question_list_admin:
                questions_kind = gr.Textbox(value="questions", show_label=False)
                questions_get_button = gr.Button("取得", size="sm", variant="primary")
                questions_edit_button = gr.Button("編輯", size="sm", variant="primary")
                questions_update_button = gr.Button("儲存", size="sm", variant="primary")
                questions_delete_button = gr.Button("刪除", size="sm", variant="primary")
                questions_create_button = gr.Button("重建", size="sm", variant="primary")
            with gr.Row():
                questions_json = gr.Textbox(label="Questions", lines=40, interactive=False, show_copy_button=True)
        with gr.Tab("問題答案本文"):
            with gr.Row() as questions_answers_admin:
                questions_answers_kind = gr.Textbox(value="questions_answers", show_label=False)
                questions_answers_get_button = gr.Button("取得", size="sm", variant="primary")
                questions_answers_edit_button = gr.Button("編輯", size="sm", variant="primary")
                questions_answers_update_button = gr.Button("儲存", size="sm", variant="primary")
                questions_answers_delete_button = gr.Button("刪除", size="sm", variant="primary")
                questions_answers_create_button = gr.Button("重建", size="sm", variant="primary")
            with gr.Row():
                questions_answers_json = gr.Textbox(label="Questions Answers", lines=40, interactive=False, show_copy_button=True)
        with gr.Tab("教學備課"):
            with gr.Row() as worksheet_admin:
                worksheet_kind = gr.Textbox(value="ai_content_list", show_label=False)
                worksheet_get_button = gr.Button("取得", size="sm", variant="primary")
                worksheet_edit_button = gr.Button("編輯", size="sm", variant="primary")
                worksheet_update_button = gr.Button("儲存", size="sm", variant="primary")
                worksheet_delete_button = gr.Button("刪除", size="sm", variant="primary")
                worksheet_create_button = gr.Button("重建(X)", size="sm", variant="primary", interactive=False)
            with gr.Row():
                worksheet_json = gr.Textbox(label="worksheet", lines=40, interactive=False, show_copy_button=True)      
        with gr.Tab("逐字稿"):
            simple_html_content = gr.HTML(label="Simple Transcript")
        with gr.Tab("圖文"):
            transcript_html = gr.HTML(label="YouTube Transcript and Video") 
        with gr.Tab("markdown"):
            gr.Markdown("## 請複製以下 markdown 並貼到你的心智圖工具中,建議使用:https://markmap.js.org/repl")
            mind_map = gr.Textbox(container=True, show_copy_button=True, lines=40, elem_id="mind_map_markdown") 
        with gr.Tab("心智圖",elem_id="mind_map_tab"):
            mind_map_html = gr.HTML()
       
    # OPEN AI CHATBOT SELECT
    chatbot_select_outputs=[
        chatbot_select_accordion, 
        all_chatbot_select_btn, 
        chatbot_open_ai_streaming, 
        chatbot_ai, 
        ai_name,
        ai_chatbot_ai_type,
        ai_chatbot_thread_id
    ]
    # 聊天机器人的配置数据
    chatbots = [
        {
            "button": vaitor_chatbot_select_btn,
            "name_state": chatbot_open_ai_name,
            "avatar_images": vaitor_chatbot_avatar_images,
            "description_value": vaitor_chatbot_description_value,
            "chatbot_select_outputs": chatbot_select_outputs,
            "chatbot_output": ai_chatbot
        },
        {
            "button": foxcat_chatbot_select_btn,
            "name_state": foxcat_chatbot_name,
            "avatar_images": foxcat_avatar_images,
            "description_value": foxcat_chatbot_description_value,
            "chatbot_select_outputs": chatbot_select_outputs,
            "chatbot_output": ai_chatbot
        },
        {
            "button": lili_chatbot_select_btn,
            "name_state": lili_chatbot_name,
            "avatar_images": lili_avatar_images,
            "description_value": lili_chatbot_description_value,
            "chatbot_select_outputs": chatbot_select_outputs,
            "chatbot_output": ai_chatbot
        },
        {
            "button": maimai_chatbot_select_btn,
            "name_state": maimai_chatbot_name,
            "avatar_images": maimai_avatar_images,
            "description_value": maimai_chatbot_description_value,
            "chatbot_select_outputs": chatbot_select_outputs,
            "chatbot_output": ai_chatbot
        }
    ]

    def setup_chatbot_select_button(chatbot_dict):
        button = chatbot_dict["button"]
        chatbot_name_state = chatbot_dict["name_state"]
        avatar_images = chatbot_dict["avatar_images"]
        description_value = chatbot_dict["description_value"]
        chatbot_select_outputs = chatbot_dict["chatbot_select_outputs"]
        chatbot_output = chatbot_dict["chatbot_output"]
        button.click(
            chatbot_select,  # 你可能需要修改这个函数以适应当前的逻辑
            inputs=[chatbot_name_state],
            outputs=chatbot_select_outputs
        ).then(
            update_avatar_images,
            inputs=[avatar_images, description_value],
            outputs=[chatbot_output],
            scroll_to_output=True
        )

    for chatbot_dict in chatbots:
        setup_chatbot_select_button(chatbot_dict)

    # STREAMING CHATBOT SELECT
    chatbot_open_ai_streaming_select_btn.click(
        chatbot_select,
        inputs=[chatbot_open_ai_streaming_name],
        outputs=chatbot_select_outputs
    ).then(
        create_thread_id,
        inputs=[],
        outputs=[streaming_chat_thread_id_state]
    )

    # ALL CHATBOT SELECT LIST
    all_chatbot_select_btn.click(
        show_all_chatbot_accordion,
        inputs=[],
        outputs=[chatbot_select_accordion, all_chatbot_select_btn]
    )
    # OPENAI ASSISTANT CHATBOT 連接按鈕點擊事件
    def setup_question_button_click(button, inputs_list, outputs_list, chat_func, scroll_to_output=True):
        button.click(
        chat_func,
        inputs=inputs_list,
        outputs=outputs_list,
        scroll_to_output=scroll_to_output
    )

    # 其他精靈 ai_chatbot 模式
    ai_send_button.click(
        chat_with_any_ai,
        inputs=[ai_chatbot_ai_type, password, video_id, user_data, trascript_state, key_moments, ai_msg, ai_chatbot, content_subject, content_grade, questions_answers_json, ai_chatbot_socratic_mode_btn, ai_chatbot_thread_id, ai_name],
        outputs=[ai_msg, ai_chatbot, ai_send_button, ai_send_feedback_btn, ai_chatbot_thread_id],
        scroll_to_output=True
    )
    ai_send_feedback_btn.click(
        feedback_with_ai,
        inputs=[user_data, ai_chatbot_ai_type, ai_chatbot, ai_chatbot_thread_id],
        outputs=[ai_chatbot, ai_send_feedback_btn],
        scroll_to_output=True
    )
    # 其他精靈 ai_chatbot 连接 QA 按钮点击事件
    ai_chatbot_question_buttons = [ai_chatbot_question_1, ai_chatbot_question_2, ai_chatbot_question_3]
    for question_btn in ai_chatbot_question_buttons:
        inputs_list = [ai_chatbot_ai_type, password, video_id, user_data, trascript_state, key_moments, question_btn, ai_chatbot, content_subject, content_grade, questions_answers_json, ai_chatbot_socratic_mode_btn, ai_chatbot_thread_id, ai_name]
        outputs_list = [ai_msg, ai_chatbot, ai_send_button, ai_send_feedback_btn, ai_chatbot_thread_id]
        setup_question_button_click(question_btn, inputs_list, outputs_list, chat_with_any_ai)

    # 為生成問題按鈕設定特殊的點擊事件
    question_buttons = [
        ai_chatbot_question_1,
        ai_chatbot_question_2,
        ai_chatbot_question_3
    ]
    create_questions_btn.click(
        change_questions, 
        inputs=[password, df_string_output], 
        outputs=question_buttons
    )
    ai_chatbot_audio_input.change(
        process_open_ai_audio_to_chatbot,
        inputs=[password, ai_chatbot_audio_input],
        outputs=[ai_msg]
    )

    # 当输入 YouTube 链接时触发
    process_youtube_link_inputs = [password, youtube_link, LLM_model]
    process_youtube_link_outputs = [
        video_id,
        questions_answers_json,
        df_string_output, 
        summary_text,
        df_summarise,
        key_moments,
        key_moments_html,
        mind_map, 
        mind_map_html,
        transcript_html,
        simple_html_content, 
        reading_passage_text,
        reading_passage,
        content_subject,
        content_grade,
    ]
    update_state_inputs = [
        content_subject,
        content_grade,
        df_string_output,
        key_moments,
        questions_answers_json,
    ]
    update_state_outputs = [
        content_subject_state, 
        content_grade_state, 
        trascript_state,
        key_moments_state,
        streaming_chat_thread_id_state,
        ai_chatbot_question_1,
        ai_chatbot_question_2,
        ai_chatbot_question_3
    ]

    youtube_link.change(
        process_youtube_link, 
        inputs=process_youtube_link_inputs, 
        outputs=process_youtube_link_outputs
    ).then(
        update_state,
        inputs=update_state_inputs,
        outputs=update_state_outputs
    )

    youtube_link_btn.click(
        process_youtube_link, 
        inputs=process_youtube_link_inputs, 
        outputs=process_youtube_link_outputs
    ).then(
        update_state,
        inputs=update_state_inputs,
        outputs=update_state_outputs
    )


    # --- CRUD admin ---
    def setup_content_buttons(buttons_config):
        for config in buttons_config:
            button = config['button']
            action = config['action']
            inputs = config['inputs']
            outputs = config['outputs']
            button.click(
                fn=action,
                inputs=inputs,
                outputs=outputs
            )

    content_buttons_config = [
        # Transcript actions
        {
            'button': transcript_get_button,
            'action': get_LLM_content,
            'inputs': [video_id, transcript_kind],
            'outputs': [df_string_output]
        },
        {
            'button': transcript_create_button,
            'action': create_LLM_content,
            'inputs': [video_id, df_string_output, transcript_kind, LLM_model],
            'outputs': [df_string_output]
        },
        {
            'button': transcript_delete_button,
            'action': delete_LLM_content,
            'inputs': [video_id, transcript_kind],
            'outputs': [df_string_output]
        },
        {
            'button': transcript_edit_button,
            'action': enable_edit_mode,
            'inputs': [],
            'outputs': [df_string_output]
        },
        {
            'button': transcript_update_button,
            'action': update_LLM_content,
            'inputs': [video_id, df_string_output, transcript_kind],
            'outputs': [df_string_output]
        },
        # Reading passage actions
        {
            'button': reading_passage_get_button,
            'action': get_LLM_content,
            'inputs': [video_id, reading_passage_kind],
            'outputs': [reading_passage_text]
        },
        {
            'button': reading_passage_create_button,
            'action': create_LLM_content,
            'inputs': [video_id, df_string_output, reading_passage_kind, LLM_model],
            'outputs': [reading_passage_text]
        },
        {
            'button': reading_passage_delete_button,
            'action': delete_LLM_content,
            'inputs': [video_id, reading_passage_kind],
            'outputs': [reading_passage_text]
        },
        {
            'button': reading_passage_edit_button,
            'action': enable_edit_mode,
            'inputs': [],
            'outputs': [reading_passage_text]
        },
        {
            'button': reading_passage_update_button,
            'action': update_LLM_content,
            'inputs': [video_id, reading_passage_text, reading_passage_kind],
            'outputs': [reading_passage_text]
        },
        # Summary actions
        {
            'button': summary_get_button,
            'action': get_LLM_content,
            'inputs': [video_id, summary_kind],
            'outputs': [summary_text]
        },
        {
            'button': summary_create_button,
            'action': create_LLM_content,
            'inputs': [video_id, df_string_output, summary_kind, LLM_model],
            'outputs': [summary_text]
        },
        {
            'button': summary_delete_button,
            'action': delete_LLM_content,
            'inputs': [video_id, summary_kind],
            'outputs': [summary_text]
        },
        {
            'button': summary_edit_button,
            'action': enable_edit_mode,
            'inputs': [],
            'outputs': [summary_text]
        },
        {
            'button': summary_update_button,
            'action': update_LLM_content,
            'inputs': [video_id, summary_text, summary_kind],
            'outputs': [summary_text]
        },
        # Key moments actions
        {
            'button': key_moments_get_button,
            'action': get_LLM_content,
            'inputs': [video_id, key_moments_kind],
            'outputs': [key_moments]
        },
        {
            'button': key_moments_create_button,
            'action': create_LLM_content,
            'inputs': [video_id, df_string_output, key_moments_kind, LLM_model],
            'outputs': [key_moments]
        },
        {
            'button': key_moments_delete_button,
            'action': delete_LLM_content,
            'inputs': [video_id, key_moments_kind],
            'outputs': [key_moments]
        },
        {
            'button': key_moments_edit_button,
            'action': enable_edit_mode,
            'inputs': [],
            'outputs': [key_moments]
        },
        {
            'button': key_moments_update_button,
            'action': update_LLM_content,
            'inputs': [video_id, key_moments, key_moments_kind],
            'outputs': [key_moments]
        },
        # Questions actions
        {
            'button': questions_get_button,
            'action': get_LLM_content,
            'inputs': [video_id, questions_kind],
            'outputs': [questions_json]
        },
        {
            'button': questions_create_button,
            'action': create_LLM_content,
            'inputs': [video_id, df_string_output, questions_kind, LLM_model],
            'outputs': [questions_json]
        },
        {
            'button': questions_delete_button,
            'action': delete_LLM_content,
            'inputs': [video_id, questions_kind],
            'outputs': [questions_json]
        },
        {
            'button': questions_edit_button,
            'action': enable_edit_mode,
            'inputs': [],
            'outputs': [questions_json]
        },
        {
            'button': questions_update_button,
            'action': update_LLM_content,
            'inputs': [video_id, questions_json, questions_kind],
            'outputs': [questions_json]
        },
        # Questions answers actions
        {
            'button': questions_answers_get_button,
            'action': get_LLM_content,
            'inputs': [video_id, questions_answers_kind],
            'outputs': [questions_answers_json]
        },
        {
            'button': questions_answers_create_button,
            'action': create_LLM_content,
            'inputs': [video_id, df_string_output, questions_answers_kind, LLM_model],
            'outputs': [questions_answers_json]
        },
        {
            'button': questions_answers_delete_button,
            'action': delete_LLM_content,
            'inputs': [video_id, questions_answers_kind],
            'outputs': [questions_answers_json]
        },
        {
            'button': questions_answers_edit_button,
            'action': enable_edit_mode,
            'inputs': [],
            'outputs': [questions_answers_json]
        },
        {
            'button': questions_answers_update_button,
            'action': update_LLM_content,
            'inputs': [video_id, questions_answers_json, questions_answers_kind],
            'outputs': [questions_answers_json]
        },
        # Worksheet actions
        {
            'button': worksheet_get_button,
            'action': get_LLM_content,
            'inputs': [video_id, worksheet_kind],
            'outputs': [worksheet_json]
        },
        {
            'button': worksheet_create_button,
            'action': create_LLM_content,
            'inputs': [video_id, df_string_output, worksheet_kind, LLM_model],
            'outputs': [worksheet_json]
        },
        {
            'button': worksheet_delete_button,
            'action': delete_LLM_content,
            'inputs': [video_id, worksheet_kind],
            'outputs': [worksheet_json]
        },
        {
            'button': worksheet_edit_button,
            'action': enable_edit_mode,
            'inputs': [],
            'outputs': [worksheet_json]
        },
        {
            'button': worksheet_update_button,
            'action': update_LLM_content,
            'inputs': [video_id, worksheet_json, worksheet_kind],
            'outputs': [worksheet_json]
        },
    ]
    setup_content_buttons(content_buttons_config)

    # --- Education Material ---
    def setup_education_buttons(buttons_config):
        for config in buttons_config:
            button = config["button"]
            action = config["action"]
            inputs = config["inputs"]
            outputs = config["outputs"]
            button.click(
                fn=action,
                inputs=inputs,
                outputs=outputs
            )
    education_buttons_config = [
        # 學習單相關按鈕
        {
            "button": worksheet_content_btn,
            "action": get_ai_content,
            "inputs": [password, user_data, video_id, df_string_output, content_subject, content_grade, content_level, worksheet_algorithm, worksheet_content_type_name],
            "outputs": [worksheet_result_original, worksheet_result, worksheet_prompt, worksheet_result_prompt]
        },
        {
            "button": worksheet_result_fine_tune_btn,
            "action": generate_ai_content_fine_tune_result,
            "inputs": [password, user_data, worksheet_result_prompt, df_string_output, worksheet_result, worksheet_result_fine_tune_prompt, worksheet_content_type_name],
            "outputs": [worksheet_result]
        },
        {
            "button": worksheet_download_button,
            "action": download_exam_result,
            "inputs": [worksheet_result],
            "outputs": [worksheet_result_word_link]
        },
        {
            "button": worksheet_result_retrun_original,
            "action": return_original_exam_result,
            "inputs": [worksheet_result_original],
            "outputs": [worksheet_result]
        },
        # 教案相關按鈕
        {
            "button": lesson_plan_btn,
            "action": get_ai_content,
            "inputs": [password, user_data, video_id, df_string_output, content_subject, content_grade, content_level, lesson_plan_time, lesson_plan_content_type_name],
            "outputs": [lesson_plan_result_original, lesson_plan_result, lesson_plan_prompt, lesson_plan_result_prompt]
        },
        {
            "button": lesson_plan_result_fine_tune_btn,
            "action": generate_ai_content_fine_tune_result,
            "inputs": [password, user_data, lesson_plan_result_prompt, df_string_output, lesson_plan_result, lesson_plan_result_fine_tune_prompt, lesson_plan_content_type_name],
            "outputs": [lesson_plan_result]
        },
        {
            "button": lesson_plan_download_button,
            "action": download_exam_result,
            "inputs": [lesson_plan_result],
            "outputs": [lesson_plan_result_word_link]
        },
        {
            "button": lesson_plan_result_retrun_original,
            "action": return_original_exam_result,
            "inputs": [lesson_plan_result_original],
            "outputs": [lesson_plan_result]
        },
        # 出場券相關按鈕
        {
            "button": exit_ticket_btn,
            "action": get_ai_content,
            "inputs": [password, user_data, video_id, df_string_output, content_subject, content_grade, content_level, exit_ticket_time, exit_ticket_content_type_name],
            "outputs": [exit_ticket_result_original, exit_ticket_result, exit_ticket_prompt, exit_ticket_result_prompt]
        },
        {
            "button": exit_ticket_result_fine_tune_btn,
            "action": generate_ai_content_fine_tune_result,
            "inputs": [password, user_data, exit_ticket_result_prompt, df_string_output, exit_ticket_result, exit_ticket_result_fine_tune_prompt, exit_ticket_content_type_name],
            "outputs": [exit_ticket_result]
        },
        {
            "button": exit_ticket_download_button,
            "action": download_exam_result,
            "inputs": [exit_ticket_result],
            "outputs": [exit_ticket_result_word_link]
        },
        {
            "button": exit_ticket_result_retrun_original,
            "action": return_original_exam_result,
            "inputs": [exit_ticket_result_original],
            "outputs": [exit_ticket_result]
        }
    ]
    setup_education_buttons(education_buttons_config)

    # init_params
    init_outputs = [
        admin, 
        reading_passage_admin, 
        summary_admmin, 
        see_details,
        worksheet_accordion, 
        lesson_plan_accordion, 
        exit_ticket_accordion,
        password, 
        youtube_link,
        chatbot_open_ai_streaming,
        chatbot_ai,
        ai_chatbot_params,
        is_env_prod,
    ]
    demo.load(
        init_params, 
        inputs =[youtube_link],
        outputs = init_outputs
    )

demo.launch(allowed_paths=["videos"], server_name="0.0.0.0", server_port=7860)