File size: 194,049 Bytes
70c6613
46f5603
c775910
9a7a5d5
70c6613
 
0e729c5
9a2b012
5c4cdd1
 
646e937
a0a3ddc
a6fb9ef
4288196
d4e991b
70c6613
5c4cdd1
 
 
2a3dc52
 
 
 
 
 
 
 
 
5c4cdd1
70c6613
 
5118e23
 
2a3dc52
 
5c4cdd1
70c6613
10588ca
5118e23
15b9da3
029fc0c
70c6613
5118e23
f4a1918
5c4cdd1
 
 
 
48c99b6
 
78f5c78
7421597
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ca3ee1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec43651
 
 
 
 
 
 
 
 
 
2ca3ee1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec43651
 
 
 
 
 
 
 
2ca3ee1
 
 
 
 
 
11b1dbb
 
 
 
7421597
 
 
 
 
 
 
 
 
 
 
11b1dbb
07a55ac
 
 
 
 
7421597
 
11b1dbb
 
 
 
 
 
877f289
 
11b1dbb
 
 
 
877f289
11b1dbb
 
ec43651
 
 
 
 
 
 
 
 
 
 
 
500c53b
2ca3ee1
500c53b
01fac1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec43651
 
 
 
 
 
 
01fac1e
 
 
2ca3ee1
f7092d6
2ca3ee1
500c53b
 
 
e9f90d1
500c53b
 
 
 
e9f90d1
 
 
500c53b
 
f7092d6
 
500c53b
11b1dbb
2ca3ee1
 
 
c9e97ad
daa5f8e
 
 
 
 
07a55ac
 
 
 
 
 
daa5f8e
 
 
 
 
 
 
 
 
 
 
 
 
ec43651
 
 
 
 
 
 
daa5f8e
e56d3c5
 
 
 
daa5f8e
cc83ab8
 
 
 
 
07a55ac
 
 
 
 
 
cc83ab8
 
 
 
 
 
 
 
 
 
 
466d591
cc83ab8
 
ec43651
 
 
 
 
 
 
 
cc83ab8
af1d454
 
 
 
12a83ad
 
 
 
 
169fbfd
12a83ad
 
07a55ac
c1ee647
 
 
 
07a55ac
 
c1ee647
 
 
0e729c5
c1ee647
 
 
 
 
 
07a55ac
c1ee647
9a7a5d5
c1ee647
 
 
a85c4be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a7a5d5
 
 
07a55ac
19c63ff
 
 
 
07a55ac
 
 
19c63ff
 
 
0e729c5
19c63ff
 
 
 
07a55ac
19c63ff
9a7a5d5
19c63ff
 
 
a85c4be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a7a5d5
 
 
0e729c5
 
 
9a7a5d5
0e729c5
 
 
9a7a5d5
0e729c5
 
9a7a5d5
0e729c5
 
9a7a5d5
0e729c5
 
19c63ff
0e729c5
 
8bc08bd
0e729c5
 
19c63ff
9a7a5d5
 
 
07a55ac
f35c083
 
 
 
07a55ac
 
 
f35c083
 
 
0e729c5
f35c083
 
 
 
 
 
07a55ac
f35c083
0e729c5
f35c083
 
 
a85c4be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f35c083
0e729c5
9a7a5d5
0e729c5
 
9a7a5d5
ea53a26
5c4cdd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56d1ceb
 
 
c584705
 
 
 
 
 
5c4cdd1
4288196
03b8934
 
5c4cdd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4d5ef7
56d1ceb
 
 
 
 
 
 
 
 
 
 
 
 
20da85e
 
c2544ea
20da85e
c2544ea
 
 
 
 
 
 
20da85e
a6fb9ef
 
20da85e
a6fb9ef
 
20da85e
c2544ea
 
20da85e
c2544ea
 
 
 
6e5cbf8
05d2f62
 
 
 
5c4cdd1
 
4288196
 
5c4cdd1
 
 
 
 
 
234c26c
 
5c4cdd1
 
 
 
 
 
 
 
03b8934
5c4cdd1
 
 
 
d4e991b
 
 
 
 
 
 
 
 
 
 
 
5c4cdd1
d4e991b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92b4253
ea53a26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c4cdd1
54be502
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c4cdd1
70c6613
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92b4253
70c6613
92b4253
70c6613
92b4253
bc234ab
 
 
 
 
 
 
 
 
 
 
51534fc
 
 
 
 
70c6613
e205f14
51534fc
e205f14
51534fc
 
 
 
 
 
 
 
 
 
e205f14
70c6613
e205f14
 
 
 
 
51534fc
 
 
 
70c6613
e205f14
51534fc
e205f14
51534fc
 
 
 
 
 
 
 
e205f14
70c6613
e205f14
 
 
 
 
51534fc
 
70c6613
e205f14
51534fc
e205f14
51534fc
 
 
 
70c6613
e205f14
51534fc
e205f14
51534fc
 
361e0a3
70c6613
 
bc8513b
 
 
5118e23
 
 
 
 
 
 
 
 
 
 
 
 
 
bc8513b
70c6613
bc8513b
5118e23
 
70c6613
 
 
 
 
 
 
 
 
 
 
 
 
4614217
 
 
70c6613
 
 
 
 
 
 
 
 
 
e205f14
 
 
 
 
bc8513b
 
5118e23
 
e205f14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70c6613
 
 
 
 
5118e23
 
70c6613
 
 
e205f14
 
 
 
 
 
 
70c6613
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e205f14
 
 
 
 
70c6613
 
 
 
 
 
 
 
 
 
ec43651
 
70c6613
 
 
361e0a3
f97a7cb
 
 
2ca3ee1
 
 
361e0a3
 
 
2ca3ee1
5118e23
 
2ca3ee1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec43651
 
 
 
 
 
2ca3ee1
 
 
9a2b012
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca3ba83
d772cc2
 
 
 
 
 
e9f90d1
8ece90f
e9f90d1
 
d772cc2
 
e9f90d1
0d37efe
 
 
 
 
 
d3658c3
0d37efe
8692287
e9f90d1
0d37efe
 
e9f90d1
5c4cdd1
 
 
 
646e937
 
 
e9f90d1
27122a0
e9f90d1
 
 
 
 
 
 
096737d
 
 
 
 
 
 
e9f90d1
096737d
d772cc2
d56bfcf
 
 
 
 
 
06ba552
 
 
 
 
5c4cdd1
06ba552
 
 
5c4cdd1
06ba552
 
 
 
 
 
 
 
 
 
5c4cdd1
06ba552
 
 
5c4cdd1
06ba552
 
 
 
 
 
 
 
 
 
5c4cdd1
06ba552
 
 
5c4cdd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06ba552
 
 
 
361e0a3
 
 
 
 
06ba552
361e0a3
2ca3ee1
8692287
48a24ba
5c4cdd1
0d37efe
096737d
0d37efe
e9f90d1
 
 
5f5d0ae
 
5f15d42
 
 
 
 
 
 
d90db27
5f15d42
e9f90d1
06ba552
5f15d42
06ba552
5f15d42
06ba552
5c4cdd1
4288196
656d53f
06ba552
5d5552b
 
 
5f15d42
 
 
 
 
 
 
 
 
 
 
 
fe42d36
 
 
5f15d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9f90d1
5f15d42
e9f90d1
5f15d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9f90d1
 
5f15d42
e9f90d1
5f15d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9f90d1
5f15d42
 
 
 
e9f90d1
 
5f15d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
517008f
5f15d42
517008f
 
 
 
 
 
 
0e4505a
517008f
 
 
 
 
 
 
5f15d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9f90d1
5f15d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7761d2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f15d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8bc08bd
5f15d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fde51d0
 
5f15d42
 
 
 
 
517008f
5f15d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9f90d1
5f15d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01fac1e
5f15d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
517008f
5f15d42
 
dc7c370
5f15d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe42d36
 
 
 
5f15d42
 
 
 
 
517008f
5f15d42
 
 
 
 
 
 
 
 
 
 
 
 
 
2ee552b
5f15d42
2ee552b
361e0a3
2ee552b
 
5f15d42
 
e9f90d1
 
5f15d42
e9f90d1
5f15d42
e9f90d1
5f15d42
 
 
e9f90d1
5f15d42
2ee552b
 
 
 
e9f90d1
5f15d42
 
 
e9f90d1
5f15d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
517008f
e9f90d1
5f15d42
 
e9f90d1
5f15d42
 
361e0a3
5f15d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
517008f
e9f90d1
5f15d42
 
e9f90d1
5f15d42
 
361e0a3
5f15d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9f90d1
5f15d42
 
 
 
 
361e0a3
 
9a2b012
 
 
361e0a3
9a2b012
361e0a3
9a2b012
361e0a3
9a2b012
 
361e0a3
 
 
 
 
9a2b012
 
5f15d42
 
 
 
656d53f
5f15d42
 
361e0a3
5f15d42
 
 
 
 
 
 
 
 
 
361e0a3
5f15d42
 
361e0a3
5f15d42
 
 
 
 
361e0a3
5f15d42
 
 
 
 
 
 
e9f90d1
5c4cdd1
 
 
5f15d42
 
e9f90d1
 
5f15d42
 
 
 
 
 
 
e9f90d1
5f15d42
 
 
 
 
 
 
 
 
 
 
 
 
e9f90d1
5f15d42
e9f90d1
361e0a3
e9f90d1
5f15d42
 
 
 
 
 
 
 
e9f90d1
 
656d53f
06ba552
5d5552b
5f15d42
 
 
 
5d5552b
 
5f15d42
 
5d5552b
5f15d42
 
361e0a3
5f15d42
 
 
 
 
 
 
 
 
 
 
361e0a3
5f15d42
 
 
 
 
 
 
 
 
 
 
 
361e0a3
5f15d42
 
 
 
 
 
 
 
 
 
 
 
 
361e0a3
5f15d42
 
ea53a26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f15d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
656d53f
ea53a26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
656d53f
06ba552
656d53f
5d5552b
5f15d42
 
 
5d5552b
5f15d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9f90d1
5f15d42
 
 
 
 
 
 
 
 
 
 
 
361e0a3
5f15d42
 
 
 
 
e9f90d1
5f15d42
 
 
361e0a3
5f15d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361e0a3
5f15d42
 
 
 
 
 
 
 
 
 
 
 
 
 
54be502
 
 
 
 
 
 
 
361e0a3
54be502
 
e9f90d1
54be502
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f15d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9f90d1
5f15d42
 
 
 
 
 
 
 
 
8bc08bd
5c4cdd1
 
 
 
 
 
361e0a3
234c26c
 
 
03b8934
361e0a3
03b8934
6fdf04f
234c26c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
03b8934
234c26c
03b8934
 
234c26c
 
03b8934
 
 
234c26c
 
 
 
 
 
 
 
 
 
 
 
 
 
ea53a26
361e0a3
ea53a26
 
 
 
361e0a3
ea53a26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f9a8c8
ea53a26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54be502
361e0a3
54be502
 
 
 
361e0a3
54be502
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c4cdd1
54be502
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f15d42
06ba552
 
 
 
5f15d42
 
06ba552
 
 
 
5f15d42
 
06ba552
 
 
 
5f15d42
5c4cdd1
 
 
 
 
 
5f15d42
e9f90d1
 
 
 
 
51534fc
e9f90d1
 
 
075e01e
e9f90d1
 
 
61b0f38
075e01e
 
e9f90d1
075e01e
ac81183
e9f90d1
075e01e
e9f90d1
075e01e
e9f90d1
075e01e
e9f90d1
 
 
 
075e01e
 
e9f90d1
 
 
 
 
e205f14
3845141
 
 
 
 
e205f14
 
 
 
 
11fcd89
e9f90d1
e2c0d62
e205f14
11fcd89
 
70c6613
 
 
 
 
 
 
 
 
 
 
e205f14
 
 
 
 
 
70c6613
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9f90d1
 
70c6613
e9f90d1
 
 
 
 
2ca3ee1
e9f90d1
2ca3ee1
e9f90d1
 
 
 
 
 
70c6613
 
e205f14
e9f90d1
 
e205f14
 
 
 
 
 
 
 
 
 
 
 
 
e9f90d1
 
e205f14
 
 
 
 
 
 
 
 
 
 
 
 
92b4253
e205f14
 
 
 
 
3845141
 
 
 
e205f14
 
 
 
 
 
 
e2c0d62
e205f14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9f90d1
 
096737d
e9f90d1
e205f14
 
 
 
 
 
e9f90d1
 
 
 
 
 
361e0a3
e9f90d1
51534fc
 
 
 
 
 
 
 
 
70c6613
e205f14
 
 
 
 
 
 
 
51534fc
 
 
 
 
 
 
 
 
 
 
70c6613
e205f14
51534fc
e205f14
51534fc
 
 
 
 
70c6613
e205f14
51534fc
e205f14
51534fc
 
 
 
 
 
 
 
 
e9f90d1
70c6613
 
e205f14
e9f90d1
e205f14
e9f90d1
 
 
 
 
e205f14
 
 
e9f90d1
 
 
 
 
 
 
0281f07
51534fc
 
 
 
 
 
 
 
 
 
 
 
 
 
70c6613
e205f14
51534fc
 
 
 
e205f14
51534fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70c6613
e205f14
51534fc
e205f14
51534fc
 
 
 
 
 
 
0281f07
d772cc2
 
 
e9f90d1
5c4cdd1
 
0d37efe
096737d
e9f90d1
 
 
d772cc2
e9f90d1
991d9ac
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

import gradio as gr
from openai import OpenAI

import os
from docx import Document
import random
import uuid
import json
from datetime import datetime
import pytz
import json
import tempfile
import urllib.parse
import pandas as pd
import time

from storage_service import GoogleCloudStorage

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

# KEY CONFIG
if is_env_local:
    with open("local_config.json") as f:
        config = json.load(f)
        IS_ENV_PROD = "False"
        OPEN_AI_KEY = config["OPEN_AI_KEY"]
        GCS_KEY = json.dumps(config["GOOGLE_APPLICATION_CREDENTIALS_JSON"])
        CUTOR_OPEN_AI_KEY = config["CUTOR_OPEN_AI_KEY"]
        CUTOR_OPEN_AI_ASSISTANT_ID = config["CUTOR_OPEN_AI_ASSISTANT_ID"]
        OPEN_AI_MODERATION_BOT1 = config["OPEN_AI_MODERATION_BOT1"]

else:
    OPEN_AI_KEY = os.getenv("OPEN_AI_KEY")
    GCS_KEY = os.getenv("GOOGLE_APPLICATION_CREDENTIALS_JSON")
    CUTOR_OPEN_AI_KEY = os.getenv("CUTOR_OPEN_AI_KEY")
    CUTOR_OPEN_AI_ASSISTANT_ID = os.getenv("CUTOR_OPEN_AI_ASSISTANT_ID")
    OPEN_AI_MODERATION_BOT1 = os.getenv("OPEN_AI_MODERATION_BOT1", OPEN_AI_KEY)

OPEN_AI_CLIENT = OpenAI(api_key=OPEN_AI_KEY)
CUTOR_OPEN_AI_CLIENT = OpenAI(api_key=CUTOR_OPEN_AI_KEY)
OPEN_AI_MODERATION_CLIENT = OpenAI(api_key=OPEN_AI_MODERATION_BOT1)

# 设置 Google Cloud Storage 客户端
GCS_SERVICE = GoogleCloudStorage(GCS_KEY)
GCS_CLIENT = GCS_SERVICE.client

def update_scenario_input(scenario_radio):
    return scenario_radio

def get_exam_history():
    exam_history = """
    92
    Topic: Various Exams in High School Life
    Theme Sentence (First Paragraph): Exams of all kinds have become a necessary part of my high school life.
    Theme Sentence (Second Paragraph): The most unforgettable exam I have ever taken is…
    Keywords:
    giving reasons
    experience

    93
    Topic: Travel Is The Best Teacher
    Theme Sentence (First Paragraph): Explain the advantages of travel.
    Theme Sentence (Second Paragraph): Share personal travel experiences, either domestic or international, to support the first paragraph.
    Keywords:
    enumeration
    experience

    94
    Topic: Organizing the First Reunion After Graduation
    Theme Sentence (First Paragraph): Details of the reunion, including time, location, and activities.
    Theme Sentence (Second Paragraph): Reasons for choosing this type of activity.
    Keywords:
    description
    giving reasons

    95
    Topic: Experiences of Being Misunderstood
    Theme Sentence (First Paragraph): Describe a personal experience of being misunderstood.
    Theme Sentence (Second Paragraph): Discuss the impact and insights gained from this experience.
    Keywords:
    experience
    effect

    96
    Topic: Imagining a World Without Electricity
    Theme Sentence (First Paragraph): Describe what the world would be like without electricity.
    Theme Sentence (Second Paragraph): Explain whether such a world would be good or bad, with examples.
    Keywords:
    description
    giving reasons

    97
    Topic: A Memorable Advertisement
    Theme Sentence (First Paragraph): Describe the content of a memorable TV or print advertisement (e.g., theme, storyline, music, visuals).
    Theme Sentence (Second Paragraph): Explain why the advertisement is memorable.
    Keywords:
    description
    giving reasons
    
    98
    Topic: A Day Without Budget Concerns
    Theme Sentence (First Paragraph): Who would you invite to spend the day with and why?
    Theme Sentence (Second Paragraph): Describe where you would go, what you would do, and why.
    Keywords:
    description
    
    99
    Topic: An Unforgettable Smell
    Theme Sentence (First Paragraph): Describe the situation in which you encountered the smell and your initial feelings.
    Theme Sentence (Second Paragraph): Explain why the smell remains unforgettable.
    Keywords:
    description
    giving reasons
    
    100
    Topic: Your Ideal Graduation Ceremony
    Theme Sentence (First Paragraph): Explain the significance of the graduation ceremony to you.
    Theme Sentence (Second Paragraph): Describe how to arrange or conduct the ceremony to reflect this significance.
    Keywords:
    definition
    enumeration
    """

    return exam_history

def generate_topics(model, max_tokens, sys_content, scenario, eng_level, user_generate_topics_prompt):
    """
    根据系统提示和用户输入的情境及主题,调用OpenAI API生成相关的主题句。
    """

    exam_history = get_exam_history()
    exam_history_prompt = f"""
        Please refer a topic scenario from the following exam history: 
        {exam_history}
        Base on English level to give similar topic scenario. But don't use the same topic scenario.
    """

    user_content = f"""
        english level is: {eng_level}
        ---
        exam_history_prompt: {exam_history_prompt}
        ---
        {user_generate_topics_prompt}
    """
    messages = [
        {"role": "system", "content": sys_content},
        {"role": "user", "content": user_content}
    ]

    request_payload = {
        "model": model,
        "messages": messages,
        "max_tokens": max_tokens,
        "response_format": { "type": "json_object" }
    }

    try:
        response = OPEN_AI_CLIENT.chat.completions.create(**request_payload)
        content = response.choices[0].message.content
        topics = json.loads(content)["topics"]
        print(f"====generate_topics====")
        print(topics)
        gr_update = gr.update(choices=topics, visible=True)
    except Exception as e:
        print(f"An error occurred while generating topics: {e}")
        raise gr.Error("網路塞車,請重新嘗試一次!")

    return gr_update

def update_topic_input(topic):
    return topic

def generate_points(model, max_tokens, sys_content, scenario, eng_level, topic, user_generate_points_prompt):
    """
    根据系统提示和用户输入的情境、主题,调用OpenAI API生成相关的主题句。
    """
    user_content = f"""
        scenario is: {scenario}
        english level is: {eng_level}
        topic is: {topic}
        ---
        {user_generate_points_prompt}
    """
    messages = [
        {"role": "system", "content": sys_content},
        {"role": "user", "content": user_content}
    ]

    request_payload = {
        "model": model,
        "messages": messages,
        "max_tokens": max_tokens,
    }

    try:
        response = OPEN_AI_CLIENT.chat.completions.create(**request_payload)
        content = response.choices[0].message.content
        points = json.loads(content)["points"]
        gr_update = gr.update(choices=points, visible=True)
    except Exception as e:
        print(f"An error occurred while generating points: {e}")
        raise gr.Error("網路塞車,請重新嘗試一次!")

    return gr_update

def update_points_input(points):
    return points

def generate_topic_sentences(model, max_tokens, sys_content, scenario, eng_level, topic, points, user_generate_topic_sentences_prompt):
    """
    根据系统提示和用户输入的情境及要点,调用OpenAI API生成相关的主题句及其合理性解释。
    """

    if eng_level == "台灣學科能力測驗等級":
        exam_history = get_exam_history()
        exam_history_prompt = f"""
            Please refer a topic scenario from the following exam history:
            {exam_history}
            give similar topic scenario and level of English. But don't use the same topic scenario.
        """
    else:
        exam_history_prompt = ""

    user_content = f"""
        scenario is: {scenario}
        english level is: {eng_level}
        topic is: {topic}
        points is: {points}
        ---
        exam_history_prompt: {exam_history_prompt}
        ---
        {user_generate_topic_sentences_prompt}
    """
    messages = [
        {"role": "system", "content": sys_content},
        {"role": "user", "content": user_content}
    ]
    response_format = { "type": "json_object" }

    request_payload = {
        "model": model,
        "messages": messages,
        "max_tokens": max_tokens,
        "response_format": response_format
    }

    try:
        response = OPEN_AI_CLIENT.chat.completions.create(**request_payload)
        response_content = json.loads(response.choices[0].message.content)
        json_content = response_content["results"]
        topic_sentences_list = [item["topic-sentence"] for item in json_content]
        random.shuffle(topic_sentences_list)
        
        gr_update_json = gr.update(value=json_content)
        gr_update_radio = gr.update(choices=topic_sentences_list, visible=True)
    except Exception as e:
        print(f"An error occurred while generating topic sentences: {e}")
        raise gr.Error("網路塞車,請重新嘗試一次!")

    return gr_update_json, gr_update_radio

def generate_topic_sentence_feedback(model, max_tokens, sys_content, scenario, eng_level, topic, points, topic_sentence, user_generate_topic_sentence_feedback_prompt):
    """
    根据系统提示和用户输入的情境、主题、要点、主题句,调用OpenAI API生成相关的主题句反饋。
    """
    user_content = f"""
        scenario is: {scenario}
        english level is: {eng_level}
        topic is: {topic}
        points is: {points}
        ---
        my written topic sentence is: {topic_sentence}
        ---
        {user_generate_topic_sentence_feedback_prompt}
    """
    messages = [
        {"role": "system", "content": sys_content},
        {"role": "user", "content": user_content}
    ]

    request_payload = {
        "model": model,
        "messages": messages,
        "max_tokens": max_tokens,
    }

    try:
        response = OPEN_AI_CLIENT.chat.completions.create(**request_payload)
        content = response.choices[0].message.content.strip()
        gr_update = gr.update(value=content, visible=True)
    except Exception as e:
        print(f"An error occurred while generating topic sentence feedback: {e}")
        raise gr.Error("網路塞車,請重新嘗試一次!")

    return gr_update

def update_topic_sentence_input(topic_sentences_json, selected_topic_sentence):
    topic_sentence_input = ""
    for ts in topic_sentences_json:
        if ts["topic-sentence"] == selected_topic_sentence:
            appropriate = "O 適合" if ts["appropriate"] == "Y" else "X 不適合"
            border_color = "green" if ts["appropriate"] == "Y" else "red"
            text_color = "green" if ts["appropriate"] == "Y" else "red"
            background_color = "#e0ffe0" if ts["appropriate"] == "Y" else "#ffe0e0"
            
            suggestion_html = f"""
            <div style="border: 2px solid {border_color}; background-color: {background_color}; padding: 10px; border-radius: 5px;">
                <p style="color: {text_color}" >你選了主題句:{selected_topic_sentence}</p>
                <p style="color: {text_color}">是否適當:{appropriate}</p>
                <p style="color: {text_color}">原因:{ts['reason']}</p>
            </div>
            """

            topic_sentence_input = ts["topic-sentence"] if ts["appropriate"] == "Y" else ""
            break

    gr_suggestion_html = gr.update(value=suggestion_html, visible=True)

    return topic_sentence_input, gr_suggestion_html

def generate_supporting_sentences(model, max_tokens, sys_content, scenario, eng_level, topic, points, topic_sentence, user_generate_supporting_sentences_prompt):
    """
    根据系统提示和用户输入的情境、主题、要点、主题句,调用OpenAI API生成相关的支持句。
    """
    user_content = f"""
        scenario is: {scenario}
        english level is: {eng_level}
        topic is: {topic}
        points is: {points}
        topic sentence is: {topic_sentence}
        ---
        {user_generate_supporting_sentences_prompt}
    """
    messages = [
        {"role": "system", "content": sys_content},
        {"role": "user", "content": user_content}
    ]

    request_payload = {
        "model": model,
        "messages": messages,
        "max_tokens": max_tokens,
    }

    try:
        response = OPEN_AI_CLIENT.chat.completions.create(**request_payload)
        content = response.choices[0].message.content.strip()
        gr_update = gr.update(choices=[content], visible=True)
    except Exception as e:
        print(f"An error occurred while generating supporting sentences: {e}")
        raise gr.Error("網路塞車,請重新嘗試一次!")

    return gr_update

def update_supporting_sentences_input(supporting_sentences_radio):
    return supporting_sentences_radio

def generate_conclusion_sentences(model, max_tokens, sys_content, scenario, eng_level, topic, points, topic_sentence, user_generate_conclusion_sentence_prompt):
    """
    根据系统提示和用户输入的情境、主题、要点、主题句,调用OpenAI API生成相关的结论句。
    """
    user_content = f"""
        scenario is: {scenario}
        english level is: {eng_level}
        topic is: {topic}
        points is: {points}
        topic sentence is: {topic_sentence}
        ---
        {user_generate_conclusion_sentence_prompt}
    """
    messages = [
        {"role": "system", "content": sys_content},
        {"role": "user", "content": user_content}
    ]

    request_payload = {
        "model": model,
        "messages": messages,
        "max_tokens": max_tokens,
        "response_format": { "type": "json_object" }
    }

    try:
        response = OPEN_AI_CLIENT.chat.completions.create(**request_payload)
        response_content = json.loads(response.choices[0].message.content)
        json_content = response_content["results"]
        gr_update = gr.update(choices=[json_content], visible=True)
    except Exception as e:
        print(f"An error occurred while generating conclusion sentences: {e}")
        raise gr.Error("網路塞車,請重新嘗試一次!")

    return gr_update

def update_conclusion_sentence_input(conclusion_sentence_radio):
    return conclusion_sentence_radio

def generate_paragraph(topic_sentence, supporting_sentences, conclusion_sentence):
    """
    根据用户输入的主题句、支持句、结论句,生成完整的段落。
    """
    paragraph = f"{topic_sentence} {supporting_sentences} {conclusion_sentence}"
    return paragraph

def generate_paragraph_evaluate(model, sys_content, paragraph, user_generate_paragraph_evaluate_prompt):
    """
    根据用户输入的段落,调用OpenAI API生成相关的段落分析。
    """
    user_content = f"""
        paragraph is: {paragraph}
        ---
        {user_generate_paragraph_evaluate_prompt}
    """
    messages = [
        {"role": "system", "content": sys_content},
        {"role": "user", "content": user_content}
    ]

    response_format = { "type": "json_object" }

    request_payload = {
        "model": model,
        "messages": messages,
        "max_tokens": 2000,
        "response_format": response_format
    }

    max_attempts = 2
    attempt = 0
    while attempt < max_attempts:
        try:
            response = OPEN_AI_CLIENT.chat.completions.create(**request_payload)
            content = response.choices[0].message.content

            print(f"====generate_paragraph_evaluate====")
            print(content)

            data = json.loads(content)
            table_data = [
                ["學測架構|內容(Content)", data['content']['level'], data['content']['explanation']],
                ["學測架構|組織(Organization)", data['organization']['level'], data['organization']['explanation']],
                ["學測架構|文法、句構(Grammar/Sentence Structure)", data['grammar_and_usage']['level'], data['grammar_and_usage']['explanation']],
                ["學測架構|字彙、拼字(Vocabulary/Spelling)", data['vocabulary']['level'], data['vocabulary']['explanation']],
                ["JUTOR 架構|連貫性和連接詞(Coherence and Cohesion)", data['coherence_and_cohesion']['level'], data['coherence_and_cohesion']['explanation']]
            ]
            headers = ["架構", "評分", "解釋"]
            gr_update = gr.update(value=table_data, headers=headers, visible=True)
            break
        except Exception as e:
            print(f"An error occurred while generating paragraph evaluate: {e}")
            attempt += 1
            if attempt == max_attempts:
                raise gr.Error("網路塞車,請重新嘗試一次!")

    return gr_update

def generate_correct_grammatical_spelling_errors(model, sys_content, eng_level, paragraph, user_correct_grammatical_spelling_errors_prompt):
    """
    根据用户输入的段落,调用OpenAI API生成相关的文法和拼字错误修正。
    """
    user_content = f"""
        level is: {eng_level}
        paragraph is: {paragraph}
        ---
        {user_correct_grammatical_spelling_errors_prompt}
    """
    messages = [
        {"role": "system", "content": sys_content},
        {"role": "user", "content": user_content}
    ]
    response_format = { "type": "json_object" }
    request_payload = {
        "model": model,
        "messages": messages,
        "max_tokens": 1000,
        "response_format": response_format
    }

    max_attempts = 2
    attempt = 0
    while attempt < max_attempts:
        try:
            response = OPEN_AI_CLIENT.chat.completions.create(**request_payload)
            content = response.choices[0].message.content
            data = json.loads(content)
            print(f"data: {data}")

            corrections_list = [
                [item['original'], item['correction'], item['explanation']]
                for item in data['Corrections and Explanations']
            ]
            headers = ["原文", "建議", "解釋"]

            corrections_list_gr_update = gr.update(value=corrections_list, headers=headers, wrap=True, visible=True)
            reverse_paragraph_gr_update = gr.update(value=data["Revised Paragraph"], visible=False)
            break
        except Exception as e:
            print(f"An error occurred while generating correct grammatical spelling errors: {e}")
            attempt += 1
            if attempt == max_attempts:
                raise gr.Error("網路塞車,請重新嘗試一次!")
    
    return corrections_list_gr_update, reverse_paragraph_gr_update

def highlight_diff_texts(highlight_list, text):
    # Convert DataFrame to JSON string
    highlight_list_json = highlight_list.to_json()

    # Print the JSON string to see its structure
    print("=======highlight_list_json=======")
    print(highlight_list_json)

    # Parse JSON string back to dictionary
    highlight_list_dict = json.loads(highlight_list_json)

    # Extract suggestions from the parsed JSON
    suggestions = [highlight_list_dict['建議'][str(i)] for i in range(len(highlight_list_dict['建議']))]

    # Initialize the HTML for text
    text_html = f"<p>{text}</p>"

    # Replace each suggestion in text with highlighted version
    for suggestion in suggestions:
        text_html = text_html.replace(suggestion, f'<span style="color:red;">{suggestion}</span>')

    return text_html

def update_paragraph_correct_grammatical_spelling_errors_input(paragraph):
    return paragraph

def generate_refine_paragraph(model, sys_content, eng_level, paragraph, user_refine_paragraph_prompt):
    """
    根据用户输入的段落,调用OpenAI API生成相关的段落改善建议。
    """
    user_content = f"""
        eng_level is: {eng_level}
        paragraph is: {paragraph}
        ---
        {user_refine_paragraph_prompt}
    """
    messages = [
        {"role": "system", "content": sys_content},
        {"role": "user", "content": user_content}
    ]

    response_format = { "type": "json_object" }

    request_payload = {
        "model": model,
        "messages": messages,
        "max_tokens": 4000,
        "response_format": response_format
    }

    max_attempts = 2
    attempt = 0
    while attempt < max_attempts:
        try:
            response = OPEN_AI_CLIENT.chat.completions.create(**request_payload)
            content = response.choices[0].message.content
            data = json.loads(content)
            headers = ["原文", "建議", "解釋"]
            table_data = [
                [item['origin'], item['suggestion'], item['explanation']]
                for item in data['Suggestions and Explanations']
            ]

            refine_paragraph_gr_update = gr.update(value=table_data, headers=headers, visible=True)
            revised_paragraph_gr_update = gr.update(value=data["Revised Paragraph"],visible=False)
            break
        except Exception as e:
            print(f"An error occurred while generating refine paragraph: {e}")
            attempt += 1
            if attempt == max_attempts:
                raise gr.Error("網路塞車,請重新嘗試一次!")

    return refine_paragraph_gr_update, revised_paragraph_gr_update

def update_paragraph_refine_input(text):
    return text

# 段落練習歷史紀錄
def generate_paragraph_history(
        user_data,
        session_timestamp,
        request_origin,
        scenario_input,
        topic_output,
        points_output,
        topic_sentence_input,
        supporting_sentences_input,
        conclusion_sentence_input,
        paragraph_output,
        paragraph_evaluate_output,
        correct_grammatical_spelling_errors_output_table,
        refine_output_table,
        refine_output
    ):
    """
    生成段落歷史紀錄
    """

    print("====生成段落歷史紀錄====")
    print(f"user_data: {user_data}")
    print(f"session_timestamp: {session_timestamp}")
    print(f"request_origin: {request_origin}")

    if user_data:
        encoded_user_id_url = urllib.parse.quote(user_data, safe='')
        log_type_name = "jutor_write_paragraph_practice"
        file_name = f"{encoded_user_id_url}/{log_type_name}/{session_timestamp}.json"
        content = {
            "session_timestamp": session_timestamp,
            "request_origin": request_origin,
            "scenario_input": scenario_input,
            "topic_output": topic_output,
            "points_output": points_output,
            "topic_sentence_input": topic_sentence_input,
            "supporting_sentences_input": supporting_sentences_input,
            "conclusion_sentence_input": conclusion_sentence_input,
            "paragraph_output": paragraph_output,
            "paragraph_evaluate_output": paragraph_evaluate_output.to_dict(orient='records'),
            "correct_grammatical_spelling_errors_output_table": correct_grammatical_spelling_errors_output_table.to_dict(orient='records'),
            "refine_output_table": refine_output_table.to_dict(orient='records'),
            "refine_output": refine_output
        }
        print(file_name)
        print(content)
        GCS_SERVICE.upload_json_string("jutor_logs", file_name, json.dumps(content))
    else:
        print("User data is empty.")

    return scenario_input, \
            topic_output, \
            points_output, \
            topic_sentence_input, \
            supporting_sentences_input, \
            conclusion_sentence_input, \
            paragraph_output, \
            paragraph_evaluate_output, \
            correct_grammatical_spelling_errors_output_table, \
            refine_output_table, \
            refine_output

def paragraph_save_and_tts(paragraph_text):
    """
    Saves the paragraph text and generates an audio file using OpenAI's TTS.
    """
    try:
        # Call OpenAI's TTS API to generate speech from text
        response = OPEN_AI_CLIENT.audio.speech.create(
            model="tts-1",
            voice="alloy",
            input=paragraph_text,
        )

        with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as temp_file:
            temp_file.write(response.content)

        # Get the file path of the temp file
        audio_path = temp_file.name

        # Return the path to the audio file along with the text
        return paragraph_text, audio_path

    except Exception as e:
        print(f"An error occurred while generating TTS: {e}")
        # Handle the error appropriately (e.g., return an error message or a default audio path)
        return paragraph_text, None

def update_history_accordion():
    history_accordion_gr_update = gr.update(open=True)
    return history_accordion_gr_update

def get_logs_sessions(user_data, log_type):
    if user_data and log_type:
        encoded_user_id_url = urllib.parse.quote(user_data, safe='')
        file_name_prefix = f"{encoded_user_id_url}/{log_type}"
        print(f"file_name_prefix: {file_name_prefix}")
        file_names = GCS_SERVICE.list_files("jutor_logs", file_name_prefix)
        print(f"file_names: {file_names}")
    else:
        file_names = []

    # file_names sort by timestamp DESC
    file_names.sort(reverse=True)
    choices = [
        (file_name.split("/")[-1].split(".")[0], file_name) for file_name in file_names
    ]

    paragraph_logs_session_list = gr.update(choices=choices, interactive=True, visible=True)

    return paragraph_logs_session_list

def get_paragraph_practice_log_session_content(file_name):
    if file_name:
        content = GCS_SERVICE.download_as_string("jutor_logs", file_name)
        print(f"content: {content}")
        content_json = json.loads(content)
        paragraph_log_topic_input_history = content_json["topic_output"]
        paragraph_log_points_input_history = content_json["points_output"]
        paragraph_log_topic_sentence_input_history = content_json["topic_sentence_input"]
        paragraph_log_supporting_sentences_input_history = content_json["supporting_sentences_input"]
        paragraph_log_conclusion_sentence_input_history = content_json["conclusion_sentence_input"]
        paragraph_log_paragraph_output_history = content_json["paragraph_output"]
        # to df
        paragraph_log_paragraph_evaluate_output_history = pd.DataFrame(content_json["paragraph_evaluate_output"])
        paragraph_log_correct_grammatical_spelling_errors_output_table_history = pd.DataFrame(content_json["correct_grammatical_spelling_errors_output_table"])
        paragraph_log_refine_output_table_history = pd.DataFrame(content_json["refine_output_table"])
        paragraph_log_refine_output_history = content_json["refine_output"]
        paragraph_log_paragraph_save_output = content_json["paragraph_output"]
    else:
        paragraph_log_topic_input_history = ""
        paragraph_log_points_input_history = ""
        paragraph_log_topic_sentence_input_history = ""
        paragraph_log_supporting_sentences_input_history = ""
        paragraph_log_conclusion_sentence_input_history = ""
        paragraph_log_paragraph_output_history = ""
        paragraph_log_paragraph_evaluate_output_history = pd.DataFrame()
        paragraph_log_correct_grammatical_spelling_errors_output_table_history = pd.DataFrame()
        paragraph_log_refine_output_table_history = pd.DataFrame()
        paragraph_log_refine_output_history = ""
        paragraph_log_paragraph_save_output = ""

    return paragraph_log_topic_input_history, \
            paragraph_log_points_input_history, \
            paragraph_log_topic_sentence_input_history, \
            paragraph_log_supporting_sentences_input_history, \
            paragraph_log_conclusion_sentence_input_history, \
            paragraph_log_paragraph_output_history, \
            paragraph_log_paragraph_evaluate_output_history, \
            paragraph_log_correct_grammatical_spelling_errors_output_table_history, \
            paragraph_log_refine_output_table_history, \
            paragraph_log_refine_output_history, \
            paragraph_log_paragraph_save_output

# 全文批改歷史紀錄
def generate_paragraph_evaluate_history(
        user_data,
        session_timestamp,
        request_origin,
        full_paragraph_input,
        full_paragraph_evaluate_output,
        full_paragraph_correct_grammatical_spelling_errors_input,
        full_paragraph_correct_grammatical_spelling_errors_output_table,
        full_paragraph_refine_input,
        full_paragraph_refine_output_table,
        full_paragraph_refine_output,
        full_paragraph_save_output
    ):

    print("====生成全文批改歷史紀錄====")
    print(f"user_data: {user_data}")
    print(f"session_timestamp: {session_timestamp}")
    print(f"request_origin: {request_origin}")

    if user_data:
        encoded_user_id_url = urllib.parse.quote(user_data, safe='')
        log_type_name = "jutor_write_full_paragraph_evaluation"
        file_name = f"{encoded_user_id_url}/{log_type_name}/{session_timestamp}.json"
        content = {
            "session_timestamp": session_timestamp,
            "request_origin": request_origin,
            "full_paragraph_input": full_paragraph_input,
            "full_paragraph_evaluate_output": full_paragraph_evaluate_output.to_dict(orient='records'),
            "full_paragraph_correct_grammatical_spelling_errors_input": full_paragraph_correct_grammatical_spelling_errors_input,
            "full_paragraph_correct_grammatical_spelling_errors_output_table": full_paragraph_correct_grammatical_spelling_errors_output_table.to_dict(orient='records'),
            "full_paragraph_refine_input": full_paragraph_refine_input,
            "full_paragraph_refine_output_table": full_paragraph_refine_output_table.to_dict(orient='records'),
            "full_paragraph_refine_output": full_paragraph_refine_output,
            "full_paragraph_save_output": full_paragraph_save_output
        }
        print(file_name)
        print(content)
        GCS_SERVICE.upload_json_string("jutor_logs", file_name, json.dumps(content))

    return full_paragraph_input, \
            full_paragraph_evaluate_output, \
            full_paragraph_correct_grammatical_spelling_errors_input, \
            full_paragraph_correct_grammatical_spelling_errors_output_table, \
            full_paragraph_refine_input, \
            full_paragraph_refine_output_table, \
            full_paragraph_refine_output, \
            full_paragraph_save_output

def get_full_paragraph_evaluate_log_session_content(file_name):
    if file_name:
        content = GCS_SERVICE.download_as_string("jutor_logs", file_name)
        print(f"content: {content}")
        content_json = json.loads(content)
        full_paragraph_input = content_json["full_paragraph_input"]
        full_paragraph_evaluate_output = pd.DataFrame(content_json["full_paragraph_evaluate_output"])
        full_paragraph_correct_grammatical_spelling_errors_input = content_json["full_paragraph_correct_grammatical_spelling_errors_input"]
        full_paragraph_correct_grammatical_spelling_errors_output_table = pd.DataFrame(content_json["full_paragraph_correct_grammatical_spelling_errors_output_table"])
        full_paragraph_refine_input = content_json["full_paragraph_refine_input"]
        full_paragraph_refine_output_table = pd.DataFrame(content_json["full_paragraph_refine_output_table"])
        full_paragraph_refine_output = content_json["full_paragraph_refine_output"]
        full_paragraph_save_output = content_json["full_paragraph_save_output"]
    else:
        full_paragraph_input = ""
        full_paragraph_evaluate_output = pd.DataFrame()
        full_paragraph_correct_grammatical_spelling_errors_input = ""
        full_paragraph_correct_grammatical_spelling_errors_output_table = pd.DataFrame()
        full_paragraph_refine_input = ""
        full_paragraph_refine_output_table = pd.DataFrame()
        full_paragraph_refine_output = ""
        full_paragraph_save_output = ""

    return full_paragraph_input, \
            full_paragraph_evaluate_output, \
            full_paragraph_correct_grammatical_spelling_errors_input, \
            full_paragraph_correct_grammatical_spelling_errors_output_table, \
            full_paragraph_refine_input, \
            full_paragraph_refine_output_table, \
            full_paragraph_refine_output, \
            full_paragraph_save_output


# # 考古題練習歷史紀錄
def generate_past_exam_history(
        user_data,
        session_timestamp,
        request_origin,
        past_exam_title,
        past_exam_evaluation_input,
        past_exam_evaluation_output,
        past_exam_correct_grammatical_spelling_errors_input,
        past_exam_correct_grammatical_spelling_errors_output_table,
        past_exam_refine_input,
        past_exam_refine_output_table,
        past_exam_refine_output,
        past_exam_save_output
    ):
    print("====生成考古題練習歷史紀錄====")
    print(f"user_data: {user_data}")
    print(f"session_timestamp: {session_timestamp}")
    print(f"request_origin: {request_origin}")

    if user_data:
        encoded_user_id_url = urllib.parse.quote(user_data, safe='')
        log_type_name = "jutor_write_past_exam"
        file_name = f"{encoded_user_id_url}/{log_type_name}/{session_timestamp}.json"
        content = {
            "session_timestamp": session_timestamp,
            "request_origin": request_origin,
            "past_exam_title": past_exam_title,
            "past_exam_evaluation_input": past_exam_evaluation_input,
            "past_exam_evaluation_output": past_exam_evaluation_output.to_dict(orient='records'),
            "past_exam_correct_grammatical_spelling_errors_input": past_exam_correct_grammatical_spelling_errors_input,
            "past_exam_correct_grammatical_spelling_errors_output_table": past_exam_correct_grammatical_spelling_errors_output_table.to_dict(orient='records'),
            "past_exam_refine_input": past_exam_refine_input,
            "past_exam_refine_output_table": past_exam_refine_output_table.to_dict(orient='records'),
            "past_exam_refine_output": past_exam_refine_output,
            "past_exam_save_output": past_exam_save_output
        }
        print(file_name)
        print(content)
        GCS_SERVICE.upload_json_string("jutor_logs", file_name, json.dumps(content))
    
    return past_exam_title, \
            past_exam_evaluation_input, \
            past_exam_evaluation_output, \
            past_exam_correct_grammatical_spelling_errors_input, \
            past_exam_correct_grammatical_spelling_errors_output_table, \
            past_exam_refine_input, \
            past_exam_refine_output_table, \
            past_exam_refine_output, \
            past_exam_save_output

def get_past_exam_practice_log_session_content(file_name):
    if file_name:
        content = GCS_SERVICE.download_as_string("jutor_logs", file_name)
        print(f"content: {content}")
        content_json = json.loads(content)
        past_exam_title = content_json["past_exam_title"]
        past_exam_evaluation_input = content_json["past_exam_evaluation_input"]
        past_exam_evaluation_output = pd.DataFrame(content_json["past_exam_evaluation_output"])
        past_exam_correct_grammatical_spelling_errors_input = content_json["past_exam_correct_grammatical_spelling_errors_input"]
        past_exam_correct_grammatical_spelling_errors_output_table = pd.DataFrame(content_json["past_exam_correct_grammatical_spelling_errors_output_table"])
        past_exam_refine_input = content_json["past_exam_refine_input"]
        past_exam_refine_output_table = pd.DataFrame(content_json["past_exam_refine_output_table"])
        past_exam_refine_output = content_json["past_exam_refine_output"]
        past_exam_save_output = content_json["past_exam_save_output"]
    else:
        past_exam_title = ""
        past_exam_evaluation_input = ""
        past_exam_evaluation_output = pd.DataFrame()
        past_exam_correct_grammatical_spelling_errors_input = ""
        past_exam_correct_grammatical_spelling_errors_output_table = pd.DataFrame()
        past_exam_refine_input = ""
        past_exam_refine_output_table = pd.DataFrame()
        past_exam_refine_output = ""
        past_exam_save_output = ""

    return past_exam_title, \
            past_exam_evaluation_input, \
            past_exam_evaluation_output, \
            past_exam_correct_grammatical_spelling_errors_input, \
            past_exam_correct_grammatical_spelling_errors_output_table, \
            past_exam_refine_input, \
            past_exam_refine_output_table, \
            past_exam_refine_output, \
            past_exam_save_output

# === Chinese ===
# def generate_chinese_evaluation_table(model, sys_content, user_prompt, text):
#     # https://www.ceec.edu.tw/files/file_pool/1/0j052575870800204600/1216%E5%9C%8B%E6%96%87%E4%BD%9C%E6%96%87%E5%88%86%E9%A0%85%E5%BC%8F%E8%A9%95%E5%88%86%E6%8C%87%E6%A8%99.pdf

#     user_content = f"""
#         本篇作文:{text}
#         ---
#         {user_prompt}
#     """
#     messages = [
#         {"role": "system", "content": sys_content},
#         {"role": "user", "content": user_content}
#     ]

#     response_format = { "type": "json_object" }

#     request_payload = {
#         "model": model,
#         "messages": messages,
#         "max_tokens": 2000,
#         "response_format": response_format
#     }

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

#     print(f"====generate_chinese_evaluation_table====")
#     print(content)

#     data = json.loads(content)["results"]
#     headers = ["架構", "評分", "解釋"]
#     table_data = [
#         ["主題與內容", data['主題與內容']['level'], data['主題與內容']['explanation']],
#         ["段落結構", data['段落結構']['level'], data['段落結構']['explanation']],
#         ["遣詞造句", data['遣詞造句']['level'], data['遣詞造句']['explanation']],
#         ["錯別字與標點符號", data['錯別字與標點符號']['level'], data['錯別字與標點符號']['explanation']]
#     ]
    
#     gr_update = gr.update(value=table_data, headers=headers)

#     return gr_update

def load_exam_data():
    with open("exams.json", "r") as file:
        data = json.load(file)
    return data

def update_exam_contents(selected_title):
    exams = load_exam_data()["exams"]
    for exam in exams:
        if exam["title"] == selected_title:
            return exam["title"], exam["question"], exam["hint"], exam["image_url"]

def generate_chinese_paragraph_practice_history(
    user_data,
    session_timestamp,
    request_origin,
    chinese_full_paragraph_input,
    chinese_full_paragraph_evaluate_output_text,
    chinese_full_paragraph_evaluate_output_table,
    chinese_full_paragraph_refine_input,
    chinese_full_paragraph_refine_output_text,
    chinese_full_paragraph_refine_output_table,
    chinese_full_paragraph_save_output
):
    if user_data:
        encoded_user_id_url = urllib.parse.quote(user_data, safe='')
        log_type_name = "jutor_write_chinese_full_paragraph_evaluation"
        file_name = f"{encoded_user_id_url}/{log_type_name}/{session_timestamp}.json"
        content = {
            "session_timestamp": session_timestamp,
            "request_origin": request_origin,
            "chinese_full_paragraph_input": chinese_full_paragraph_input,
            "chinese_full_paragraph_evaluate_output_text": chinese_full_paragraph_evaluate_output_text,
            "chinese_full_paragraph_evaluate_output_table": chinese_full_paragraph_evaluate_output_table.to_dict(orient='records'),
            "chinese_full_paragraph_refine_input": chinese_full_paragraph_refine_input,
            "chinese_full_paragraph_refine_output_text": chinese_full_paragraph_refine_output_text,
            "chinese_full_paragraph_refine_output_table": chinese_full_paragraph_refine_output_table.to_dict(orient='records'),
            "chinese_full_paragraph_save_output": chinese_full_paragraph_save_output
        }
        GCS_SERVICE.upload_json_string("jutor_logs", file_name, json.dumps(content))

    return chinese_full_paragraph_input, \
            chinese_full_paragraph_evaluate_output_text, \
            chinese_full_paragraph_evaluate_output_table, \
            chinese_full_paragraph_refine_input, \
            chinese_full_paragraph_refine_output_text, \
            chinese_full_paragraph_refine_output_table, \
            chinese_full_paragraph_save_output

def get_chinese_paragraph_practice_log_session_content(file_name):
    if file_name:
        content = GCS_SERVICE.download_as_string("jutor_logs", file_name)
        print(f"content: {content}")
        content_json = json.loads(content)
        chinese_full_paragraph_input_history = content_json["chinese_full_paragraph_input"]
        chinese_full_paragraph_evaluate_output_text_history = content_json["chinese_full_paragraph_evaluate_output_text"] if "chinese_full_paragraph_evaluate_output_text" in content_json else ""
        chinese_full_paragraph_evaluate_output_table_history = pd.DataFrame(content_json["chinese_full_paragraph_evaluate_output_table"])
        chinese_full_paragraph_refine_input_history = content_json["chinese_full_paragraph_refine_input"]
        chinese_full_paragraph_refine_output_text_history = content_json["chinese_full_paragraph_refine_output_text"]
        chinese_full_paragraph_refine_output_table_history = pd.DataFrame(content_json["chinese_full_paragraph_refine_output_table"])
        chinese_full_paragraph_save_output_history = content_json["chinese_full_paragraph_save_output"]
    else:
        chinese_full_paragraph_input_history = ""
        chinese_full_paragraph_evaluate_output_text_history = ""
        chinese_full_paragraph_evaluate_output_table_history = pd.DataFrame()
        chinese_full_paragraph_refine_input_history = ""
        chinese_full_paragraph_refine_output_text_history = ""
        chinese_full_paragraph_refine_output_table_history = pd.DataFrame()
        chinese_full_paragraph_save_output_history = ""

    return chinese_full_paragraph_input_history, \
            chinese_full_paragraph_evaluate_output_text_history, \
            chinese_full_paragraph_evaluate_output_table_history, \
            chinese_full_paragraph_refine_input_history, \
            chinese_full_paragraph_refine_output_text_history, \
            chinese_full_paragraph_refine_output_table_history, \
            chinese_full_paragraph_save_output_history


# === OpenAI Assistant ===
def verify_string_length(text):
    if len(text) > 2000:
        raise gr.Error("輸入的文字長度過長,請重新輸入!")

def verify_moderation(text):
    response = OPEN_AI_MODERATION_CLIENT.moderations.create(input=text)
    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==========")

    if is_flagged:
        raise gr.Error("您的輸入包含不當內容,請重新輸入!")

    return is_flagged, response_dict

def get_chinese_paragraph_evaluate_content(model, sys_content, paragraph, user_generate_paragraph_evaluate_prompt):
    verify_string_length(paragraph)
    verify_moderation(paragraph)

    user_content = f"""
        sys_content: {sys_content}
        ---
        paragraph is: {paragraph}
        ---
        {user_generate_paragraph_evaluate_prompt}
    """
    content = generate_content_by_open_ai_assistant(user_content, thread_id=None, model_name=model)
    print(f"====generate_paragraph_evaluate====")
    print(content)

    content_list = content.split("```json")
    content_text = content_list[0]
    print(f"content_text: {content_text}")
    content_json = content_list[1].replace("```", "")
    print(f"content_json: {content_json}")

    data = json.loads(content_json)["results"]
    headers = ["架構", "評分", "解釋"]
    table_data = [
        ["主題與內容", data['主題與內容']['level'], data['主題與內容']['explanation']],
        ["段落結構", data['段落結構']['level'], data['段落結構']['explanation']],
        ["遣詞造句", data['遣詞造句']['level'], data['遣詞造句']['explanation']],
        ["錯別字與標點符號", data['錯別字與標點符號']['level'], data['錯別字與標點符號']['explanation']]
    ]
    
    content_table = gr.update(value=table_data, headers=headers, visible=True)

    return content_text, content_table

def get_chinese_paragraph_refine_evaluate_content(model, sys_content, paragraph_1, paragraph_2, user_refine_paragraph_prompt):
    verify_string_length(paragraph_1)
    verify_string_length(paragraph_2)
    verify_moderation(paragraph_1+paragraph_2)

    user_content = f"""
        sys_content: {sys_content}
        ---
        original paragraph is: {paragraph_1}
        ---
        refined paragraph is: {paragraph_2}
        ---
        {user_refine_paragraph_prompt}
    """
    content = generate_content_by_open_ai_assistant(user_content, thread_id=None, model_name=model)
    print(f"====generate_paragraph_evaluate====")
    print(content)

    content_list = content.split("```json")
    content_text = content_list[0]
    print(f"content_text: {content_text}")
    content_json = content_list[1].replace("```", "")
    print(f"content_json: {content_json}")

    data = json.loads(content_json)["results"]
    headers = ["架構", "評分", "解釋"]
    table_data = [
        ["主題與內容", data['主題與內容']['level'], data['主題與內容']['explanation']],
        ["段落結構", data['段落結構']['level'], data['段落結構']['explanation']],
        ["遣詞造句", data['遣詞造句']['level'], data['遣詞造句']['explanation']],
        ["錯別字與標點符號", data['錯別字與標點符號']['level'], data['錯別字與標點符號']['explanation']]
    ]
    
    gr_update = gr.update(value=table_data, headers=headers, visible=True)

    return content_text, gr_update

def generate_content_by_open_ai_assistant(user_content, thread_id=None, model_name=None):
    verify_moderation(user_content)

    client = CUTOR_OPEN_AI_CLIENT
    assistant_id = CUTOR_OPEN_AI_ASSISTANT_ID

    assistant = client.beta.assistants.update(
        assistant_id=assistant_id,
        tools=[{"type": "file_search"}], 
    )
    print(f"My assistant: {assistant}")
    print(f"instructions: {assistant.instructions}")

    try:
        if not thread_id:
            thread = client.beta.threads.create()
            thread_id = thread.id
        else:
            thread = client.beta.threads.retrieve(thread_id)

        print(f"Thread ID: {thread.id}")

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

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

        # Run the assistant
        print("==============Run the assistant====================")
        run = client.beta.threads.runs.create_and_poll(
            thread_id=thread.id, 
            assistant_id=assistant.id,
            tools=[{"type": "file_search"}],
        )
        
        if run.status == "completed":
            print("==============completed====================")
            print(f"Thread ID: {thread.id}")
            messages = client.beta.threads.messages.list(thread_id=thread.id)
            print(f"Messages: {messages}")
            response = messages
            response_text = messages.data[0].content[0].text.value
            print(f"Response: {response_text}")
    except Exception as e:
        print(f"An error occurred while generating content by OpenAI Assistant: {e}")
        raise gr.Error("網路塞車,請重新嘗試一次!")

    return response_text

# 小工具
def show_elements():
    return gr.update(visible=True)

def hide_elements():
    return gr.update(visible=False)

def duplicate_element(element):
    return element

def generate_chinese_essay_idea(model, user_prompt, chinese_essay_title_input):
    verify_moderation(chinese_essay_title_input)

    sys_content = "你是一位老師,正在和我一起練習提高我的寫作技能。 給予的回覆不超過 500字。 用 Markdown 語法回答。"
    user_content = f"""
        {user_prompt}
        ---
        題目:{chinese_essay_title_input}
    """
    messages = [
        {"role": "system", "content": sys_content},
        {"role": "user", "content": user_content}
    ]

    request_payload = {
        "model": model,
        "messages": messages,
        "max_tokens": 2000,
    }

    try:
        response = OPEN_AI_CLIENT.chat.completions.create(**request_payload)
        content = response.choices[0].message.content.strip()
    except Exception as e:
        print(f"An error occurred while generating Chinese essay idea: {e}")
        raise gr.Error("網路塞車,請重新嘗試一次!")

    return content

# Download doc
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_content(content):
    word_path = create_word(content)
    return word_path


# === INIT PARAMS ===
def init_params(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)
        
        admin_group = gr.update(visible=False)
        english_group = gr.update(visible=True)
        chinese_group = gr.update(visible=True)

        # check if origin is from junyiacademy
        query_params = dict(request.query_params)
        request_origin = request.headers.get("origin", "").replace("https://", "").replace("http://", "")
        print(f"request_origin: {request_origin}")
        allowed_request_origins = [
            "junyiacademy.org", 
            "junyiacademy.appspot.com", 
            "colearn30.com", # 樂寫網
            "hf.space",
        ]
        if any(allowed_origin in request_origin for allowed_origin in allowed_request_origins) or is_env_local:
            pass
        else:
            raise gr.Error("Invalid origin")
        
        # admin_group visible in local
        if is_env_local:
            admin_group = gr.update(visible=True)

        # session timestamp 用 2024-01-01-12-00-00 格式, 要用 UTC+8 時間
        session_timestamp = datetime.now(pytz.utc).astimezone(pytz.timezone('Asia/Taipei')).strftime("%Y-%m-%d-%H-%M-%S")

        if "language" in query_params:
            if query_params["language"] == "english":
                print(f"language: english")
                english_group = gr.update(visible=True)
                chinese_group = gr.update(visible=False)
            elif query_params["language"] == "chinese":
                print(f"language: chinese")
                english_group = gr.update(visible=False)
                chinese_group = gr.update(visible=True)

        assignment_id = None
        if "assignment" in query_params:
            assignment_id = query_params["assignment"]
        
        assignment_id_input = gr.update(value=assignment_id)

        
    return admin_group, session_timestamp, request_origin, assignment_id_input, english_group, chinese_group

CSS = """
    .accordion-prompts {
        background-color: orange;
    }
"""

english_grapragh_practice_button_js = """
    function english_grapragh_practice_button_click() {
        document.getElementById("english_grapragh_practice_row").style.display = "block";
        document.getElementById("english_grapragh_evaluate_row").style.display = "none";
        document.getElementById("english_exam_practice_row").style.display = "none";
        document.getElementById("english_logs_row").style.display = "none";
        document.getElementById("english_grapragh_practice_button").classList.add("primary");
        document.getElementById("english_grapragh_evaluate_button").classList.remove("primary");
        document.getElementById("english_exam_practice_tab_button").classList.remove("primary");
        document.getElementById("english_logs_tab_button").classList.remove("primary");

        return true;
    }
"""

english_grapragh_evaluate_button_js = """
    function english_grapragh_evaluate_button_click() {
        document.getElementById("english_grapragh_practice_row").style.display = "none";
        document.getElementById("english_grapragh_evaluate_row").style.display = "block";
        document.getElementById("english_exam_practice_row").style.display = "none";
        document.getElementById("english_logs_row").style.display = "none";
        document.getElementById("english_grapragh_practice_button").classList.remove("primary");
        document.getElementById("english_grapragh_evaluate_button").classList.add("primary");
        document.getElementById("english_exam_practice_tab_button").classList.remove("primary");
        document.getElementById("english_logs_tab_button").classList.remove("primary");
    
        return true;
    }
"""

english_exam_practice_tab_button_js = """
    function english_exam_practice_tab_button_click() {
        document.getElementById("english_grapragh_practice_row").style.display = "none";
        document.getElementById("english_grapragh_evaluate_row").style.display = "none";
        document.getElementById("english_exam_practice_row").style.display = "block";
        document.getElementById("english_logs_row").style.display = "none";
        document.getElementById("english_grapragh_practice_button").classList.remove("primary");
        document.getElementById("english_grapragh_evaluate_button").classList.remove("primary");
        document.getElementById("english_exam_practice_tab_button").classList.add("primary");
        document.getElementById("english_logs_tab_button").classList.remove("primary");

        return true;
    }
"""

english_logs_tab_button_js = """
    function english_logs_tab_button_click() {
        document.getElementById("english_grapragh_practice_row").style.display = "none";
        document.getElementById("english_grapragh_evaluate_row").style.display = "none";
        document.getElementById("english_exam_practice_row").style.display = "none";
        document.getElementById("english_logs_row").style.display = "block";
        document.getElementById("english_grapragh_practice_button").classList.remove("primary");
        document.getElementById("english_grapragh_evaluate_button").classList.remove("primary");
        document.getElementById("english_exam_practice_tab_button").classList.remove("primary");
        document.getElementById("english_logs_tab_button").classList.add("primary");

        return true;
    }
"""
THEME = gr.themes.Glass(primary_hue=gr.themes.colors.blue, secondary_hue=gr.themes.colors.orange).set(
    button_primary_background_fill="*primary_300",
    button_shadow="*block_shadow",
    button_shadow_hover="*block_shadow"
)

with gr.Blocks(theme=THEME, css=CSS) as demo:

    with gr.Row(visible=False) as admin_group:
        user_data = gr.Textbox(label="User Data", value="", elem_id="jutor_user_data_input")
        session_timestamp = gr.Textbox(label="Session Timestamp", value="", elem_id="jutor_session_timestamp_input")
        request_origin = gr.Textbox(label="Request Domain", value="")
        assignment_id_input = gr.Textbox(label="Assignment ID", value="", elem_id="jutor_assignment_id_input")

    with gr.Row(visible=False) as english_group:
        with gr.Column():
            with gr.Row() as page_title_english:
                with gr.Column():
                    with gr.Row():
                        with gr.Column():
                            gr.Markdown("# 🔮 JUTOR 英文段落寫作練習")
                        with gr.Column():
                            gr.HTML("""
                                <span style="text-align: center;">
                                    <a href="https://www.facebook.com/groups/jutor" target="_blank" style=" font-size: 14px; color="blue";> 🇫 加入 Facebook 討論社團</a>
                                </span>
                            """)
                    with gr.Row():
                        with gr.Column():
                            english_grapragh_practice_button = gr.Button("📝 英文段落寫作練習", variant="primary", elem_id="english_grapragh_practice_button")
                        with gr.Column():
                            english_grapragh_evaluate_button = gr.Button("📊 英文段落寫作評分", variant="", elem_id="english_grapragh_evaluate_button")
                        with gr.Column():
                            english_exam_practice_tab_button = gr.Button("🎯 英文考古題寫作練習", variant="", elem_id="english_exam_practice_tab_button")
                        with gr.Column():
                            english_logs_tab_button = gr.Button("📚 歷程回顧", variant="", elem_id="english_logs_tab_button")
            # ===== 英文段落寫作練習 =====
            with gr.Row(visible=True, elem_id="english_grapragh_practice_row") as english_grapragh_practice_row:
                with gr.Column():
                    with gr.Row():
                        gr.Markdown("# 📝 英文段落寫作練習")
                    with gr.Row():
                        with gr.Column():
                            gr.Image(value="https://storage.googleapis.com/jutor/Jutor%E6%AE%B5%E8%90%BD%20banner.jpg", show_label=False, show_download_button=False)
                        with gr.Column():
                            with gr.Accordion("📝 為什麼要學英文寫作架構?學測英文作文評分標準的啟示", open=False):
                                gr.Markdown("""
                                    ### 我們相信學習英文段落寫作基礎架構,必能幫助你在學測英文作文的內容、結構項目有好的表現。目前「大學學科能力測驗」的英文作文項目要求考生寫兩個段落,如果能書寫有清晰組織架構、強而有力的段落,你必然能在競爭激烈的環境中脫穎而出。
                                    ### 學測英文作文評分標準在內容、組織兩項目(計10分)的要求:「開頭、發展、結尾、主題清楚,相關細節支持、連貫一致、轉承語」。因此,「JUTOR 英文段落寫作平台」將幫助你從主題句「開頭」,然後「發展」支持句,最後「結尾」寫結論句。藉由基礎架構:讓「主題」清楚,具有「相關細節支持」,確保作文「連貫一致」,並在最後輔助正確使用「轉承語」。
                                    ### 此外,由於英文段落是一切英文寫作的基礎,成功駕馭段落是掌握不同形式英文寫作的關鍵,諸如語言能力測驗、郵件、部落格貼文、報告、論文等。然而英文段落有其特殊的架構與表達方式,與中文大不相同。你如果使用 ChatGPT 將中文文章翻譯成英文,你會發現 ChatGPT 會按照英文慣例,先在中文文章中找尋「主題句」並移至段落開頭處,顯現中、英文段落寫作的明顯差異。
                                    ### 我們創建這個平台旨在為你提供一個良好的學習環境,通過啟發和挑戰,幫助你逐步提升英文段落寫作的技能。無論初學者還是有一定經驗的寫作者,我們都盡力為你提供所需的學習資源,助你突破學習瓶頸。
                                    ### 謝謝你選擇使用我們的平台,讓我們攜手前行,一起開始這段寫作之旅吧!Cheers!
                                """)
                            with gr.Accordion("📝 英文作文跟中文作文的差異?", open=False):
                                gr.Image(value="https://storage.googleapis.com/jutor/jutor_en_chinese.jpg", show_label=False, show_download_button=False)

                    # ===== 基礎級使用者 =====
                    with gr.Row(visible=False) as default_params:
                        model = gr.Radio(["gpt-4o", "gpt-4-turbo"], label="Model", value="gpt-4o")
                        max_tokens = gr.Slider(minimum=50, maximum=4000, value=4000, label="Max Tokens")
                        sys_content_input = gr.Textbox(label="System Prompt", value="You are an English teacher who is practicing with me to improve my English writing skill.")
                    with gr.Row():
                        eng_level_input = gr.Radio([("初學", "beginner"), ("進階", "advanced")], label="English Level", value="beginner")

                    # basic inputs 主題與情境
                    with gr.Group():
                        with gr.Row(visible=False) as scenario_params:
                            with gr.Column():
                                
                                with gr.Row():
                                    gr.Markdown("# Step 1. 你今天想練習寫什麼呢?")
                                with gr.Row():
                                    gr.Markdown("""## 寫作的主題與讀者、寫作的目的、文章的風格、長度、範圍、以及作者的專業知識等都有關係。因為不容易找主題,所以利用兩階段方式來找主題。特為較無英文寫作經驗的  基礎級使用者 提供多種大範圍情境,待篩選情境後,下一步再來決定明確的主題。""")
                                with gr.Row():
                                    with gr.Column():
                                        scenario_input = gr.Textbox(label="先選擇一個大範圍的情境或是自定義:")
                                    with gr.Column():
                                        scenario_values = [
                                            "Health",
                                            "Thanksgiving",
                                            "Halloween",
                                            "moon festival in Taiwan",
                                            "School and Learning",
                                            "Travel and Places",
                                            "Family and Friends",
                                            "Hobbies and Leisure Activities",
                                            "Health and Exercise",
                                            "Personal Experiences",
                                            "My Future Goals",
                                            "School Life",
                                            "Pets",
                                            "A Problem and Solution",
                                            "Holidays and Celebrations",
                                            "My Favorite Cartoon/Anime"
                                        ]
                                        scenario_radio_button = gr.Radio(scenario_values, label="Scenario", elem_id="scenario_button")

                                        scenario_radio_button.select(
                                            fn=update_scenario_input,
                                            inputs=[scenario_radio_button],
                                            outputs=[scenario_input]
                                        )

                    # Step 1. 確定段落主題
                    with gr.Row():
                        with gr.Column():      
                            with gr.Row():
                                gr.Markdown("# Step 1. 確定段落主題")
                            with gr.Row():
                                with gr.Column():
                                    gr.Markdown("""## 主題是整個段落要探討、闡述的主要議題。確定主題對於段落的架構、內容非常重要。""")
                                # with gr.Column():
                                #     with gr.Accordion("參考指引:情境與主題如何搭配呢?", open=False):
                                #         gr.Markdown("""
                                #         例如,情境是 `School & Learning` ,你可以依照自己的興趣、背景及經驗,決定合適的主題,像是:`My First Day at School` 或 `The Role of Internet in Learning`
                                #         例如,情境是 `Climate Change`,相關主題可能是 `Global Warming` 或 `Extreme Weather Events`
                                #     """)
                            with gr.Row(visible=False) as topic_params:
                                default_generate_topics_prompt = """
                                    The topic is the main issue that the entire paragraph aims to discuss and elaborate on. 
                                    Determining the topic is crucial for the structure and content of the paragraph.
                                    For example, if the context is School & Learning, you can decide on an appropriate topic based on your interests, background, and experiences, such as My First Day at School or The Role of the Internet in Learning. 
                                    If the context is Climate Change, related topics could be Global Warming or Extreme Weather Events.

                                    Give me 10 randon topics, 
                                    for a paragraph. Just the topics, no explanation, use English language base on  eng_level. 
                                    Make sure the vocabulary you use is at eng_level.
                                    output use JSON 
                                    EXAMPLE:
                                    "topics":["topic1", "topic2", "topic3", "topic4", "topic5", "topic6", "topic7", "topic8", "topic9", "topic10"]
                                """
                                user_generate_topics_prompt = gr.Textbox(label="Topics Prompt", value=default_generate_topics_prompt, visible=False)
                            with gr.Row():
                                with gr.Column():
                                    topic_input = gr.Textbox(label="自訂主題")
                                with gr.Column():
                                    generate_topics_button = gr.Button("✨ JUTOR 隨機產出 10 個段落主題,挑選一個來練習吧!", variant="primary")
                                    topic_output = gr.Radio(label="AI 產出主題", visible=False, interactive=True)
                                        
                                    generate_topics_button.click(
                                        fn=show_elements,
                                        inputs=[],
                                        outputs=[topic_output]
                                    ).then(
                                        fn=generate_topics,
                                        inputs=[
                                            model, 
                                            max_tokens, 
                                            sys_content_input, 
                                            scenario_input, 
                                            eng_level_input,
                                            user_generate_topics_prompt
                                        ],
                                        outputs=[topic_output]
                                    )

                                    topic_output.select(
                                        fn=update_topic_input,
                                        inputs=[topic_output],
                                        outputs=[topic_input]
                                    )

                    
                    # Step 2. 寫出關鍵字
                    with gr.Row():
                        with gr.Column():
                            with gr.Row() as points_params:
                                default_generate_points_prompt = """
                                    Based on the topic and eng_level setting, think about the direction and content of the paragraph, then present it using some related points/keywords. 
                                    For example, the topic: "The Benefits of Learning a Second Language." The direction and content: Learning a second language, such as Japanese, allows you to communicate with Japanese people and understand Japanese culture. 
                                    Therefore, the points/keywords are "Improving communication skills" and "Understanding other cultures." ....
                                    Please provide main points to develop in a paragraph about topic in the context of scenario, 
                                    use simple English language and make sure the vocabulary you use is at eng_level.
                                    No more explanation either no developing these points into a simple paragraph.
                                    Output use JSON format
                                    EXAMPLE:
                                    "points":["point1", "point2", "point3"]
                                """  
                                user_generate_points_prompt = gr.Textbox(label="Points Prompt", value=default_generate_points_prompt, visible=False)
                            with gr.Row() as points_html:
                                gr.Markdown("# Step 2. 找要點/關鍵字")
                            with gr.Row():
                                with gr.Column():
                                    with gr.Row():
                                        gr.Markdown("## 根據主題,思考段落的方向及內容,然後用兩個要點/關鍵字來呈現。例如主題:\"The Benefits of Learning a Second Language\" 「學習第二種語言的好處」,內容及方向:因為學習第二種語言,例如日語,就可以和日本人溝通,進而學習瞭解日本文化,因而要點/關鍵字就是 \"Improving communication skills\" 「提升溝通能力」及 \"Understanding other cultures\" 「瞭解其他文化」。")
                                    with gr.Row():
                                        gr.Markdown("## 如果不知道要寫什麼,也可以讓Jutor提供要點/關鍵字,以兩個要點/關鍵字為限。")
                                with gr.Column():
                                    with gr.Row():
                                        with gr.Accordion("📝 參考指引:要點/關鍵字的重要性?", open=False):
                                            gr.Markdown("""
                                                ### 寫段落時先決定要點/關鍵字很重要,因為這能確保段落內容連貫一致。
                                                1. 保持主題一致: 確定要點可以幫助作者集中在主題上,不會偏離主題,使段落更有一致性。
                                                2. 提高清晰度: 明確的要點能幫助讀者迅速理解段落的主旨,避免混淆。
                                                3. 組織結構: 有明確的要點,作者可以更容易組織自己的想法,使段落結構清晰、有邏輯。
                                                4. 省時省力: 先決定要點可以減少修改和重寫的次數,提高寫作效率。
                                            """)
                            with gr.Row():
                                with gr.Column():
                                    points_input = gr.Textbox(label="寫出要點/關鍵字")
                                with gr.Column():
                                    generate_points_button = gr.Button("✨ 找尋靈感?使用 JUTOR 產生要點/關鍵字", variant="primary")
                                    points_output = gr.Radio(label="AI 產出要點/關鍵字", visible=False, interactive=True)                        
                                    generate_points_button.click(
                                        fn=show_elements,
                                        inputs=[],
                                        outputs=[points_output]
                                    ).then(
                                        fn=generate_points,
                                        inputs=[
                                            model, 
                                            max_tokens, 
                                            sys_content_input, 
                                            scenario_input, 
                                            eng_level_input,
                                            topic_input,
                                            user_generate_points_prompt
                                        ],
                                        outputs=points_output
                                    )
                                    
                                    points_output.select(
                                        fn=update_points_input,
                                        inputs=[points_output],
                                        outputs=[points_input]
                                    )
                    
                    # Step 3. 選定主題句
                    with gr.Row():
                        with gr.Column():
                            with gr.Row() as topic_sentences_params:
                                default_generate_topic_sentences_prompt = """
                                    Please provide one appropriate topic sentence that aptly introduces the subject for the given scenario and topic. 
                                    Additionally, provide two topic sentences that, while related to the topic, 
                                    would be considered inappropriate or less effective for the specified context. 
                                    Those sentences must include the three main points:". 
                                    Use English language and each sentence should not be too long.
                                    For each sentence, explain the reason in Traditional Chinese, Taiwan, 繁體中文 zh-TW. 
                                    Make sure the vocabulary you use is at level.

                                    Output use JSON format

                                    EXAMPLE:
                                    "results": 
                                        [
                                            {{ "topic-sentence": "#","appropriate": "Y/N", "reason": "#中文解釋" }} , 
                                            {{ "topic-sentence": "#","appropriate": "Y/N", "reason": "#中文解釋" }},
                                            {{ "topic-sentence": "#","appropriate": "Y/N", "reason": "#中文解釋" }}
                                        ]       
                                """
                                user_generate_topic_sentences_prompt = gr.Textbox(label="Topic Sentences Prompt", value=default_generate_topic_sentences_prompt, visible=False)

                            with gr.Row() as topic_sentences_html:    
                                gr.Markdown("# Step 3. 寫主題句")
                            with gr.Row():      
                                with gr.Column():
                                    gr.Markdown("## 主題句(Topic Sentence)通常位於段落的開頭,幫助讀者迅速理解段落的內容。是段落中最重要的句子,介紹主題並含括段落的所有要點/關鍵字。")
                                    gr.Markdown("## 書寫段落時,必須確保每個句子都支持和闡述主題句,避免引入無關或偏離主題的討論,否則就會影響段落的架構及內容的一致性及連貫性。")
                                with gr.Column():
                                    with gr.Accordion("📝 參考指引:主題句樣例", open=False):
                                        gr.Markdown("""
                                            ### 主題句應該清晰、具體、明確,讓讀者一眼就能明白段落的內容及方向。

                                            - ✅ 合適的主題句:
                                                - Learning a second language improves communication skills and helps you understand other cultures better.
                                                - `Benefits of learning a second language` 是主題, `improving communication skills和 understanding other cultures` 則是兩個要點/關鍵字。

                                            - ❌ 不合適的主題句:
                                                - 樣例1:Reading is important.
                                                    - 解釋: 主題句過於籠統,應具體說明讀書重要性或影響。
                                                    - 改寫: Reading helps improve our thinking, making it a very important habit.
                                                - 樣例2:Today is a sunny day.
                                                    - 解釋: 主題句缺乏主要論點,無法指引段落內容。
                                                    - 改寫: The sunny weather today is perfect for outdoor activities.
                                                - 樣例3:I watched a movie yesterday.
                                                    - 解釋: 主題句不夠具體也缺乏深度,應介紹電影內容或觀後感。
                                                    - 改寫: Yesterday, I watched an interesting movie that made me think about human relationships.
                                                - 樣例4:There are many restaurants in this city.
                                                    - 解釋: 主題句過於籠統,應具體說明餐廳的特色或影響。
                                                    - 改寫: This city has many different restaurants, each offering unique food to attract different customers.
                                                    """)
                            with gr.Row():
                                with gr.Column():
                                    with gr.Row():
                                        topic_sentence_input = gr.Textbox(label="根據主題、要點/關鍵字來寫主題句")
                                    with gr.Row():
                                        default_generate_topic_sentence_input_feedback_prompt = """
                                            Rules:
                                            - 主題句(Topic Sentence)通常位於段落的開頭,幫助讀者迅速理解段落的內容。是段落中最重要的句子,介紹主題(topic)並含括段落的所有要點/關鍵字(points)。
                                            - 例如:"Learning a second language improves communication skills and helps you understand other cultures better." "The Benefits of Learning a second language"是主題, "improving communication skills" 和 "understanding other cultures" 則是兩個要點/關鍵字。
                                            - 書寫段落時,必須確保每個句子都支持和闡述主題句,避免引入無關或偏離主題的討論,否則就會影響段落的架構及內容的一致性及連貫性。
                                            
                                            Please check my written topic sentence, it should introduces the subject for the given topic and points and follow the rules.
                                            using Zh-TW to explain the reason. 
                                            please don't give any correct topic sentence as an example in the feedback.

                                            EXAMPLE:
                                            - 主題: "My Favorite Animal"
                                            - 要點/關鍵字: "Dogs are friendly," 
                                            - 你寫的主題句: {{xxxxxx}}
                                            
                                            - 分析結果:✅ 主題句合適/ ❌ 主題句並不合適 
                                            - 解釋: {{中文解釋}}
                                        """
                                        user_generate_topic_sentence_input_feedback_prompt = gr.Textbox(label="Feedback Prompt", value=default_generate_topic_sentence_input_feedback_prompt, visible=False)
                                        topic_sentence_input_feedback_button = gr.Button("✨ 提交主題句,獲得反饋", variant="primary")
                                    with gr.Row():
                                        topic_sentence_input_feedback_text = gr.Textbox(label="Feedback")

                                    topic_sentence_input_feedback_button.click(
                                        fn=generate_topic_sentence_feedback,
                                        inputs=[
                                            model, 
                                            max_tokens, 
                                            sys_content_input, 
                                            scenario_input, 
                                            eng_level_input,
                                            topic_input,
                                            points_input,
                                            topic_sentence_input,
                                            user_generate_topic_sentence_input_feedback_prompt
                                        ],
                                        outputs=[topic_sentence_input_feedback_text]
                                    )
                                with gr.Column():
                                    generate_topic_sentences_button = gr.Button("✨ JUTOR 產出三個主題句,選出一個最合適的", variant="primary")
                                    topic_sentence_output_json = gr.JSON(label="AI 產出主題句", visible=False)
                                    topic_sentence_output_radio = gr.Radio(label="AI 產出主題句", interactive=True, visible=False)
                                    topic_sentences_suggestions = gr.HTML(visible=False)
                                    
                                    generate_topic_sentences_button.click(
                                        fn=show_elements,
                                        inputs=[],
                                        outputs=[topic_sentence_output_radio]
                                    ).then(
                                        fn=hide_elements,
                                        inputs=[],
                                        outputs=[topic_sentences_suggestions]
                                    ).then(
                                        fn=generate_topic_sentences,
                                        inputs=[
                                            model, 
                                            max_tokens, 
                                            sys_content_input, 
                                            scenario_input, 
                                            eng_level_input,
                                            topic_input,
                                            points_input,
                                            user_generate_topic_sentences_prompt
                                        ],
                                        outputs=[topic_sentence_output_json, topic_sentence_output_radio]
                                    )

                                    topic_sentence_output_radio.select(
                                        fn=update_topic_sentence_input, 
                                        inputs=[topic_sentence_output_json, topic_sentence_output_radio], 
                                        outputs= [topic_sentence_input, topic_sentences_suggestions]
                                    )
                    
                    # Step 4.寫出支持句
                    with gr.Row():
                        with gr.Column():
                            with gr.Row() as supporting_sentences_params:
                                default_generate_supporting_sentences_prompt = """
                                    I'm aiming to improve my writing. I have a topic sentence as topic_sentence_input. 
                                    Please assist me by "Developing supporting detials" based on the keyword: points to write three sentences as an example.

                                    Rules:
                                    - Make sure any revised vocabulary aligns with the eng_level. 
                                    - Guidelines for Length and Complexity: 
                                    - Please keep the example concise and straightforward, 

                                    Restrictions:
                                    - avoiding overly technical language. 
                                    - Total word-count is around 50. no more explanation either no more extra non-relation sentences.
                                    - just output supporting sentences, don't output topic sentence at this step.
                                    - don't output bullet points, just output sentences.
                                    - don't number the sentences.

                                    EXAMPLE:
                                    - Washing your hands often helps you stay healthy. It removes dirt and germs that can make you sick. Clean hands prevent the spread of diseases. You protect yourself and others by washing your hands regularly.
                                """
                                user_generate_supporting_sentences_prompt = gr.Textbox(label="Supporting Sentences Prompt", value=default_generate_supporting_sentences_prompt, visible=False)
                            
                            with gr.Row() as supporting_sentences_html:
                                gr.Markdown("# Step 4. 寫出支持句")
                            with gr.Row():
                                with gr.Column():
                                    with gr.Row():
                                        gr.Image(value="https://storage.googleapis.com/jutor/jutor_support_image_1.jpg", show_label=False, show_download_button=False)
                                    with gr.Row():
                                        gr.Markdown("## 請根據主題句及段落要點/關鍵字,來寫支持句。")
                                    with gr.Row():
                                        gr.Markdown("## 支持句必須詳細描寫、記敘、説明、論證段落的要點/關鍵字,必要時舉例説明,來支持佐證主題句。支持句應該按照邏輯順序來組織,例如時間順序、空間順序、重要性順序、因果關係等。並使用轉折詞來引導讀者從一個 idea 到下一個 idea,讓讀者讀起來很順暢,不需反覆閱讀。")
                                with gr.Column():
                                    with gr.Accordion("📝 參考指引:撰寫支持句的方法?", open=False):
                                        gr.Markdown("""
                                            - Explanation 解釋説明:說明居住城市的優點,例如住在城市可享受便利的交通。
                                            - Fact 陳述事實:説明運動可以增強心肺功能和肌肉力量,對於身體健康有正面影響。
                                            - Cause and Effect 原因結果:解釋為何必須家事分工,例如家事分工更容易維護家庭環境的整齊清潔。
                                            - Compare and Contrast 比較與對比:將主題與其他相關事物進行比較。例如比較傳統教學與線上學習。
                                            - Incident 事件:利用事件來做説明。例如誤用表情符號造成困擾的事件,或葡式蛋塔風行的跟瘋事件。
                                            - Evidence 提供證據:引用相關數據、研究或事實來佐證。例如全球互聯網用戶數已經突破了 50 億人,佔全球總人口近 65%。
                                            - Example 舉例:舉自家為例,説明如何將家事的責任分配給每個家庭成員。
                                        """)
                                    with gr.Accordion("參考指引:針對要點/關鍵字的支持句,要寫幾句呢?", open=False):
                                        gr.Markdown("""
                                            - 一個要點/關鍵字,寫 3-6 句
                                            - 兩個要點/關鍵字,每個寫 2-3 句
                                            - 三個要點/關鍵字,每個寫 1-2 句
                                        """)
                            with gr.Row():
                                with gr.Column():
                                    supporting_sentences_input = gr.Textbox(label="根據要點/關鍵字來寫支持句")
                                with gr.Column():
                                    generate_supporting_sentences_button = gr.Button("✨ JUTOR 產出支持句,供參考並自行寫出支持句", variant="primary")
                                    supporting_sentences_output = gr.Radio(label="AI 產出支持句", elem_id="supporting_sentences_button", visible=False, interactive=True)
                                
                                    generate_supporting_sentences_button.click(
                                        fn=show_elements,
                                        inputs=[],
                                        outputs=[supporting_sentences_output]
                                    ).then(
                                        fn=generate_supporting_sentences,
                                        inputs=[
                                            model, 
                                            max_tokens, 
                                            sys_content_input, 
                                            scenario_input, 
                                            eng_level_input,
                                            topic_input, 
                                            points_input,
                                            topic_sentence_input,
                                            user_generate_supporting_sentences_prompt
                                        ],
                                        outputs=supporting_sentences_output
                                    )

                                    supporting_sentences_output.select(
                                        fn=update_supporting_sentences_input, 
                                        inputs=[supporting_sentences_output], 
                                        outputs= [supporting_sentences_input]
                                    )
                    
                    # Step 5. 寫出結論句
                    with gr.Row():
                        with gr.Column():
                            with gr.Row() as conclusion_sentences_params:
                                default_generate_conclusion_sentence_prompt = """
                                    I'm aiming to improve my writing. 
                                    By the topic sentence, please assist me by "Developing conclusion sentences" 
                                    based on keywords of points to finish a paragrpah as an example.
                                    
                                    Rules:
                                    - Make sure any revised vocabulary aligns with the correctly eng_level. 
                                    - Guidelines for Length and Complexity: 
                                    - Please keep the example concise and straightforward, 
                                    - Total word-count is around 20. 

                                    Restrictions:
                                    - avoiding overly technical language. 
                                    - no more explanation either no more extra non-relation sentences. this is very important.

                                    Output use JSON format
                                    EXAMPLE:
                                    {{"results": "Thus, drinking water every day keeps us healthy and strong."}}
                                """
                                user_generate_conclusion_sentence_prompt = gr.Textbox(label="Conclusion Sentence Prompt", value=default_generate_conclusion_sentence_prompt, visible=False)
                            
                            with gr.Row() as conclusion_sentences_html:
                                gr.Markdown("# Step 5. 寫出結論句")
                            with gr.Row():
                                with gr.Column():
                                    gr.Markdown("## 簡潔重申段落主旨,可以用重述主題句、摘要支持句、回應或評論主題句(例如強調重要性或呼籲採取行動)等方式來寫。")
                                with gr.Column():
                                    with gr.Accordion("📝 參考指引:撰寫「結論句」的方法?", open=False):
                                        gr.Markdown("""
                                            - 以換句話說 (paraphrase) 的方式把主題句再說一次
                                            - 摘要段落要點方式寫結論句
                                            - 回應或評論主題句的方式來寫結論句(例如主題句要從事課外活動,就說課外活動有這麼多好處,應該多參加課外活動等等)
                                        """)
                            with gr.Row():
                                with gr.Column():
                                    conclusion_sentence_input = gr.Textbox(label="根據主題句、支持句來寫結論句")
                                with gr.Column():
                                    generate_conclusion_sentence_button = gr.Button("✨ JUTOR 產出結論句,供參考並自行寫出結論句", variant="primary")
                                    conclusion_sentence_output = gr.Radio(label="AI 產出結論句", visible=False, interactive=True)

                                    generate_conclusion_sentence_button.click(
                                        fn=show_elements,
                                        inputs=[],
                                        outputs=[conclusion_sentence_output]
                                    ).then(
                                        fn=generate_conclusion_sentences,
                                        inputs=[
                                            model, 
                                            max_tokens, 
                                            sys_content_input, 
                                            scenario_input, 
                                            eng_level_input,
                                            topic_input, 
                                            points_input,
                                            topic_sentence_input,
                                            user_generate_conclusion_sentence_prompt
                                        ],
                                        outputs=conclusion_sentence_output
                                    )

                                    conclusion_sentence_output.select(
                                        fn=update_conclusion_sentence_input, 
                                        inputs=[conclusion_sentence_output], 
                                        outputs= [conclusion_sentence_input]
                                    )
                    
                    # Step 6. 段落確認與修訂
                    with gr.Row():
                        with gr.Column():
                            with gr.Row():
                                gr.Markdown("# Step 6. 段落確認與修訂")
                            with gr.Row():
                                with gr.Column():
                                    with gr.Row():
                                        gr.Image(value="https://storage.googleapis.com/jutor/jutor_paragraph_evaluate.jpg", show_label=False, show_download_button=False)
                                    with gr.Row():
                                        gr.Markdown("""## 你已經完成段落草稿,可再檢視幾次:
                                                    ### 1. 找出文法、拼字或標點錯誤
                                                    ### 2. 需要之處加入合適的轉折詞,例如:first, second, however, moreover, etc.
                                                    ### 3. 整個段落是否連貫、流暢、容易理解
                                                """)
                                with gr.Column():
                                    with gr.Accordion("📝 參考指引:什麼是段落的連貫性?", open=False):
                                        gr.Markdown("""
                                            - 能夠以清晰、邏輯的方式表達自己的想法,使讀者易於理解。
                                            - 連貫的段落應該有一個清晰的主題句來介紹主要想法(main idea),接著是支持句,提供更多細節和例子來支持主題句。
                                            - 支持句應該按照邏輯制序,引導讀者從一個idea順利讀懂下一個idea。
                                            - 有些句子間邏輯關係不清楚,還需要使用轉折詞(邏輯膠水)做連結,來引導讀者,例如:
                                                - first, second, finally 表示段落要點的秩序
                                                - moreover, furthermore, additionally 表示介紹另外一個要點
                                                - however, nevertheless 表示下面句子是相反的關係
                                                - therefore, as a result表示下面句子是結果
                                                - in comparison, by contrast表示下面句子比較的關係
                                                - for example, for instance 表示下面句子是舉例
                                            - 最後,段落應該有一個結論句,總結主要觀點,強化所要傳遞的資訊。
                                        """)
                            with gr.Row():
                                generate_paragraph_button = gr.Button("請點擊此按鈕,合併已填寫的句子為草稿,供閱讀、下載及修訂", variant="primary")
                            with gr.Row():
                                with gr.Column():
                                    paragraph_output = gr.TextArea(label="完整段落", show_copy_button=True)
                                with gr.Column():
                                    paragraph_output_download = gr.File(label="下載段落草稿")

                                generate_paragraph_button.click(
                                    fn=show_elements,
                                    inputs=[],
                                    outputs=[paragraph_output]
                                ).then(
                                    fn=generate_paragraph,
                                    inputs=[
                                        topic_sentence_input,
                                        supporting_sentences_input, 
                                        conclusion_sentence_input
                                    ],
                                    outputs=paragraph_output
                                ).then(
                                    fn=download_content,
                                    inputs=[paragraph_output],
                                    outputs=[paragraph_output_download]
                                )
                            with gr.Row(visible=False) as paragraph_evaluate_params:
                                default_user_generate_paragraph_evaluate_prompt = """
                                    Based on the final paragraph provided, evaluate the writing in terms of content, organization, grammar, and vocabulary. Provide feedback in simple and supportive language.

                                    -- 根據上述的文章,以「內容(content)」層面評分。
                                    Assess the student's writing by focusing on the 'Content' category according to the established rubric. Determine the clarity of the theme or thesis statement and whether it is supported by specific and complete details relevant to the topic. Use the following levels to guide your evaluation:

                                    - Excellent (5-4 points): Look for a clear and pertinent theme or thesis, directly related to the topic, with detailed support.
                                    - Good (3 points): The theme should be present but may lack clarity or emphasis; some narrative development related to the theme should be evident.
                                    - Fair (2-1 points): Identify if the theme is unclear or if the majority of the narrative is undeveloped or irrelevant to the theme.
                                    - Poor (0 points): Determine if the response is off-topic or not written at all. Remember that any response that is off-topic or unwritten should receive zero points in all aspects.

                                    Your detailed feedback should explain the score you assign, including specific examples from the text to illustrate how well the student's content meets the criteria. 
                                    Translate your feedback into Traditional Chinese (zh-tw) as the final result (#中文解釋 zh-TW).

                                    評分結果以 JSON 格式輸出: content: { 
                                    "level": "#Excellent(5-4 pts)/Good(3 pts)/Fair(2-1 pts)/Poor(0 pts)", 
                                    "explanation": "#中文解釋 zh-TW"
                                    }

                                    -- 根據上述的文章,以「組織(organization)」層面評分。
                                    Evaluate the student's writing with a focus on 'Organization' according to the grading rubric. Consider the structure of the text, including the presence of a clear introduction, development, and conclusion, as well as the coherence throughout the piece and the use of transitional phrases. Use the following levels to structure your feedback:

                                    - Excellent (5-4 points): Look for clear key points with a logical introduction, development, and conclusion, and note whether transitions are coherent and effectively used.
                                    - Good (3 points): The key points should be identifiable but may not be well-arranged; observe any imbalance in development and transitional phrase usage.
                                    - Fair (2-1 points): Identify if the key points are unclear and if the text lacks coherence.
                                    - Poor (0 points): Check if the writing is completely unorganized or not written according to the prompts. Texts that are entirely unorganized should receive zero points.
                                    
                                    Your detailed feedback should explain the score you assign, including specific examples from the text to illustrate how well the student's Organization meets the criteria. Translate your feedback into Traditional Chinese (zh_tw) as the final result (#中文解釋).

                                    評分結果以 JSON 格式輸出: organization: { 
                                    "level": "#Excellent(5-4 pts)/Good(3 pts)/Fair(2-1 pts)/Poor(0 pts)", 
                                    "explanation": "#中文解釋 zh-TW" 
                                    }

                                    -- 根據上述的文章,以「文法和用法(Grammar and usage)」層面評分。
                                    Review the student's writing, paying special attention to 'Grammar/Sentence Structure'. Assess the accuracy of grammar and the variety of sentence structures throughout the essay. Use the rubric levels to judge the work as follows:

                                    - Excellent (5-4 points): Search for text with minimal grammatical errors and a diverse range of sentence structures.
                                    - Good (3 points): There may be some grammatical errors, but they should not affect the overall meaning or flow of the text.
                                    - Fair (2-1 points): Determine if grammatical errors are frequent and if they significantly affect the meaning of the text.
                                    - Poor (0 points): If the essay contains severe grammatical errors throughout, leading to an unclear meaning, it should be marked accordingly.

                                    Your detailed feedback should explain the score you assign, including specific examples from the text to illustrate how well the student's Grammar/Sentence Structure meets the criteria. Translate your feedback into Traditional Chinese (zh_tw) as the final result (#中文解釋).

                                    評分結果以 JSON 格式輸出: grammar_and_usage: { 
                                    "level": "#Excellent(5-4 pts)/Good(3 pts)/Fair(2-1 pts)/Poor(0 pts)", 
                                    "explanation": "#中文解釋 zh-TW" 
                                    }

                                    -- 根據上述的文章,以「詞彙(Vocabulary )」層面評分。
                                    Assess the use of 'Vocabulary/Spelling' in the student's writing based on the criteria provided. Evaluate the precision and appropriateness of the vocabulary and the presence of spelling errors. Reference the following scoring levels in your analysis:

                                    - Excellent (5-4 points): The writing should contain accurate and appropriate vocabulary with almost no spelling mistakes.
                                    - Good (3 points): Vocabulary might be somewhat repetitive or mundane; there may be occasional misused words and minor spelling mistakes, but they should not impede understanding.
                                    - Fair (2-1 points): Notice if there are many vocabulary errors and spelling mistakes that clearly affect the clarity of the text's meaning.
                                    - Poor (0 points): Writing that only contains scattered words related to the topic or is copied should be scored as such.

                                    Your detailed feedback should explain the score you assign, including specific examples from the text to illustrate how well the student's Vocabulary/Spelling meets the criteria. Translate your feedback into Traditional Chinese (zh_tw) as the final result (#中文解釋).

                                    評分結果以 JSON 格式輸出: vocabulary: { 
                                    "level": "#Excellent(5-4 pts)/Good(3 pts)/Fair(2-1 pts)/Poor(0 pts)", 
                                    "explanation": "#中文解釋 zh-TW" 
                                    }

                                    -- 根據上述的文章,以「連貫性和連接詞(Coherence and Cohesion)」層面評分。
                                    - 評分等級有三級:beginner, intermediate, advanced.
                                    - 以繁體中文 zh-TW 解釋
                                    評分結果以 JSON 格式輸出: coherence_and_cohesion: { 
                                    "level": "#beginner/intermediate/advanced", 
                                    "explanation": "#中文解釋 zh-TW"
                                    }

                                    Restrictions:
                                    - the _explanation should be in Traditional Chinese (zh-TW), it's very important.

                                    Final Output JSON Format:
                                    {{
                                    “content“: {{content’s dict}},
                                    “organization“: {{organization'dict}},
                                    “grammar_and_usage“: {{grammar_and_usage'dict}},
                                    “vocabulary“: {{vocabulary'dict}},
                                    “coherence_and_cohesion“: {{coherence_and_cohesion'dict}}
                                    }}            
                                """
                                user_generate_paragraph_evaluate_prompt = gr.Textbox(label="Paragraph evaluate Prompt", value=default_user_generate_paragraph_evaluate_prompt, visible=False)
                            with gr.Row():
                                generate_paragraph_evaluate_button = gr.Button("✨ 段落分析", variant="primary")
                            with gr.Row():
                                paragraph_evaluate_output = gr.Dataframe(label="完整段落分析", wrap=True, column_widths=[35, 15, 50], interactive=False, visible=False)

                    # 修訂文法與拼字錯誤
                    with gr.Row():
                        with gr.Column():
                            with gr.Row() as paragraph_correct_grammatical_spelling_errors_params:
                                default_user_correct_grammatical_spelling_errors_prompt = """
                                    I'm aiming to improve my writing. 
                                    Please assist me by "Correcting Grammatical and Spelling Errors" in the provided paragraph. 
                                    For every correction you make, I'd like an "Explanation" to understand the reasoning behind it. 
                                    
                                    Rules:
                                    - Paragraph for Correction: [paragraph split by punctuation mark]    
                                    - The sentence to remain unchanged: [sentence_to_remain_unchanged]
                                    - When explaining, use Traditional Chinese (Taiwan, 繁體中文) for clarity. 
                                    - But others(original, Correction, revised_paragraph) in English.
                                    - Make sure any revised vocabulary aligns with the eng_level. 
                                    - Prepositions Followed by Gerunds: After a preposition, a gerund (the -ing form of a verb) should be used. For example: "interested in reading."
                                    - Two Main Verbs in a Sentence: When a sentence has two main verbs, it is necessary to use conjunctions, infinitives, clauses, or participles to correctly organize and connect the verbs, avoiding confusion in the sentence structure.
                                    
                                    Guidelines for Length and Complexity: 
                                    - Please keep explanations concise and straightforward
                                    - if there are no grammatical or spelling errors, don't need to revise either no more suggestions to show in the revised paragraph.
                                    
                                    Restrictions:
                                    - avoiding overly technical language.
                                    - don't give any suggestions about the sentence to remain unchanged.
                                    - don't give suggestions about the Period, Comma etc.
                                    - Do not change the original text's case.
                                    - if no mistakes, don't need to revise.

                                    The response should strictly be in the below JSON format and nothing else:

                                    EXAMPLE:
                                    {{ 
                                        "Corrections and Explanations": [ 
                                            {{ "original": "# original_sentence1", "correction": "#correction_1", "explanation": "#explanation_1(in_traditional_chinese ZH-TW)" }}, 
                                            {{ "original": "# original_sentence2", "correction": "#correction_2", "explanation": "#explanation_2(in_traditional_chinese ZH-TW)" }}, 
                                            ... 
                                        ], 
                                        "Revised Paragraph": "#revised_paragraph" 
                                    }}
                                """
                                user_correct_grammatical_spelling_errors_prompt = gr.Textbox(label="Correct Grammatical and Spelling Errors Prompt", value=default_user_correct_grammatical_spelling_errors_prompt, visible=False)
                            
                            with gr.Row() as paragraph_correct_grammatical_spelling_errors_html:
                                gr.Markdown("# Step 7. 修訂文法與拼字錯誤")
                                with gr.Accordion("📝 參考指引:AI 的混淆狀況?", open=False):
                                    gr.Markdown("""
                                        - 段落寫作的過程,如果全程採用 JUTOR 的建議例句,則不會有文法與拼字錯誤。JUTOR 有時後仍會挑出一些字詞修訂,並非原本字詞錯誤,而是改換不同說法,你可以參考。
                                        - 若是自行完成段落寫作,則不會發生自我修訂的混淆狀況。
                                    """)
                            with gr.Row():
                                with gr.Column():
                                    paragraph_correct_grammatical_spelling_errors_input = gr.TextArea(label="這是你的原始寫作內容,參考 JUTOR 的改正,你可以選擇是否修改:", show_copy_button=True)
                                with gr.Column():
                                    generate_correct_grammatical_spelling_errors_button = gr.Button("✨ 修訂文法與拼字錯誤", variant="primary")
                                    correct_grammatical_spelling_errors_output_table = gr.Dataframe(label="修訂文法與拼字錯誤", interactive=False, visible=False)
                                    revised_paragraph_output = gr.Textbox(label="Revised Paragraph", show_copy_button=True, visible=False)
                                    gr.Markdown("## 修改參考")
                                    revised_paragraph_diff = gr.HTML()

                    # 段落改善建議
                    with gr.Row():
                        with gr.Column():
                            with gr.Row() as paragraph_refine_params:
                                default_user_refine_paragraph_prompt = """
                                    I need assistance with revising a paragraph. Please Refine the paragraph and immediately "Provide Explanations" for each suggestion you made. 
                                    
                                    Rules:
                                    - Do not modify the sentence: topicSentence" 
                                    - Make sure any revised vocabulary aligns with the eng_level. 
                                    - When explaining, use Traditional Chinese (Taiwan, 繁體中文 zh-TW) for clarity.
                                    - But others(Origin, Suggestion, revised_paragraph_v2) use English, that's very important.
                                    
                                    Guidelines for Length and Complexity: 
                                    - Please keep explanations concise and straightforward
                                    - if there are no problems, don't need to revise either no more suggestions to show in the revised paragraph.
                                    
                                    Restrictions:
                                    - avoiding overly technical language.
                                    - don't change the text's case in the original text.
                                    
                                    The response should strictly be in the below JSON format and nothing else:
                                    
                                    EXAMPLE:
                                    {
                                    "Suggestions and Explanations": [ 
                                        { "origin": "#original_text_1", "suggestion": "#suggestion_1", "explanation": "#explanation_1(in_traditional_chinese zh-TW)" }, 
                                        { "origin": "#original_text_2", "suggestion": "#suggestion_2", "explanation": "#explanation_2(in_traditional_chinese zh-TW)" }, 
                                    ... ],
                                    "Revised Paragraph": "#revised_paragraph_v2"
                                    }  
                                """
                                user_refine_paragraph_prompt = gr.Textbox(label="Refine Paragraph Prompt", value=default_user_refine_paragraph_prompt, visible=False)
                            
                            with gr.Row() as paragraph_refine_html:
                                gr.Markdown("# Step 8. 段落改善建議")
                                with gr.Accordion("📝 參考指引:段落改善建議?", open=False ):
                                    gr.Markdown("""
                                        - 段落寫作的過程,如果全程採用 JUTOR 的建議例句,在這部分的批改可能會發生自我修訂的現象。例如:為了符合級別需求,JUTOR 會將自已建議的例句,以換句話說的方式再次修改,你可以忽略。
                                        - 若是自行完成段落寫作,則不會發生自我修訂的混淆狀況。
                                    """)
                            with gr.Row():
                                with gr.Column():
                                    paragraph_refine_input = gr.TextArea(label="這是你的原始寫作內容,參考 JUTOR 的建議,你可以選擇是否修改:", show_copy_button=True)
                                with gr.Column():
                                    generate_refine_paragraph_button = gr.Button("✨ 段落改善建議", variant="primary")
                                    refine_output_table = gr.Dataframe(label="段落改善建議", wrap=True, interactive=False, visible=False)
                                    refine_output = gr.HTML(label="修改建議", visible=False)
                                    gr.Markdown("## 修改參考")
                                    refine_output_diff = gr.HTML()

                    # 段落分析
                    generate_paragraph_evaluate_button.click(
                        fn=show_elements,
                        inputs=[],
                        outputs=[paragraph_evaluate_output]
                    ).then(
                        fn=generate_paragraph_evaluate,
                        inputs=[
                            model,
                            sys_content_input,
                            paragraph_output,
                            user_generate_paragraph_evaluate_prompt
                        ],
                        outputs=paragraph_evaluate_output
                    ).then(
                        fn=update_paragraph_correct_grammatical_spelling_errors_input,
                        inputs=[paragraph_output],
                        outputs=paragraph_correct_grammatical_spelling_errors_input
                    )

                    # 修訂文法與拼字錯誤
                    generate_correct_grammatical_spelling_errors_button.click(
                        fn=show_elements,
                        inputs=[],
                        outputs=[correct_grammatical_spelling_errors_output_table]
                    ).then(
                        fn=generate_correct_grammatical_spelling_errors,
                        inputs=[
                            model,
                            sys_content_input,
                            eng_level_input,
                            paragraph_output,
                            user_correct_grammatical_spelling_errors_prompt,
                        ],
                        outputs=[
                            correct_grammatical_spelling_errors_output_table, 
                            revised_paragraph_output
                        ]
                    ).then(
                        fn=highlight_diff_texts,
                        inputs=[correct_grammatical_spelling_errors_output_table, revised_paragraph_output],
                        outputs=revised_paragraph_diff
                    ).then(
                        fn=update_paragraph_refine_input,
                        inputs=[paragraph_correct_grammatical_spelling_errors_input],
                        outputs=paragraph_refine_input
                    )

                    # 段落改善建議
                    generate_refine_paragraph_button.click(
                        fn=show_elements,
                        inputs=[],
                        outputs=[refine_output_table]
                    ).then(
                        fn=generate_refine_paragraph,
                        inputs=[
                            model,
                            sys_content_input,
                            eng_level_input,
                            paragraph_correct_grammatical_spelling_errors_input,
                            user_refine_paragraph_prompt
                        ],
                        outputs=[refine_output_table, refine_output]
                    ).then(
                        fn=highlight_diff_texts,
                        inputs=[refine_output_table, refine_output],
                        outputs=refine_output_diff
                    )
                            
                    # Final Step. 寫作完成
                    with gr.Row():
                        with gr.Column():
                            with gr.Row():
                                gr.Markdown("# Step 9. 寫作完成 Save and Share")
                            with gr.Row():
                                paragraph_practice_save_button = gr.Button("點擊建立 doc", variant="primary")
                            with gr.Row():
                                # 顯示最後段落寫作結果
                                with gr.Column():
                                    paragraph_practice_save_output = gr.TextArea(label="最後結果", show_copy_button=True)
                                with gr.Column():
                                    paragraph_practice_download_link = gr.File(label="請點擊右下角連結(ex: 37KB),進行下載")

                                    paragraph_practice_save_button.click(
                                        fn=download_content,
                                        inputs=[paragraph_refine_input],
                                        outputs=[paragraph_practice_download_link]
                                    ).then(
                                        fn=duplicate_element,
                                        inputs=[paragraph_refine_input],
                                        outputs=[paragraph_practice_save_output]
                                    )

                            with gr.Row():
                                gr.Markdown("## 完成修訂!你按部就班地完成了一次段落寫作練習,太棒了!")
                            with gr.Row():
                                paragraph_save_button = gr.Button("建立歷程回顧", variant="primary")
                            with gr.Row(elem_id="paragraph_save_output"):
                                with gr.Accordion("歷程回顧", open=False) as history_accordion:
                                    scenario_input_history = gr.Textbox(label="情境", visible=False)
                                    
                                    gr.Markdown("<span style='color:#4e80ee'>主題</span>")
                                    topic_input_history = gr.Markdown(label="主題")
                                    gr.Markdown("<span style='color:#4e80ee'>要點/關鍵字</span>")
                                    points_input_history = gr.Markdown(label="要點/關鍵字")
                                    gr.Markdown("<span style='color:#4e80ee'>主題句</span>")
                                    topic_sentence_input_history = gr.Markdown(label="主題句")
                                    gr.Markdown("<span style='color:#4e80ee'>支持句</span>")
                                    supporting_sentences_input_history = gr.Markdown(label="支持句")
                                    gr.Markdown("<span style='color:#4e80ee'>結論句</span>")
                                    conclusion_sentence_input_history = gr.Markdown(label="結論句")
                                    
                                    gr.Markdown("<span style='color:#4e80ee'>完整段落</span>")
                                    paragraph_output_history = gr.Markdown(label="完整段落")
                                    
                                    paragraph_evaluate_output_history = gr.Dataframe(label="完整段落分析", wrap=True, column_widths=[35, 15, 50], interactive=False)
                                    correct_grammatical_spelling_errors_output_table_history = gr.Dataframe(label="修訂文法與拼字錯誤", interactive=False, wrap=True, column_widths=[30, 30, 40])
                                    refine_output_table_history = gr.Dataframe(label="段落改善建議", wrap=True, interactive=False, column_widths=[30, 30, 40])
                                    gr.Markdown("<span style='color:#4e80ee'>修改建議</span>")
                                    refine_output_history = gr.Markdown(label="修改建議")
                                    
                                    gr.Markdown("<span style='color:#4e80ee'>修改結果</span>")
                                    paragraph_save_output = gr.Markdown(label="最後結果")
                            with gr.Row():
                                audio_output = gr.Audio(label="音檔", type="filepath")

                                paragraph_save_button.click(
                                    fn=generate_paragraph_history,
                                    inputs=[
                                        user_data,
                                        session_timestamp,
                                        request_origin,
                                        scenario_input,
                                        topic_input,
                                        points_input,
                                        topic_sentence_input,
                                        supporting_sentences_input,
                                        conclusion_sentence_input,
                                        paragraph_output,
                                        paragraph_evaluate_output,
                                        correct_grammatical_spelling_errors_output_table,
                                        refine_output_table,
                                        refine_output
                                    ],
                                    outputs=[
                                        scenario_input_history,
                                        topic_input_history,
                                        points_input_history,
                                        topic_sentence_input_history,
                                        supporting_sentences_input_history,
                                        conclusion_sentence_input_history,
                                        paragraph_output_history,
                                        paragraph_evaluate_output_history,
                                        correct_grammatical_spelling_errors_output_table_history,
                                        refine_output_table_history,
                                        refine_output_history,
                                    ]
                                ).then(
                                    fn=paragraph_save_and_tts,
                                    inputs=[
                                        paragraph_practice_save_output
                                    ],
                                    outputs=[
                                        paragraph_save_output, 
                                        audio_output
                                    ]
                                ).then(
                                    fn=update_history_accordion,
                                    inputs=[],
                                    outputs=history_accordion
                                )

            # ====="英文全文批改"=====
            with gr.Row(visible=False, elem_id="english_grapragh_evaluate_row") as english_grapragh_evaluate_row:
                with gr.Column():
                    with gr.Row(visible=False) as full_paragraph_params:
                        full_paragraph_sys_content_input = gr.Textbox(label="System Prompt", value="You are an English teacher who is practicing with me to improve my English writing skill.")
                        default_user_generate_full_paragraph_evaluate_prompt = default_user_generate_paragraph_evaluate_prompt
                        user_generate_full_paragraph_evaluate_prompt = gr.Textbox(label="Paragraph evaluate Prompt", value=default_user_generate_full_paragraph_evaluate_prompt, visible=False)
                    with gr.Row():
                        gr.Markdown("# 📊 英文段落寫作評分")
                    # 輸入段落全文
                    with gr.Row():
                        gr.Markdown("## 輸入段落全文")
                    with gr.Row():
                        with gr.Column():
                            full_paragraph_input = gr.TextArea(label="輸入段落全文")
                        with gr.Column():
                            with gr.Row():
                                full_paragraph_evaluate_button = gr.Button("✨ JUTOR 段落全文分析", variant="primary")
                            with gr.Row():
                                full_paragraph_evaluate_output = gr.Dataframe(label="段落全文分析", wrap=True, column_widths=[35, 15, 50], interactive=False)

                    # JUTOR 段落批改與整體建議
                    with gr.Row():
                        gr.Markdown("# JUTOR 修訂文法與拼字錯誤")
                    with gr.Row():
                        with gr.Column():
                            full_paragraph_correct_grammatical_spelling_errors_input = gr.TextArea(label="這是你的原始寫作內容,參考 JUTOR 的建議,你可以選擇是否修改:")
                        with gr.Column():
                            generate_full_paragraph_correct_grammatical_spelling_errors_button = gr.Button("✨ JUTOR 修訂文法與拼字錯誤", variant="primary")
                            full_paragraph_correct_grammatical_spelling_errors_output_table = gr.Dataframe(label="修訂文法與拼字錯誤", interactive=False, column_widths=[30, 30, 40])
                            revised_full_paragraph_output = gr.Textbox(label="Revised Paragraph", show_copy_button=True, visible=False)
                            gr.Markdown("## 修訂結果")
                            revised_full_paragraph_diff = gr.HTML()

                    # JUTOR 段落批改與整體建議
                    with gr.Row():
                        gr.Markdown("# JUTOR 段落改善建議")
                    with gr.Row():
                        with gr.Column():
                            full_paragraph_refine_input = gr.TextArea(label="這是你的原始寫作內容,參考 JUTOR 的建議,你可以選擇是否修改:", show_copy_button=True)
                        with gr.Column():
                            generate_full_paragraph_refine_button = gr.Button("✨ JUTOR 段落改善建議", variant="primary")
                            full_paragraph_refine_output_table = gr.DataFrame(label="段落改善建議", wrap=True, interactive=False)
                            full_paragraph_refine_output = gr.HTML(label="修改建議", visible=False)
                            gr.Markdown("## 修改結果")
                            full_paragraph_refine_output_diff = gr.HTML()

                    # 寫作完成
                    with gr.Row():
                        gr.Markdown("# 寫作完成")
                    with gr.Row():
                        full_paragraph_save_button = gr.Button("輸出結果", variant="primary")
                    with gr.Row():
                        full_paragraph_save_output = gr.TextArea(label="最後結果")
                        full_audio_output = gr.Audio(label="音檔", type="filepath")

                    # 建立歷程回顧
                    with gr.Row():
                        gr.Markdown("# 歷程回顧")
                    with gr.Row():
                        full_paragraph_history_save_button = gr.Button("建立歷程回顧", variant="primary")
                    with gr.Row():
                        with gr.Accordion("歷程回顧", open=False) as full_paragraph_history_accordion:
                            gr.Markdown("<span style='color:#4e80ee'>輸入段落全文</span>")
                            full_paragraph_input_history = gr.Markdown()
                            gr.Markdown("<span style='color:#4e80ee'>段落全文分析</span>")
                            full_paragraph_evaluate_output_history = gr.Dataframe( wrap=True, column_widths=[35, 15, 50], interactive=False)
                            
                            gr.Markdown("<span style='color:#4e80ee'>修訂文法與拼字錯誤 輸入</span>")
                            full_paragraph_correct_grammatical_spelling_errors_input_history = gr.Markdown()
                            gr.Markdown("<span style='color:#4e80ee'>修訂文法與拼字錯誤</span>")
                            full_paragraph_correct_grammatical_spelling_errors_output_table_history = gr.Dataframe(interactive=False, wrap=True, column_widths=[30, 30, 40])
                            
                            gr.Markdown("<span style='color:#4e80ee'>段落改善建議 輸入</span>")
                            full_paragraph_refine_input_history = gr.Markdown()
                            gr.Markdown("<span style='color:#4e80ee'>段落改善建議</span>")
                            full_paragraph_refine_output_table_history = gr.Dataframe(wrap=True, interactive=False, column_widths=[30, 30, 40])
                            
                            gr.Markdown("<span style='color:#4e80ee'>修改建議</span>")
                            full_paragraph_refine_output_history = gr.Markdown()
                            gr.Markdown("<span style='color:#4e80ee'>修改結果</span>")
                            full_paragraph_save_output_history = gr.Markdown()
                           
                    full_paragraph_evaluate_button.click(
                        fn=generate_paragraph_evaluate,
                        inputs=[model, sys_content_input, full_paragraph_input, user_generate_full_paragraph_evaluate_prompt],
                        outputs=full_paragraph_evaluate_output
                    ).then(
                        fn=update_paragraph_correct_grammatical_spelling_errors_input,
                        inputs=[full_paragraph_input],
                        outputs=full_paragraph_correct_grammatical_spelling_errors_input
                    )
                    
                    generate_full_paragraph_correct_grammatical_spelling_errors_button.click(
                        fn=generate_correct_grammatical_spelling_errors,
                        inputs=[model, sys_content_input, eng_level_input, full_paragraph_correct_grammatical_spelling_errors_input, user_correct_grammatical_spelling_errors_prompt],
                        outputs=[full_paragraph_correct_grammatical_spelling_errors_output_table, revised_full_paragraph_output]
                    ).then(
                        fn=highlight_diff_texts,
                        inputs=[full_paragraph_correct_grammatical_spelling_errors_output_table, revised_full_paragraph_output],
                        outputs=revised_full_paragraph_diff
                    ).then(
                        fn=update_paragraph_refine_input,
                        inputs=[full_paragraph_correct_grammatical_spelling_errors_input],
                        outputs=full_paragraph_refine_input
                    )

                    generate_full_paragraph_refine_button.click(
                        fn=generate_refine_paragraph,
                        inputs=[
                            model, 
                            sys_content_input, 
                            eng_level_input, 
                            full_paragraph_refine_input, 
                            user_refine_paragraph_prompt
                        ],
                        outputs=[full_paragraph_refine_output_table, full_paragraph_refine_output]
                    ).then(
                        fn=highlight_diff_texts,
                        inputs=[full_paragraph_refine_output_table, full_paragraph_refine_output],
                        outputs=full_paragraph_refine_output_diff
                    )

                    full_paragraph_save_button.click(
                        fn=paragraph_save_and_tts,
                        inputs=[full_paragraph_refine_input],
                        outputs=[full_paragraph_save_output, full_audio_output]
                    )

                    full_paragraph_history_save_button.click(
                        fn=generate_paragraph_evaluate_history,
                        inputs=[
                            user_data,
                            session_timestamp,
                            request_origin,
                            full_paragraph_input,
                            full_paragraph_evaluate_output,
                            full_paragraph_correct_grammatical_spelling_errors_input,
                            full_paragraph_correct_grammatical_spelling_errors_output_table,
                            full_paragraph_refine_input,
                            full_paragraph_refine_output_table,
                            full_paragraph_refine_output,
                            full_paragraph_save_output
                        ],
                        outputs=[
                            full_paragraph_input_history,
                            full_paragraph_evaluate_output_history,
                            full_paragraph_correct_grammatical_spelling_errors_input_history,
                            full_paragraph_correct_grammatical_spelling_errors_output_table_history,
                            full_paragraph_refine_input_history,
                            full_paragraph_refine_output_table_history,
                            full_paragraph_refine_output_history,
                            full_paragraph_save_output_history,
                        ]
                    ).then(
                        fn=update_history_accordion,
                        inputs=[],
                        outputs=full_paragraph_history_accordion
                    )


            # ====="英文考古題寫作練習====="   
            with gr.Row(visible=False, elem_id="english_exam_practice_row") as english_exam_practice_row:
                
                with gr.Column():
                    with gr.Row():
                        with gr.Column():
                            with gr.Row():
                                gr.Markdown("# 🎯 英文考古題寫作練習")
                            with gr.Row():
                                gr.Markdown("## 選擇考古題")
                            with gr.Row():
                                exams_data = load_exam_data()
                                past_exam_choices = [exam["title"] for exam in exams_data["exams"]]
                                past_exam_dropdown = gr.Radio(label="選擇考古題", choices=past_exam_choices)
                            with gr.Row():
                                past_exam_title = gr.Markdown()
                            with gr.Row():
                                with gr.Column():
                                    with gr.Row():
                                        past_exam_question = gr.Markdown()
                                    with gr.Row():
                                        with gr.Accordion("提示", open=False):
                                            with gr.Row():
                                                past_exam_hint = gr.Markdown()
                                with gr.Column():
                                    past_exam_image = gr.Image(show_label=False)
                                
                                past_exam_dropdown.select(
                                    fn=update_exam_contents,
                                    inputs=[past_exam_dropdown],
                                    outputs=[past_exam_title, past_exam_question, past_exam_hint, past_exam_image]
                                )

                            # 評分
                            with gr.Row():
                                with gr.Column():
                                    with gr.Row():
                                        past_exam_evaluation_sys_content_prompt = gr.Textbox(label="System Prompt", value="You are an English teacher who is practicing with me to improve my English writing skill.", visible=False)
                                        past_exam_evaluation_user_prompt = gr.Textbox(label="Paragraph evaluate Prompt", value=default_user_generate_paragraph_evaluate_prompt, visible=False)
                                        past_exam_evaluation_input = gr.TextArea("",label="這是你的原始寫作內容,參考 JUTOR 的建議,你可以選擇是否修改:")
                                with gr.Column():
                                    with gr.Row():
                                        past_exam_evaluation_button = gr.Button("全文分析", variant="primary")
                                    with gr.Row():
                                        past_exam_evaluation_output = gr.Dataframe(label="全文分析結果", wrap=True, column_widths=[20, 15, 65], interactive=False)
                                
                            # 修正錯字、語法
                            with gr.Row():
                                with gr.Column():
                                    past_exam_correct_grammatical_spelling_errors_input = gr.TextArea(label="這是你的原始寫作內容,參考 JUTOR 的建議,你可以選擇是否修改:",lines= 10, show_copy_button=True)
                                with gr.Column():
                                    with gr.Row():
                                        with gr.Accordion("prompt 提供微調測試", open=False, elem_classes=['accordion-prompts'], visible=False):
                                            past_exam_correct_grammatical_spelling_errors_prompt = gr.Textbox(label="Correct Grammatical and Spelling Errors Prompt", value=default_user_correct_grammatical_spelling_errors_prompt, lines= 20)
                                    with gr.Row():
                                        past_exam_generate_correct_grammatical_spelling_errors_button = gr.Button("修訂文法與拼字錯誤", variant="primary")
                                    with gr.Row():
                                        past_exam_correct_grammatical_spelling_errors_output_table = gr.Dataframe(label="修訂文法與拼字錯誤", interactive=False, column_widths=[30, 30, 40])
                                    with gr.Row():
                                        past_exam_revised_output = gr.Textbox(label="Revised Paragraph", show_copy_button=True, visible=False)
                                    with gr.Row():
                                        gr.Markdown("## 修訂結果")
                                    with gr.Row():
                                        past_exam_revised_diff = gr.HTML()

                            # 修正段落
                            with gr.Row():
                                with gr.Column():
                                    past_exam_refine_input = gr.TextArea(label="這是你的原始寫作內容,參考 JUTOR 的建議,你可以選擇是否修改:", show_copy_button=True)
                                with gr.Column():
                                    with gr.Row():
                                        with gr.Accordion("prompt 提供微調測試", open=False, elem_classes=['accordion-prompts'], visible=False):
                                            past_exam_refine_paragraph_prompt = gr.Textbox(label="Refine Paragraph Prompt", value=default_user_refine_paragraph_prompt, lines= 20)
                                    with gr.Row():
                                        past_exam_generate_refine_button = gr.Button("段落改善建議", variant="primary")
                                    with gr.Row():
                                        past_exam_refine_output_table = gr.DataFrame(label="Refine Paragraph 段落改善建議", wrap=True, interactive=False)
                                    with gr.Row():
                                        past_exam_refine_output = gr.HTML(label="修改建議", visible=False)
                                    with gr.Row():
                                        gr.Markdown("## 修改結果")
                                    with gr.Row():
                                        past_exam_refine_output_diff = gr.HTML()

                            # 最後成果
                            with gr.Row():
                                gr.Markdown("# 寫作完成")
                            with gr.Row():
                                past_exam_save_button = gr.Button("輸出結果", variant="primary")
                            with gr.Row():
                                with gr.Column():
                                    past_exam_save_output = gr.TextArea(label="最後結果")
                                with gr.Column():
                                    past_exam_audio_output = gr.Audio(label="音檔", type="filepath")
                                
                                past_exam_save_button.click(
                                    fn=paragraph_save_and_tts,
                                    inputs=[past_exam_refine_input],
                                    outputs=[past_exam_save_output, past_exam_audio_output]
                                )

                            # 建立歷程回顧
                            with gr.Row():
                                gr.Markdown("# 建立歷程回顧")
                            with gr.Row():
                                past_exam_history_save_button = gr.Button("建立歷程回顧", variant="primary")
                            with gr.Row():
                                with gr.Accordion("歷程回顧", open=False) as past_exam_history_accordion:
                                    gr.Markdown("<span style='color:#4e80ee'>考古題</span>")
                                    past_exam_dropdown_history = gr.Markdown()

                                    gr.Markdown("<span style='color:#4e80ee'>段落全文</span>")
                                    past_exam_input_history = gr.Markdown()
                                    gr.Markdown("<span style='color:#4e80ee'>段落全文分析</span>")
                                    past_exam_evaluate_output_history = gr.Dataframe(wrap=True, column_widths=[35, 15, 50], interactive=False)
                                    
                                    gr.Markdown("<span style='color:#4e80ee'>文法與拼字錯誤</span>")
                                    past_exam_correct_grammatical_spelling_errors_input_history = gr.Markdown()
                                    gr.Markdown("<span style='color:#4e80ee'>修訂文法與拼字錯誤</span>")
                                    past_exam_correct_grammatical_spelling_errors_output_table_history = gr.Dataframe(interactive=False, wrap=True, column_widths=[30, 30, 40])
                                    
                                    gr.Markdown("<span style='color:#4e80ee'>段落改善</span>")
                                    past_exam_refine_input_history = gr.Markdown()
                                    gr.Markdown("<span style='color:#4e80ee'>段落改善建議</span>")
                                    past_exam_refine_output_table_history = gr.Dataframe(wrap=True, interactive=False, column_widths=[30, 30, 40])
                        
                                    gr.Markdown("<span style='color:#4e80ee'>修改建議</span>")
                                    past_exam_refine_output_history = gr.Markdown()
                                    gr.Markdown("<span style='color:#4e80ee'>修改結果</span>")
                                    past_exam_save_output_history = gr.Markdown()


                                past_exam_history_save_button.click(  
                                    fn=generate_past_exam_history,
                                    inputs=[
                                        user_data,
                                        session_timestamp,
                                        request_origin,
                                        past_exam_dropdown,
                                        past_exam_evaluation_input,
                                        past_exam_evaluation_output,
                                        past_exam_correct_grammatical_spelling_errors_input,
                                        past_exam_correct_grammatical_spelling_errors_output_table,
                                        past_exam_refine_input,
                                        past_exam_refine_output_table,
                                        past_exam_refine_output,
                                        past_exam_save_output
                                    ],
                                    outputs=[
                                        past_exam_dropdown_history,
                                        past_exam_input_history,
                                        past_exam_evaluate_output_history,
                                        past_exam_correct_grammatical_spelling_errors_input_history,
                                        past_exam_correct_grammatical_spelling_errors_output_table_history,
                                        past_exam_refine_input_history,
                                        past_exam_refine_output_table_history,
                                        past_exam_refine_output_history,
                                        past_exam_save_output_history
                                    ]
                                ).then(
                                    fn=update_history_accordion,
                                    inputs=[],
                                    outputs=past_exam_history_accordion
                                )

                                past_exam_evaluation_button.click(
                                    fn=generate_paragraph_evaluate,
                                    inputs=[model, past_exam_evaluation_sys_content_prompt, past_exam_evaluation_input, past_exam_evaluation_user_prompt],
                                    outputs=past_exam_evaluation_output
                                ).then(
                                    fn=update_paragraph_correct_grammatical_spelling_errors_input,
                                    inputs=[past_exam_evaluation_input],
                                    outputs=past_exam_correct_grammatical_spelling_errors_input
                                )

                                past_exam_generate_correct_grammatical_spelling_errors_button.click(
                                    fn=generate_correct_grammatical_spelling_errors,
                                    inputs=[model, past_exam_evaluation_sys_content_prompt, eng_level_input, past_exam_correct_grammatical_spelling_errors_input, past_exam_correct_grammatical_spelling_errors_prompt],
                                    outputs=[past_exam_correct_grammatical_spelling_errors_output_table, past_exam_revised_output]
                                ).then(
                                    fn=highlight_diff_texts,
                                    inputs=[past_exam_correct_grammatical_spelling_errors_output_table, past_exam_revised_output],
                                    outputs=past_exam_revised_diff
                                ).then(
                                    fn=update_paragraph_refine_input,
                                    inputs=[past_exam_correct_grammatical_spelling_errors_input],
                                    outputs=past_exam_refine_input
                                )
                                
                                past_exam_generate_refine_button.click(
                                    fn=generate_refine_paragraph,
                                    inputs=[model, past_exam_evaluation_sys_content_prompt, eng_level_input, past_exam_refine_input, past_exam_refine_paragraph_prompt],
                                    outputs=[past_exam_refine_output_table, past_exam_refine_output]
                                ).then(
                                    fn=highlight_diff_texts,
                                    inputs=[past_exam_refine_output_table, past_exam_refine_output],
                                    outputs=past_exam_refine_output_diff
                                )
                
            # ===== 英文歷程 ====
            with gr.Row(visible=False, elem_id="english_logs_row") as english_logs_row:
                with gr.Column():
                    with gr.Row():
                        gr.Markdown("# 📚 歷程回顧")
                    with gr.Row():
                        with gr.Accordion("📝 英文段落練習歷程回顧", open=False) as english_grapragh_practice_logs_accordion:
                            with gr.Row():
                                with gr.Column(scale=1):
                                    # 取得英文段落練習 log from GCS
                                    paragraph_practice_logs_type = gr.State("jutor_write_paragraph_practice")
                                    get_paragraph_practice_logs_button = gr.Button("👉 取得英文段落練習歷程", variant="primary")
                                    paragraph_practice_logs_session_list = gr.Radio(label="歷程時間列表")
                                with gr.Column(scale=3, variant="compact"):
                                    gr.Markdown("<span style='color:#4e80ee'>主題</span>")
                                    paragraph_log_topic_input_history = gr.Markdown(label="主題")
                                    gr.Markdown("<span style='color:#4e80ee'>要點/關鍵字</span>")
                                    paragraph_log_points_input_history = gr.Markdown(label="要點/關鍵字")
                                    gr.Markdown("<span style='color:#4e80ee'>主題句</span>")
                                    paragraph_log_topic_sentence_input_history = gr.Markdown(label="主題句")
                                    gr.Markdown("<span style='color:#4e80ee'>支持句</span>")
                                    paragraph_log_supporting_sentences_input_history = gr.Markdown(label="支持句")
                                    gr.Markdown("<span style='color:#4e80ee'>結論句</span>")
                                    paragraph_log_conclusion_sentence_input_history = gr.Markdown(label="結論句")
                                    gr.Markdown("<span style='color:#4e80ee'>完整段落</span>")
                                    paragraph_log_paragraph_output_history = gr.Markdown(label="完整段落")
                                    paragraph_log_paragraph_evaluate_output_history = gr.Dataframe(label="完整段落分析", wrap=True, column_widths=[35, 15, 50], interactive=False)
                                    paragraph_log_correct_grammatical_spelling_errors_output_table_history = gr.Dataframe(label="修訂文法與拼字錯誤", interactive=False, wrap=True, column_widths=[30, 30, 40])
                                    paragraph_log_refine_output_table_history = gr.Dataframe(label="段落改善建議", wrap=True, interactive=False, column_widths=[30, 30, 40])
                                    gr.Markdown("<span style='color:#4e80ee'>修改建議</span>")
                                    paragraph_log_refine_output_history = gr.Markdown(label="修改建議")
                                    gr.Markdown("<span style='color:#4e80ee'>修改結果</span>")
                                    paragraph_log_paragraph_save_output = gr.Markdown(label="最後結果")

                                    get_paragraph_practice_logs_button.click(
                                        fn=get_logs_sessions,
                                        inputs=[user_data, paragraph_practice_logs_type],
                                        outputs=[paragraph_practice_logs_session_list]
                                    )

                                    paragraph_practice_logs_session_list.select(
                                        fn=get_paragraph_practice_log_session_content,
                                        inputs=[paragraph_practice_logs_session_list],
                                        outputs=[
                                            paragraph_log_topic_input_history,
                                            paragraph_log_points_input_history,
                                            paragraph_log_topic_sentence_input_history,
                                            paragraph_log_supporting_sentences_input_history,
                                            paragraph_log_conclusion_sentence_input_history,
                                            paragraph_log_paragraph_output_history,
                                            paragraph_log_paragraph_evaluate_output_history,
                                            paragraph_log_correct_grammatical_spelling_errors_output_table_history,
                                            paragraph_log_refine_output_table_history,
                                            paragraph_log_refine_output_history,
                                            paragraph_log_paragraph_save_output
                                        ]
                                    )
                    with gr.Row():
                        with gr.Accordion("📊 英文段落寫作評分歷程回顧", open=False) as english_grapragh_evaluate_logs_accordion:
                            with gr.Row():
                                with gr.Column(scale=1):
                                    # 取得英文段落練習 log from GCS
                                    full_paragraph_evaluate_logs_type = gr.State("jutor_write_full_paragraph_evaluation")
                                    get_full_paragraph_evaluate_logs_button = gr.Button("👉 取得英文段落寫作評分歷程", variant="primary")
                                    full_paragraph_evaluate_logs_session_list = gr.Radio(label="歷程時間列表")
                                with gr.Column(scale=3, variant="compact"):
                                    gr.Markdown("<span style='color:#4e80ee'>輸入段落全文</span>")
                                    log_full_paragraph_input_history = gr.Markdown()
                                    gr.Markdown("<span style='color:#4e80ee'>段落全文分析</span>")
                                    log_full_paragraph_evaluate_output_history = gr.Dataframe( wrap=True, column_widths=[35, 15, 50], interactive=False)
                                    
                                    gr.Markdown("<span style='color:#4e80ee'>修訂文法與拼字錯誤 輸入</span>")
                                    log_full_paragraph_correct_grammatical_spelling_errors_input_history = gr.Markdown()
                                    gr.Markdown("<span style='color:#4e80ee'>修訂文法與拼字錯誤</span>")
                                    log_full_paragraph_correct_grammatical_spelling_errors_output_table_history = gr.Dataframe(interactive=False, wrap=True, column_widths=[30, 30, 40])
                                    
                                    gr.Markdown("<span style='color:#4e80ee'>段落改善建議 輸入</span>")
                                    log_full_paragraph_refine_input_history = gr.Markdown()
                                    gr.Markdown("<span style='color:#4e80ee'>段落改善建議</span>")
                                    log_full_paragraph_refine_output_table_history = gr.Dataframe(wrap=True, interactive=False, column_widths=[30, 30, 40])
                                    
                                    gr.Markdown("<span style='color:#4e80ee'>修改建議</span>")
                                    log_full_paragraph_refine_output_history = gr.Markdown()
                                    gr.Markdown("<span style='color:#4e80ee'>修改結果</span>")
                                    log_full_paragraph_save_output_history = gr.Markdown()

                                    get_full_paragraph_evaluate_logs_button.click(
                                        fn=get_logs_sessions,
                                        inputs=[user_data, full_paragraph_evaluate_logs_type],
                                        outputs=[full_paragraph_evaluate_logs_session_list]
                                    )

                                    full_paragraph_evaluate_logs_session_list.select(
                                        fn=get_full_paragraph_evaluate_log_session_content,
                                        inputs=[full_paragraph_evaluate_logs_session_list],
                                        outputs=[
                                            log_full_paragraph_input_history,
                                            log_full_paragraph_evaluate_output_history,
                                            log_full_paragraph_correct_grammatical_spelling_errors_input_history,
                                            log_full_paragraph_correct_grammatical_spelling_errors_output_table_history,
                                            log_full_paragraph_refine_input_history,
                                            log_full_paragraph_refine_output_table_history,
                                            log_full_paragraph_refine_output_history,
                                            log_full_paragraph_save_output_history
                                        ]
                                    )
                    with gr.Row():
                        with gr.Accordion("🎯 英文考古題寫作練習歷程回顧", open=False) as english_exam_practice_logs_accordion:
                            with gr.Row():
                                with gr.Column(scale=1):
                                    # 取得英文段落練習 log from GCS
                                    past_exam_logs_type = gr.State("jutor_write_past_exam")
                                    get_past_exam_logs_button = gr.Button("👉 取得英文考古題寫作練習歷程", variant="primary")
                                    past_exam_logs_session_list = gr.Radio(label="歷程時間列表")
                                with gr.Column(scale=3, variant="compact"):
                                    gr.Markdown("<span style='color:#4e80ee'>考古題</span>")
                                    past_exam_log_dropdown_history = gr.Markdown()
                                    gr.Markdown("<span style='color:#4e80ee'>段落全文</span>")
                                    past_exam_log_input_history = gr.Markdown()
                                    gr.Markdown("<span style='color:#4e80ee'>段落全文分析</span>")
                                    past_exam_log_evaluate_output_history = gr.Dataframe(wrap=True, column_widths=[35, 15, 50], interactive=False)
                                    
                                    gr.Markdown("<span style='color:#4e80ee'>文法與拼字錯誤</span>")
                                    past_exam_log_correct_grammatical_spelling_errors_input_history = gr.Markdown()
                                    gr.Markdown("<span style='color:#4e80ee'>修訂文法與拼字錯誤</span>")
                                    past_exam_log_correct_grammatical_spelling_errors_output_table_history = gr.Dataframe(interactive=False, wrap=True, column_widths=[30, 30, 40])
                                    
                                    gr.Markdown("<span style='color:#4e80ee'>段落改善</span>")
                                    past_exam_log_refine_input_history = gr.Markdown()
                                    gr.Markdown("<span style='color:#4e80ee'>段落改善建議</span>")
                                    past_exam_log_refine_output_table_history = gr.Dataframe(wrap=True, interactive=False, column_widths=[30, 30, 40])
                                    
                                    gr.Markdown("<span style='color:#4e80ee'>最後結果</span>")
                                    past_exam_log_save_output_history = gr.Markdown()

                                    get_past_exam_logs_button.click(
                                        fn=get_logs_sessions,
                                        inputs=[user_data, past_exam_logs_type],
                                        outputs=[past_exam_logs_session_list]
                                    )

                                    past_exam_logs_session_list.select(
                                        fn=get_past_exam_practice_log_session_content,
                                        inputs=[past_exam_logs_session_list],
                                        outputs=[
                                            past_exam_log_dropdown_history,
                                            past_exam_log_input_history,
                                            past_exam_log_evaluate_output_history,
                                            past_exam_log_correct_grammatical_spelling_errors_input_history,
                                            past_exam_log_correct_grammatical_spelling_errors_output_table_history,
                                            past_exam_log_refine_input_history,
                                            past_exam_log_refine_output_table_history,
                                            past_exam_log_save_output_history
                                        ]
                                    )
                                                
            english_grapragh_practice_button.click(
                None,
                None,
                None,
                js=english_grapragh_practice_button_js
            )
            english_grapragh_evaluate_button.click(
                None,
                None,
                None,
                js=english_grapragh_evaluate_button_js
            )
            english_exam_practice_tab_button.click(
                None,
                None,
                None,
                js=english_exam_practice_tab_button_js
            )
            english_logs_tab_button.click(
                None,
                None,
                None,
                js=english_logs_tab_button_js
            )


    with gr.Row(visible=False) as chinese_group:
        with gr.Column():
            with gr.Row() as page_title_chinese:
                gr.Markdown("# 🔮 JUTOR 國文段落寫作練習")
                
            # =====中文作文工具=====
            with gr.Tab("中文作文工具") as chinese_idea_tab:
                # 輸入題目、輸出靈感
                with gr.Row():
                    chinese_write_idea_prompt = """
                        你是一位國文老師,善於引導學生寫作。請根據以下的題目,幫助學生生成靈感:
                    """
                    chinese_write_idea_prompt_input = gr.TextArea(label="System Prompt", value=chinese_write_idea_prompt, visible=False)
                    with gr.Column():
                        with gr.Row():
                            gr.Markdown("# 中文作文工具")
                        with gr.Row():
                            chinese_essay_title_input = gr.TextArea(label="輸入題目")
                    with gr.Column():
                        with gr.Row():
                            chinese_essay_generate_button = gr.Button("生成靈感", variant="primary")
                        with gr.Row():
                            chinese_essay_idea_output = gr.Markdown(label="生成靈感")
                    
                    chinese_essay_generate_button.click(
                        fn=generate_chinese_essay_idea,
                        inputs=[model, chinese_write_idea_prompt_input, chinese_essay_title_input],
                        outputs=chinese_essay_idea_output
                    )

            # =====中文全文批改=====
            with gr.Tab("中文全文批改") as chinese_full_paragraph_tab:
                with gr.Row(visible=False) as chinese_full_paragraph_params:
                    chinese_full_paragraph_sys_content_input = gr.Textbox(label="System Prompt", value="You are a Chinese teacher who is practicing with me to improve my Chinese writing skill.")
                    default_user_generate_chinese_full_paragraph_evaluate_prompt =  """
                        # 請嚴格根據 instructions

                        # 先檢查是否是合理的作文或是段落,再進行評分
                        # 請確保作文或段落的內容完整,並且符合中文語法
                        # 如果是一篇亂打的文章請直接給予回饋:「這篇文章內容不完整,無法進行評分。」
                        # 如果無法進行評分 評分標準與回饋的內容跟等級,則為 X
                        
                        # Output rules:
                        1. 先給 整體評分、綜合回饋、評分標準與回饋、修改範例
                        2. 再將評分標準與回饋的內容以JSON格式輸出,並且請使用繁體中文(ZH-TW)來評分段落並輸出,用 ```json ..... ``` 包裹:
                        3. please use Chinese language (ZH-TW) to evaluate the paragraph and output use JSON format:
                        
                        EXAMPLE:
                        # 整體評分:(🔴?🟡?🟢?) 

                        # 綜合回饋
                        你的文章...............(寫出一段話,來總結這篇作文的好壞)

                        # 評分標準與回饋
                        主題與內容:B+ 你的主題很明確,講述了CSS在渲染空間上的問題及解決方案,這是一個重要而實用的話題。然而,內容相對較少,缺乏足夠的細節與實例來支撐你的觀點。建議你可以添加一些具體情境或例子,讓讀者更容易理解CSS的應用情況,例如提到常見的渲染問題以及具體的解決方法。

                        段落結構:B 你的段落結構基本清晰,但目前只有一段,這使得整體文章顯得有些單薄。建議你可以將內容分成幾個小段落,每個段落著重於不同的要點,例如一段說明問題,另一段探討解決方案,這樣整體更具條理性。

                        遣詞造句:A 你的遣詞造句大致良好,用詞得體且通順。不過可以嘗試加一些更具體的技術詞彙或示例,使文章更專業化。

                        錯別字與標點符號:A+ 你的文章沒有明顯的錯別字,並且標點符號的使用也相當正確,這點做得很好。

                        # 修改範例
                        - 原文:內容雖然簡短,但主題明確。
                          - 修改:雖然內容相對簡短,但主題表達得非常明確。
                        - 原文:缺乏實例和具體情境來支持內容。 
                          - 修改:目前缺少具體的實例及情境來支持文章的內容與主張。
                        - 原文:可以進一步擴展。
                          - 修改:可以進一步擴展來豐富內容,讓讀者更有共鳴。

                        ```json
                        {{
                            "results": {{
                                "主題與內容": {{
                                    "level": "A+",
                                    "explanation": "#中文解釋 ZH-TW"
                                }},
                                "段落結構": {{
                                    "level": "B+",
                                    "explanation": "#中文解釋 ZH-TW"
                                }},
                                "遣詞造句": {{
                                    "level": "C",
                                    "explanation": "#中文解釋 ZH-TW"
                                }},
                                "錯別字與標點符號": {{
                                    "level": "C-",
                                    "explanation": "#中文解釋 ZH-TW"
                                }}
                            }}
                        }}
                        ```

                        Restrictions:
                        - ALL the content should be in Traditional Chinese (zh-TW), it's very important.
                    """
                    user_generate_chinese_full_paragraph_evaluate_prompt = gr.Textbox(label="Paragraph evaluate Prompt", value=default_user_generate_chinese_full_paragraph_evaluate_prompt)
                with gr.Row():
                    gr.Markdown("# 輸入段落全文")
                with gr.Row():
                    with gr.Column():
                        chinese_full_paragraph_input = gr.Textbox(label="輸入段落全文", lines=5)
                    with gr.Column():
                        with gr.Row():
                            chinese_full_paragraph_evaluate_button = gr.Button("段落全文分析", variant="primary")
                        with gr.Row():
                            chinese_full_paragraph_evaluate_output_text = gr.Markdown(label="段落全文分析")
                        with gr.Row():
                            chinese_full_paragraph_evaluate_output_table = gr.Dataframe(label="段落全文分析表格", wrap=True, column_widths=[20, 15, 65], interactive=False)

                # JUTOR 段落批改與整體建議
                # with gr.Row():
                #     gr.Markdown("# JUTOR 段落批改與整體建議")
                # with gr.Row():
                #     gr.Markdown("## 修訂文法與拼字錯誤")
                # with gr.Row():
                #     with gr.Column():
                #         chinese_full_paragraph_correct_grammatical_spelling_errors_input = gr.TextArea(label="這是你的原始寫作內容,參考 JUTOR 的建議,你可以選擇是否修改:")
                #     with gr.Column():
                #         generate_chinese_full_paragraph_correct_grammatical_spelling_errors_button = gr.Button("修訂文法與拼字錯誤", variant="primary")
                #         chinese_full_paragraph_correct_grammatical_spelling_errors_output_table = gr.Dataframe(label="修訂文法與拼字錯誤", interactive=False, column_widths=[30, 30, 40])
                #         revised_chinese_full_paragraph_output = gr.Textbox(label="Revised Paragraph", show_copy_button=True, visible=False)
                #         gr.Markdown("## 修訂結果")
                #         revised_chinese_full_paragraph_diff = gr.HTML()

                # JUTOR 段落批改與整體建議
                # with gr.Row():
                #     gr.Markdown("## 段落改善建議")
                # with gr.Row():
                #     with gr.Column():
                #         chinese_full_paragraph_refine_input = gr.TextArea(label="這是你的原始寫作內容,參考 JUTOR 的建議,你可以選擇是否修改:", show_copy_button=True)
                #     with gr.Column():
                #         generate_chinese_full_paragraph_refine_button = gr.Button("段落改善建議", variant="primary")
                #         chinese_full_paragraph_refine_output_table = gr.DataFrame(label="段落改善建議", wrap=True, interactive=False)
                #         chinese_full_paragraph_refine_output = gr.HTML(label="修改建議", visible=False)
                #         gr.Markdown("## 修改結果")
                #         chinese_full_paragraph_refine_output_diff = gr.HTML()

                # 修改文章
                with gr.Row():
                    gr.Markdown("# 根據建議修改文章")
                with gr.Row(visible=False) as chinese_full_paragraph_refine_params:
                    default_user_generate_chinese_full_paragraph_refine_evaluate_prompt =  """
                        # 請嚴格根據 instructions
                        我給你兩篇文章,請進行比較跟批改,並給出建議。
                        1. 先檢查是否是合理的作文或是段落,再進行評分
                        2. 請確保作文或段落的內容完整,並且符合中文語法
                        3. 如果是一篇亂打的文章請直接給予回饋:「這篇文章內容不完整,無法進行評分。」
                        4. 如果無法進行評分 評分標準與回饋的內容跟等級,則為 X
                        
                        # Output rules:
                        1. 先給 整體評分、綜合回饋、評分標準與回饋、修改範例
                        2. 再將評分標準與回饋的內容以JSON格式輸出,並且請使用繁體中文(ZH-TW)來評分段落並輸出,用 ```json ..... ``` 包裹:
                        3. please use Chinese language (ZH-TW) to evaluate the paragraph and output use JSON format:
                        
                        EXAMPLE:
                        # 整體評分: (🔴?🟡?🟢?) 

                        # 綜合回饋(前後比較)
                        你的文章...............(寫出一段話,比較兩篇作文的差異)

                        # 評分標準與回饋
                        主題與內容:B+ 你的主題很明確,講述了CSS在渲染空間上的問題及解決方案,這是一個重要而實用的話題。然而,內容相對較少,缺乏足夠的細節與實例來支撐你的觀點。建議你可以添加一些具體情境或例子,讓讀者更容易理解CSS的應用情況,例如提到常見的渲染問題以及具體的解決方法。

                        段落結構:B 你的段落結構基本清晰,但目前只有一段,這使得整體文章顯得有些單薄。建議你可以將內容分成幾個小段落,每個段落著重於不同的要點,例如一段說明問題,另一段探討解決方案,這樣整體更具條理性。

                        遣詞造句:A 你的遣詞造句大致良好,用詞得體且通順。不過可以嘗試加一些更具體的技術詞彙或示例,使文章更專業化。

                        錯別字與標點符號:A+ 你的文章沒有明顯的錯別字,並且標點符號的使用也相當正確,這點做得很好。

                        # 修改範例
                        - 原文:內容雖然簡短,但主題明確。
                          - 修改:雖然內容相對簡短,但主題表達得非常明確。
                        - 原文:缺乏實例和具體情境來支持內容。 
                          - 修改:目前缺少具體的實例及情境來支持文章的內容與主張。
                        - 原文:可以進一步擴展。
                          - 修改:可以進一步擴展來豐富內容,讓讀者更有共鳴。

                        ```json
                        {{
                            "results": {{
                                "主題與內容": {{
                                    "level": "A+",
                                    "explanation": "#中文解釋 ZH-TW"
                                }},
                                "段落結構": {{
                                    "level": "B+",
                                    "explanation": "#中文解釋 ZH-TW"
                                }},
                                "遣詞造句": {{
                                    "level": "C",
                                    "explanation": "#中文解釋 ZH-TW"
                                }},
                                "錯別字與標點符號": {{
                                    "level": "C-",
                                    "explanation": "#中文解釋 ZH-TW"
                                }}
                            }}
                        }}
                        ```

                        Restrictions:
                        - ALL the content should be in Traditional Chinese (zh-TW), it's very important.
                    """
                    user_generate_chinese_full_paragraph_refine_evaluate_prompt = gr.Textbox(label="Paragraph evaluate Prompt", value=default_user_generate_chinese_full_paragraph_refine_evaluate_prompt)
                with gr.Row():
                    with gr.Column():
                        chinese_full_paragraph_refine_input = gr.TextArea(label="這是你的原始寫作內容,參考建議,你可以選擇是否修改:", show_copy_button=True)
                    with gr.Column():
                        with gr.Row():
                            generate_chinese_full_paragraph_refine_button = gr.Button("段落全文分析", variant="primary")
                        with gr.Row():
                            chinese_full_paragraph_refine_output_text = gr.Markdown(label="段落全文分析")
                        with gr.Row():
                            chinese_full_paragraph_refine_output_table = gr.Dataframe(label="段落全文分析表格", wrap=True, column_widths=[20, 15, 65], interactive=False)
                # 寫作完成
                with gr.Row():
                    gr.Markdown("# 寫作完成")
                with gr.Row():
                    chinese_full_paragraph_save_button = gr.Button("輸出結果", variant="primary")
                with gr.Row():
                    chinese_full_paragraph_save_output = gr.TextArea(label="最後結果")
                    chinese_full_audio_output = gr.Audio(label="音檔", type="filepath")

                # 建立歷程回顧
                with gr.Row():
                    chinese_paragraph_save_history_button = gr.Button("建立歷程回顧", variant="primary")
                with gr.Row():
                    with gr.Accordion("歷程回顧", open=False) as chinese_grapragh_practice_history_accordion:
                        gr.Markdown("<span style='color:#4e80ee'>輸入段落全文</span>")
                        chinese_full_paragraph_input_history = gr.Markdown()
                        gr.Markdown("<span style='color:#4e80ee'>段落全文分析</span>")
                        chinese_full_paragraph_evaluate_output_text_history = gr.Markdown()
                        chinese_full_paragraph_evaluate_output_table_history = gr.Dataframe(wrap=True, column_widths=[35, 15, 50], interactive=False)
                        
                        # 根據建議修改文章
                        gr.Markdown("<span style='color:#4e80ee'>根據建議修改文章 輸入</span>")
                        chinese_full_paragraph_refine_input_history = gr.Markdown()
                        gr.Markdown("<span style='color:#4e80ee'>全文分析</span>")
                        chinese_full_paragraph_refine_output_text_history = gr.Markdown()
                        chinese_full_paragraph_refine_output_table_history = gr.Dataframe(interactive=False, wrap=True, column_widths=[30, 30, 40])

                        gr.Markdown("<span style='color:#4e80ee'>修改結果</span>")
                        chinese_full_paragraph_save_output_history = gr.Markdown()

                    chinese_paragraph_save_history_button.click(
                        fn=generate_chinese_paragraph_practice_history,
                        inputs=[
                            user_data,
                            session_timestamp,
                            request_origin,
                            chinese_full_paragraph_input,
                            chinese_full_paragraph_evaluate_output_text,
                            chinese_full_paragraph_evaluate_output_table,
                            chinese_full_paragraph_refine_input,
                            chinese_full_paragraph_refine_output_text,
                            chinese_full_paragraph_refine_output_table,
                            chinese_full_paragraph_save_output
                        ],
                        outputs=[
                            chinese_full_paragraph_input_history,
                            chinese_full_paragraph_evaluate_output_text_history,
                            chinese_full_paragraph_evaluate_output_table_history,
                            chinese_full_paragraph_refine_input_history,
                            chinese_full_paragraph_refine_output_text_history,
                            chinese_full_paragraph_refine_output_table_history,
                            chinese_full_paragraph_save_output_history
                        ]
                    ).then(
                        fn=update_history_accordion,
                        inputs=[],
                        outputs=[chinese_grapragh_practice_history_accordion]
                    )

                chinese_full_paragraph_evaluate_button.click(
                    fn=get_chinese_paragraph_evaluate_content,
                    inputs=[model, chinese_full_paragraph_sys_content_input, chinese_full_paragraph_input, user_generate_chinese_full_paragraph_evaluate_prompt],
                    outputs=[chinese_full_paragraph_evaluate_output_text, chinese_full_paragraph_evaluate_output_table]
                ).then(
                    fn=duplicate_element,
                    inputs=[chinese_full_paragraph_input],
                    outputs=chinese_full_paragraph_refine_input
                )

                generate_chinese_full_paragraph_refine_button.click(
                    fn=get_chinese_paragraph_refine_evaluate_content,
                    inputs=[model, chinese_full_paragraph_sys_content_input, chinese_full_paragraph_input, chinese_full_paragraph_refine_input, user_generate_chinese_full_paragraph_refine_evaluate_prompt],
                    outputs=[chinese_full_paragraph_refine_output_text, chinese_full_paragraph_refine_output_table]
                )

                chinese_full_paragraph_save_button.click(
                    fn=paragraph_save_and_tts,
                    inputs=[chinese_full_paragraph_refine_input],
                    outputs=[chinese_full_paragraph_save_output, chinese_full_audio_output]
                )

            # === 歷程 session 列表
            with gr.Tab("歷程回顧"):
                with gr.Accordion("📚 中文段落練習歷程回顧", open=False) as chinese_grapragh_practice_logs_accordion:
                    # 變數名稱就是加上 logs
                    with gr.Row():
                        with gr.Column(scale=1):
                            # 取得中文段落練習 log from GCS
                            chinese_paragraph_practice_logs_type = gr.State("jutor_write_chinese_full_paragraph_evaluation")
                            get_chinese_paragraph_practice_logs_button = gr.Button("👉 取得中文段落寫作練習歷程", variant="primary")    
                            chinese_paragraph_practice_logs_session_list = gr.Radio(label="歷程時間列表")
                        with gr.Column(scale=3, variant="compact"):
                            gr.Markdown("<span style='color:#4e80ee'>輸入段落全文</span>")
                            chinese_full_paragraph_input_history_log = gr.Markdown()
                            gr.Markdown("<span style='color:#4e80ee'>段落全文分析</span>")
                            chinese_full_paragraph_evaluate_output_text_history_log = gr.Markdown()
                            chinese_full_paragraph_evaluate_output_table_history_log = gr.Dataframe(wrap=True, column_widths=[35, 15, 50], interactive=False)

                            gr.Markdown("<span style='color:#4e80ee'>段落改善建議 輸入</span>")
                            chinese_full_paragraph_refine_input_history_log = gr.Markdown()
                            gr.Markdown("<span style='color:#4e80ee'>段落改善建議</span>")
                            chinese_full_paragraph_refine_output_text_history_log = gr.Markdown()
                            chinese_full_paragraph_refine_output_table_history_log = gr.Dataframe(wrap=True, interactive=False, column_widths=[30, 30, 40])

                            gr.Markdown("<span style='color:#4e80ee'>修改結果</span>")
                            chinese_full_paragraph_save_output_history_log = gr.Markdown()

                            get_chinese_paragraph_practice_logs_button.click(
                                fn=get_logs_sessions,
                                inputs=[user_data, chinese_paragraph_practice_logs_type],
                                outputs=[chinese_paragraph_practice_logs_session_list]
                            )

                            chinese_paragraph_practice_logs_session_list.select(
                                fn=get_chinese_paragraph_practice_log_session_content,
                                inputs=[chinese_paragraph_practice_logs_session_list],
                                outputs=[
                                    chinese_full_paragraph_input_history_log,
                                    chinese_full_paragraph_evaluate_output_text_history_log,
                                    chinese_full_paragraph_evaluate_output_table_history_log,
                                    chinese_full_paragraph_refine_input_history_log,
                                    chinese_full_paragraph_refine_output_text_history_log,
                                    chinese_full_paragraph_refine_output_table_history_log,
                                    chinese_full_paragraph_save_output_history_log
                                ]
                            )
                            
                


    demo.load(
        init_params, 
        inputs =[],
        outputs = [
            admin_group,
            session_timestamp,
            request_origin,
            assignment_id_input,
            english_group,
            chinese_group
        ]
    )

demo.launch(server_name="0.0.0.0", server_port=7860)