File size: 53,164 Bytes
15b9da3
46f5603
c775910
9a7a5d5
 
 
a0a3ddc
a6fb9ef
 
2a3dc52
 
 
 
 
 
 
 
 
 
 
15b9da3
029fc0c
f4a1918
78f5c78
d947472
46f5603
 
 
c71a877
 
 
 
 
46f5603
 
 
 
 
 
 
 
 
2a3dc52
46f5603
 
029fc0c
2a3dc52
 
 
46f5603
500c53b
 
2a3dc52
 
83627a0
46f5603
8a473de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
500c53b
8a473de
500c53b
 
 
 
 
 
 
 
8a473de
11b1dbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
877f289
 
11b1dbb
 
 
 
877f289
11b1dbb
 
 
500c53b
 
 
 
 
 
 
 
 
 
f7092d6
500c53b
 
 
 
 
 
 
 
 
 
 
 
 
f7092d6
 
500c53b
11b1dbb
f7092d6
c9e97ad
daa5f8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e56d3c5
daa5f8e
e56d3c5
 
 
 
daa5f8e
cc83ab8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
466d591
cc83ab8
 
 
466d591
 
 
cc83ab8
af1d454
 
 
 
12a83ad
 
 
 
 
169fbfd
12a83ad
 
c1ee647
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a7a5d5
c1ee647
 
 
 
 
 
9a7a5d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1ee647
f35c083
19c63ff
 
 
 
f35c083
19c63ff
 
 
 
 
 
 
 
 
 
 
9a7a5d5
19c63ff
 
 
 
 
9a7a5d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19c63ff
 
 
9a7a5d5
 
 
f35c083
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a7a5d5
 
20da85e
 
c2544ea
20da85e
c2544ea
 
 
 
 
 
 
20da85e
a6fb9ef
 
20da85e
a6fb9ef
 
20da85e
c2544ea
 
20da85e
c2544ea
 
 
 
6e5cbf8
e4d8ee5
500c53b
46f5603
 
f31eb9e
 
 
c71a877
e4d8ee5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
500c53b
 
 
 
e4d8ee5
 
2a3dc52
 
e4d8ee5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a3dc52
e4d8ee5
83627a0
2a3dc52
 
 
 
83627a0
 
 
 
 
 
 
500c53b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e56d3c5
500c53b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e56d3c5
f1f8df0
 
 
 
 
 
e56d3c5
 
f1f8df0
 
e56d3c5
 
 
 
 
9a7a5d5
e56d3c5
 
 
f1f8df0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e56d3c5
 
f1f8df0
e56d3c5
 
 
 
 
500c53b
af1d454
 
 
 
 
 
 
 
466d591
 
af1d454
 
466d591
 
 
 
 
 
 
 
 
 
af1d454
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
466d591
af1d454
500c53b
af1d454
 
 
 
 
500c53b
af1d454
 
 
 
7beeee7
af1d454
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140a695
af1d454
140a695
500c53b
af1d454
 
 
 
 
 
 
 
 
500c53b
140a695
af1d454
 
 
 
 
 
 
 
 
 
 
9a7a5d5
 
af1d454
 
9a7a5d5
 
af1d454
 
 
 
 
 
 
 
 
 
 
 
 
9a7a5d5
 
af1d454
 
 
 
 
 
 
 
 
 
 
 
 
9a7a5d5
 
af1d454
 
 
 
 
 
 
 
 
 
 
 
 
9a7a5d5
 
af1d454
 
 
 
 
 
9a7a5d5
 
af1d454
 
9a7a5d5
 
 
af1d454
 
 
 
 
 
 
 
 
 
140a695
 
 
9a7a5d5
46f5603
9a7a5d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f35c083
 
 
 
f7c7167
f35c083
b08769a
9a7a5d5
ef415ec
f35c083
 
 
 
 
 
9a7a5d5
 
f35c083
 
 
 
f768d7d
f35c083
12037a8
 
6e5cbf8
 
 
 
e2e704a
6e5cbf8
46f5603
d947472
c71a877
 
 
 
 
 
 
 
500c53b
46f5603
 
8a473de
 
 
 
 
 
 
 
 
 
 
 
 
 
11b1dbb
 
 
 
 
 
 
 
 
 
 
 
dad95ce
11b1dbb
 
daa5f8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc83ab8
 
 
 
 
 
 
 
 
 
 
 
 
1d7518e
cc83ab8
 
af1d454
12a83ad
0fea6e9
 
 
af1d454
0fea6e9
 
 
 
 
9a7a5d5
19c63ff
f35c083
 
 
 
 
 
 
6e5cbf8
 
 
 
8de85cd
6e5cbf8
06ae453
6e5cbf8
ef458b0
20da85e
 
 
f35c083
 
46f5603
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
import os
import gradio as gr
from openai import OpenAI

from difflib import Differ

import json
import tempfile

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"]
else:
    OPEN_AI_KEY = os.getenv("OPEN_AI_KEY")

OPEN_AI_CLIENT = OpenAI(api_key=OPEN_AI_KEY)


def generate_topics(model, max_tokens, sys_content, scenario, eng_level, user_generate_topics_prompt):
    """
    根据系统提示和用户输入的情境及主题,调用OpenAI API生成相关的主题句。
    """
    user_content = f"""
        scenario is {scenario}
        english level is {eng_level}
        {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" }
    }

    response = OPEN_AI_CLIENT.chat.completions.create(**request_payload)
    content = response.choices[0].message.content
    topics = json.loads(content)["topics"]
    topics_text = json.dumps(topics)

    gr_update = gr.update(visible=False, value=topics_text)
    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,
    }

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

    points = json.loads(content)["points"]
    points_text = json.dumps(points)

    gr_update = gr.update(visible=False, value=points_text)
    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生成相关的主题句及其合理性解释。
    """
    user_content = f"""
        scenario is {scenario}
        english level is {eng_level}
        topic is {topic}
        points is {points}
        {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
    }

    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_text = json.dumps(json_content, ensure_ascii=False)

    gr_update = gr.update(visible=False, value=topic_sentences_text)
    return gr_update

def update_topic_sentence_input(topic_sentences_radio, topic_sentence_output):
    selected_topic_sentence = topic_sentences_radio
    topic_sentence_output = json.loads(topic_sentence_output)
    topic_sentence_input = ""
    for ts in topic_sentence_output:
        if ts["topic-sentence"] == selected_topic_sentence:
            appropriate = "O 適合" if ts["appropriate"] == "Y" else "X 不適合"
            border_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>你選了主題句:{selected_topic_sentence}</p>
                <p>是否適當:{appropriate}</p>
                <p>原因:{ts['reason']}</p>
            </div>
            """

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

    return topic_sentence_input, 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,
    }

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

    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" }
    }

    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])

    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(paragraph, user_generate_paragraph_evaluate_prompt):
    """
    根据用户输入的段落,调用OpenAI API生成相关的段落分析。
    """
    user_content = f"""
        paragraph is {paragraph}
        {user_generate_paragraph_evaluate_prompt}
    """
    messages = [
        {"role": "system", "content": paragraph},
        {"role": "user", "content": user_content}
    ]

    response_format = { "type": "json_object" }

    request_payload = {
        "model": "gpt-3.5-turbo",
        "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_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)

    return gr_update


def generate_correct_grammatical_spelling_errors(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": paragraph},
        {"role": "user", "content": user_content}
    ]
    response_format = { "type": "json_object" }
    request_payload = {
        "model": "gpt-3.5-turbo",
        "messages": messages,
        "max_tokens": 1000,
        "response_format": response_format
    }

    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)
    reverse_paragraph_gr_update = gr.update(value=data["Revised Paragraph"])
    
    return corrections_list_gr_update, reverse_paragraph_gr_update

def diff_texts(text1, text2):
    user_content = f"""
        original text is {text1}
        revised text is {text2}
        please check the differences between the original text and the revised text.
        output a HTML string only
        highlight the differences with yellow background color

        restriction:
        - no more explanation either no more extra non-relation sentences.

        EXAMPLE:
        <p>Eating fruits and vegetables <span style="background-color:yellow;">are</span> important for our health. Fruits and vegetables give us the vitamins we need. They help our bodies stay strong and fight sickness. Eating them every day makes us feel better and have more energy. So, eating fruits and vegetables <span style="background-color:yellow;">keep</span> us healthy.</p>
    """
    messages = [
        {"role": "user", "content": user_content}
    ]
    request_payload = {
        "model": "gpt-3.5-turbo",
        "messages": messages,
        "max_tokens": 1000,
    }

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

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

    return content

def update_paragraph_correct_grammatical_spelling_errors_input(paragraph):
    return paragraph

def generate_refine_paragraph(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": paragraph},
        {"role": "user", "content": user_content}
    ]

    response_format = { "type": "json_object" }

    request_payload = {
        "model": "gpt-3.5-turbo",
        "messages": messages,
        "max_tokens": 500,
        "response_format": response_format
    }

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

    return content



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

with gr.Blocks(theme=gr.themes.Soft(primary_hue=gr.themes.colors.blue, secondary_hue=gr.themes.colors.orange)) as demo:
    # basic inputs 主題與情境
    with gr.Row():
        with gr.Column():
            model = gr.Radio(["gpt-4o", "gpt-3.5-turbo"], label="Model", value="gpt-4o", visible=False)
            max_tokens = gr.Slider(minimum=50, maximum=4000, value=4000, label="Max Tokens", visible=False)
            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.", visible=False)
            
            with gr.Row():
                eng_level_input = gr.Radio(["beginner", "intermediate", "advanced"], label="English Level", value="beginner")
            with gr.Row():
                gr.Markdown("# Step 1. 你今天想練習寫什麼呢?")
            with gr.Row():
                gr.Markdown("""## 寫作的主題與讀者、寫作的目的、文章的風格、長度、範圍、以及作者的專業知識等都有關係。因為不容易找主題,所以利用兩階段方式來找主題。特為較無英文寫作經驗的  基礎級使用者 提供多種大範圍情境,待篩選情境後,下一步再來決定明確的主題。""")
            with gr.Row():
                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_input = gr.Dropdown(label="先選擇一個大範圍的情境:", choices=scenario_values, value="Health")
    
    # Step 2. 確定段落主題
    with gr.Row():
        with gr.Column():      
            with gr.Row():
                gr.Markdown("# Step 2. 確定段落主題")
            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 = """
                    Give me 10 topics relevant to Scenario, 
                    for a paragraph. Just the topics, no explanation, use simple English language. 
                    Make sure the vocabulary you use is at english 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="選擇合適的主題:", interactive=False)
                with gr.Column():
                    generate_topics_button = gr.Button("使用 🪄 JUTOR 產生 10 個段落主題,再挑選一個來練習吧!", variant="primary")
                    topic_output = gr.Textbox(label="AI Generated Topic 主題", visible=True, value=[])

                    @gr.render(inputs=topic_output)
                    def render_topics(topics):    
                        topics_list = json.loads(topics)
                        topic_radio = gr.Radio(topics_list, label="Topics", elem_id="topic_button")
                        topic_radio.select(
                            fn=update_topic_input, 
                            inputs=[topic_radio], 
                            outputs=[topic_input]
                        )
                        return topic_radio
    # Step 3. 寫出段落要點
    with gr.Row():
        with gr.Column():
            with gr.Row() as points_params:
                default_generate_points_prompt = """
                    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 3. 寫出段落要點")
            with gr.Row():
                gr.Markdown("## 根據情境、主題,可以視主題不同,試著寫出 1-3 個要點。段落要點務必選擇比較相關的,才好寫入一個段落。不相關的要點會讓段落缺乏連貫一致性。")
            with gr.Row():
                gr.Markdown("### `基礎級使用者` 先從 1 個要點開始練習,比較好掌握;等熟悉之後在 `實力級`,就可選擇 2-3 個要點來發揮。")
            with gr.Row():
                with gr.Column():
                    points_input = gr.Textbox(label="#1 要點/關鍵字")
                with gr.Column():
                    generate_points_button = gr.Button("找尋靈感?使用 🪄 JUTOR 產生要點/關鍵字", variant="primary")
                    points_output = gr.Textbox(label="AI Generated Points 要點", visible=True, value=[])

                    @gr.render(inputs=points_output)
                    def render_points(points):    
                        points_list = json.loads(points)
                        points_radio = gr.Radio(points_list, label="Points", elem_id="point_button")
                        points_radio.select(
                            fn=update_points_input, 
                            inputs=[points_radio], 
                            outputs=[points_input]
                        )
                        return points_radio
    # Step 4. 選定主題句
    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 4. 選定主題句")
            with gr.Row():      
                with gr.Column():
                    gr.Markdown("## 主題句(Topic Sentence)是一個段落中最重要的句子,它介紹主題並含括該段落的所有要點,引起讀者的興趣。就像藍圖一樣,指出客廳、廚房、臥室等位置。")
                    gr.Markdown("## 主題句通常位於段落的開頭,幫助讀者迅速理解段落的內容。如果沒有主題句,段落的架構及內容的一致性及連貫性就會受影響。")
                    gr.Markdown("## 主題句的範圍,應能適當含括你剛才決定的各個要點,範圍不要太大,以致無法在一個段落清楚説明,也不能太小,無法含括段落的所有要點。")
                with gr.Column():
                    with gr.Accordion("參考指引:合適的主題句?", open=False):
                        gr.Markdown("""舉例,情境是 `School & Learning`,段落主題是 `Time Management`,那麼 `Balancing school work and leisure time is a crucial aspect of effective time management` 就是合適的主題句,因為它清楚點出該段落將説明有效運用時間來讓課業及娛樂取得平衡。""")
            with gr.Row():
                with gr.Column():
                    topic_sentence_input = gr.Textbox(label="Topic Sentences")
                with gr.Column():
                    generate_topic_sentences_button = gr.Button("生成並在下面 3 個 JUTOR 產生的主題句中,選出一個最合適的", variant="primary")
                    topic_sentence_output = gr.Textbox(label="AI Generated Topic Sentences 主題句", value=[])
                
                    @gr.render(inputs=topic_sentence_output)
                    def render_topic_sentences(topic_sentences):   
                        # Parsing the JSON string to a list
                        topic_sentences_list = json.loads(topic_sentences)
                        
                        # Extracting only the topic sentences for the radio button options
                        radio_options = [ts["topic-sentence"] for ts in topic_sentences_list]
                        
                        # Creating the radio button element
                        topic_sentences_radio = gr.Radio(radio_options, label="Topic Sentences", elem_id="topic_sentence_button")
                        topic_sentences_suggestions = gr.HTML()                        # Setting up the action when a radio button is selected
                        topic_sentences_radio.select(
                            fn=update_topic_sentence_input, 
                            inputs=[topic_sentences_radio, topic_sentence_output], 
                            outputs= [topic_sentence_input, topic_sentences_suggestions]
                        )

                        return topic_sentences_radio
    # Step 5.寫出完整段落
    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.

                    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 5.寫出完整段落")
            with gr.Row():
                gr.Markdown("## 請根據主題句,練習寫出 「支持句」及「結論句」來完成一個完整的段落。")
            with gr.Row():
                with gr.Column():
                    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():
                    gr.Markdown("### 寫出關於 focus 的支持句")
                    supporting_sentences_input = gr.Textbox(label="Supporting Sentences")
                with gr.Column():
                    generate_supporting_sentences_button = gr.Button("讓 JUTOR 產生例句,幫助你撰寫支持句。", variant="primary")
                    supporting_sentences_output = gr.Radio(choices=[],label="AI Generated Supporting Sentences 支持句", elem_id="supporting_sentences_button")
                
                    supporting_sentences_output.select(
                        fn=update_supporting_sentences_input, 
                        inputs=[supporting_sentences_output], 
                        outputs= [supporting_sentences_input]
                    )

    # Step 6. 寫出結論句
    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 6. 寫出結論句")
            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(choices=[], label="AI Generated Conclusion Sentence 結論句")

                    conclusion_sentence_output.select(
                        fn=update_conclusion_sentence_input, 
                        inputs=[conclusion_sentence_output], 
                        outputs= [conclusion_sentence_input]
                    )

    # Step 7. 段落確認與修訂
    with gr.Row():
        with gr.Column():
            with gr.Row():
                gr.Markdown("# Step 7. 段落確認與修訂")
            with gr.Row():
                with gr.Column():
                    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():
                paragraph_output = gr.Textbox(label="完整段落", show_copy_button=True)

                generate_paragraph_button.click(
                    fn=generate_paragraph,
                    inputs=[
                        topic_sentence_input,
                        supporting_sentences_input, 
                        conclusion_sentence_input
                    ],
                    outputs=paragraph_output
                )

            with gr.Row() 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)
    
    # 修訂文法與拼字錯誤
    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. 
                    - 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. 
                    - Guidelines for Length and Complexity: Please keep explanations concise and straightforward, 
                    - Avoiding overly technical language.
                    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 8. 修訂文法與拼字錯誤")
            with gr.Row():
                with gr.Column():
                    gr.Markdown("## 修訂文法與拼字錯誤(Correct Grammatical and Spelling Errors)")
                with gr.Column():
                    with gr.Accordion("參考指引:AI 的混淆狀況?", open=False):
                        gr.Markdown("""
                            - 段落寫作的過程,如果全程採用 JUTOR 的建議例句,則不會有文法與拼字錯誤。JUTOR 有時後仍會挑出一些字詞修訂,並非原本字詞錯誤,而是改換不同說法,你可以參考。
                            - 若是自行完成段落寫作,則不會發生自我修訂的混淆狀況。
                        """)
            with gr.Row():
                with gr.Column():
                    paragraph_correct_grammatical_spelling_errors_input = gr.Textbox(label="這是你的原始寫作內容,參考 JUTOR 的改正,你可以選擇是否修改:")
                with gr.Column():
                    generate_correct_grammatical_spelling_errors_button = gr.Button("JUTOR 修訂", variant="primary")
                    correct_grammatical_spelling_errors_output = gr.Dataframe(label="修訂文法與拼字錯誤")
                    revised_paragraph_output = gr.Textbox(label="Revised Paragraph", show_copy_button=True)
                    revised_paragraph_diff = gr.HTML()

                    generate_correct_grammatical_spelling_errors_button.click(
                        fn=generate_correct_grammatical_spelling_errors,
                        inputs=[
                            eng_level_input,
                            paragraph_output,
                            user_correct_grammatical_spelling_errors_prompt,
                        ],
                        outputs=[
                            correct_grammatical_spelling_errors_output, 
                            revised_paragraph_output
                        ]
                    ).then(
                        fn=diff_texts,
                        inputs=[paragraph_output, revised_paragraph_output],
                        outputs=revised_paragraph_diff
                    ).then(
                        fn=update_paragraph_correct_grammatical_spelling_errors_input,
                        inputs=[paragraph_output],
                        outputs=paragraph_correct_grammatical_spelling_errors_input
                    )

            gr.Markdown("## 10. Refine Paragraph 段落改善建議")
            default_user_refine_paragraph_prompt = """
                I need assistance with revising a paragraph. Please "Refine" the "Revised Version 1" and immediately "Provide Explanations" for each suggestion you made. 
                - Revised Version 1 (for correction): paragraph_ai_modification(split by punctuation mark)
                - 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, 
                avoiding overly technical language.
                The response should strictly be in the below JSON format and nothing else:
                {
                "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)
            generate_refine_paragraph_button = gr.Button("Refine Paragraph")
            refine_output = gr.Textbox(label="Refine Paragraph 段落改善建議", show_copy_button=True)
            paragraph_refine_input = gr.Textbox(label="Paragraph 段落改善", show_copy_button=True)

            gr.Markdown("## 11. Save and Share")
            paragraph_save_button = gr.Button("Save and Share")
            paragraph_save_output = gr.Textbox(label="Save and Share")
            audio_output = gr.Audio(label="Generated Speech", type="filepath")

    generate_topics_button.click(
        fn=generate_topics,
        inputs=[
            model, 
            max_tokens, 
            sys_content_input, 
            scenario_input, 
            eng_level_input,
            user_generate_topics_prompt
        ],
        outputs=[topic_output]
    )

    generate_points_button.click(
        fn=generate_points,
        inputs=[
            model, 
            max_tokens, 
            sys_content_input, 
            scenario_input, 
            eng_level_input,
            topic_input,
            user_generate_points_prompt
        ],
        outputs=points_output
    )

    generate_topic_sentences_button.click(
        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
    )

    generate_supporting_sentences_button.click(
        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
    )

    generate_conclusion_sentence_button.click(
        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
    )

    

    generate_paragraph_evaluate_button.click(
        fn=generate_paragraph_evaluate,
        inputs=[
            paragraph_output,
            user_generate_paragraph_evaluate_prompt
        ],
        outputs=paragraph_evaluate_output
    )

    

    generate_refine_paragraph_button.click(
        fn=generate_refine_paragraph,
        inputs=[
            eng_level_input,
            paragraph_correct_grammatical_spelling_errors_input,
            user_refine_paragraph_prompt
        ],
        outputs=refine_output
    )

    paragraph_save_button.click(
        fn=paragraph_save_and_tts,
        inputs=[
            paragraph_refine_input
        ],
        outputs=[
            paragraph_save_output, 
            audio_output
        ]
    )

demo.launch()