File size: 40,455 Bytes
55e027c
4f6b126
 
 
 
 
 
 
 
 
 
 
a093438
c98021c
 
 
 
49612ba
c515693
77dbcc7
ce202f9
03f9025
4333f18
 
9186425
 
9c7114f
4f6b126
90ce14b
4f6b126
 
90ce14b
9186425
eb4ccf0
03db1ff
6bb9d92
4f6b126
29d1af8
39dd701
77f2c42
ce202f9
3e8d848
6848520
4f6b126
 
9186425
 
4f6b126
 
fe3346f
bde4648
fe3346f
 
 
 
 
4f6b126
41d7a7a
6848520
 
 
0b100e6
 
 
0af8496
 
 
 
 
 
 
 
 
0b100e6
 
8154a1c
 
 
 
f4b17c4
8154a1c
 
 
 
0b100e6
8154a1c
4f6b126
 
8154a1c
4f6b126
 
30e4bc9
 
 
0b100e6
8154a1c
 
 
 
 
 
 
 
 
 
8beda5f
 
4f6b126
8beda5f
6848520
657f21e
 
 
 
 
d86a58c
f36945f
a294e14
762e19e
 
4f6b126
 
 
762e19e
679aef4
 
762e19e
bcb6446
 
 
4f6b126
f36945f
762e19e
d86a58c
 
 
 
762e19e
d86a58c
18ed09e
762e19e
18ed09e
 
1c2b5d2
ec40641
 
 
 
d58672c
f31a8f7
ec40641
1c2b5d2
 
 
 
d86a58c
1c2b5d2
 
 
 
 
 
4f6b126
 
 
 
 
 
18ed09e
 
 
 
 
4f6b126
 
18ed09e
 
 
4f6b126
 
18ed09e
 
4f6b126
 
18ed09e
4f6b126
 
e22b7aa
a294e14
4f6b126
 
a294e14
f31a8f7
4f6b126
 
a294e14
ec40641
 
 
 
 
 
 
c73c755
ec40641
c73c755
ec40641
 
 
 
 
 
 
 
 
 
 
4f6b126
 
ec40641
 
 
 
 
4f6b126
 
ec40641
 
 
 
 
d58672c
4f6b126
 
 
 
 
 
ec40641
 
 
 
c73c755
4f6b126
 
8b5c04c
f6180c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c73c755
4f6b126
 
52fd957
8b5c04c
6848520
8b5c04c
 
 
 
f31a8f7
4f6b126
 
8b5c04c
 
 
 
 
 
 
 
 
 
 
4f6b126
 
8b5c04c
4f6b126
 
8b5c04c
 
 
 
 
 
8a9679a
d86a58c
8b5c04c
 
 
 
 
d86a58c
8b5c04c
 
4f6b126
 
8b5c04c
4f6b126
 
6487726
 
 
 
 
73da7f9
6487726
4f6b126
 
8b5c04c
 
ec40641
4f6b126
 
8b5c04c
 
 
 
 
 
 
 
 
 
 
 
 
f6180c8
8b5c04c
 
 
 
 
 
 
 
 
 
 
 
 
4f6b126
 
f31a8f7
4f6b126
 
f36945f
 
f6180c8
 
f31a8f7
4f6b126
 
f6180c8
f31a8f7
4f6b126
 
6848520
f6180c8
4f6b126
 
 
 
 
 
6848520
f6180c8
4f6b126
 
 
 
 
 
 
 
6848520
f6180c8
 
4f6b126
 
 
 
f4e0fdd
c0a09a7
 
ce858fc
1a233c9
c0a09a7
 
 
 
 
 
4f6b126
 
c0a09a7
 
e741d7d
c0a09a7
d86a58c
4f6b126
 
 
 
 
 
 
 
8a9679a
ea9cb69
4f6b126
ea9cb69
4f6b126
ea9cb69
4f6b126
 
ea9cb69
4f6b126
 
 
 
c01b032
9869ac7
d7487c3
9869ac7
 
d7487c3
9869ac7
d7487c3
4f6b126
d7487c3
2c5812c
90ce14b
2c5812c
90ce14b
6bb9d92
b8f3115
 
 
cff018d
be28103
b8f3115
77f2c42
b8f3115
 
4333f18
2c5812c
6bb9d92
 
 
 
2c5812c
 
 
 
 
 
 
6bb9d92
 
 
 
4f6b126
 
2c5812c
73d933e
a3e8551
4f6b126
 
77f2c42
 
 
90ce14b
8154a1c
77f2c42
a3e8551
2c5812c
fce5dd0
8154a1c
fce5dd0
 
6487726
 
 
 
 
 
 
2c5812c
90ce14b
2c5812c
4f6b126
6487726
a3e8551
6bb9d92
6487726
2572cda
4f6b126
6487726
a3e8551
4333f18
6487726
2572cda
4f6b126
 
 
 
03f9025
b8f3115
90ce14b
 
8154a1c
b8f3115
5f36649
ab6c9c5
4333f18
2c5812c
90ce14b
b8f3115
90ce14b
b8f3115
 
77f2c42
 
be28103
b8f3115
77f2c42
b8f3115
2c5812c
a3e8551
4333f18
786c822
90ce14b
 
77f2c42
786c822
 
b8f3115
90ce14b
 
77f2c42
 
b8f3115
4333f18
12a17d8
 
 
 
 
 
 
 
 
 
 
 
 
 
8783eb5
a9516c8
c9610d9
4f6b126
 
c8fd9d2
4f6b126
 
 
 
 
 
 
 
4333f18
5d31dec
4f6b126
 
 
 
03db1ff
b8f3115
 
 
 
 
 
 
 
 
 
 
4333f18
5d31dec
8beda5f
ba32a82
90ce14b
8beda5f
b8f3115
e741d7d
b8f3115
 
90ce14b
 
8beda5f
b8f3115
 
fce5dd0
4f6b126
 
 
 
 
 
 
8154a1c
e5adc30
 
4f6b126
27fbd0c
30e4bc9
27fbd0c
8154a1c
 
 
 
 
6c11728
9813f91
4f6b126
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9813f91
f4e0fdd
4f6b126
 
 
 
90ce14b
4f6b126
 
 
 
 
 
 
 
 
 
 
 
 
 
f2c2a56
f4e0fdd
5e4ca56
f4e0fdd
4d6c637
 
 
 
 
 
 
 
 
 
 
 
8b5c04c
6c11728
6b4e8ea
 
 
 
 
 
 
8a9679a
 
d86a58c
8a9679a
 
 
 
 
d86a58c
8a9679a
 
 
4f6b126
6848520
8154a1c
6848520
39dd701
6848520
6b4e8ea
8a9679a
b8f3115
 
 
 
 
f744196
ce202f9
eab29c1
022b9a0
5550401
d1cfc73
bfac445
d1cfc73
 
 
29b4859
9186425
4f6b126
d1cfc73
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
# -*- coding:utf-8 -*-
from modules.models.models import get_model
from modules.train_func import *
from modules.repo import *
from modules.webui import *
from modules.overwrites import *
from modules.presets import *
from modules.utils import *
from modules.config import *
from modules import config
import gradio as gr
import colorama
import logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s",
)


logging.getLogger("httpx").setLevel(logging.WARNING)

gr.Chatbot._postprocess_chat_messages = postprocess_chat_messages
gr.Chatbot.postprocess = postprocess

# with open("web_assets/css/ChuanhuChat.css", "r", encoding="utf-8") as f:
#     ChuanhuChatCSS = f.read()


def create_new_model():
    return get_model(model_name=MODELS[DEFAULT_MODEL], access_key=my_api_key)[0]


with gr.Blocks(theme=small_and_beautiful_theme) as demo:
    user_name = gr.Textbox("", visible=False)
    promptTemplates = gr.State(load_template(get_template_names()[0], mode=2))
    user_question = gr.State("")
    assert type(my_api_key) == str
    user_api_key = gr.State(my_api_key)
    current_model = gr.State()

    topic = gr.State(i18n("未命名对话历史记录"))

    with gr.Row(elem_id="chuanhu-header"):
        gr.HTML(get_html("header_title.html").format(
            app_title=CHUANHU_TITLE), elem_id="app-title")
        status_display = gr.Markdown(get_geoip(), elem_id="status-display")
    with gr.Row(elem_id="float-display"):
        user_info = gr.Markdown(
            value="getting user info...", elem_id="user-info")
        update_info = gr.HTML(get_html("update.html").format(
            current_version=repo_tag_html(),
            version_time=version_time(),
            cancel_btn=i18n("取消"),
            update_btn=i18n("更新"),
            seenew_btn=i18n("详情"),
            ok_btn=i18n("好"),
        ), visible=check_update)

    with gr.Row(equal_height=True, elem_id="chuanhu-body"):

        with gr.Column(elem_id="menu-area"):
            with gr.Column(elem_id="chuanhu-history"):
                with gr.Box():
                    with gr.Row(elem_id="chuanhu-history-header"):
                        with gr.Row(elem_id="chuanhu-history-search-row"):
                            with gr.Column(min_width=150, scale=2):
                                historySearchTextbox = gr.Textbox(show_label=False, container=False, placeholder=i18n(
                                    "搜索(支持正则)..."), lines=1, elem_id="history-search-tb")
                            with gr.Column(min_width=52, scale=1, elem_id="gr-history-header-btns"):
                                uploadFileBtn = gr.UploadButton(
                                    interactive=True, label="", file_types=[".json"], elem_id="gr-history-upload-btn")
                                historyRefreshBtn = gr.Button("", elem_id="gr-history-refresh-btn")
                            

                    with gr.Row(elem_id="chuanhu-history-body"):
                        with gr.Column(scale=6, elem_id="history-select-wrap"):
                            historySelectList = gr.Radio(
                                label=i18n("从列表中加载对话"),
                                choices=get_history_names(),
                                value=get_first_history_name(),
                                # multiselect=False,
                                container=False,
                                elem_id="history-select-dropdown"
                            )
                        with gr.Row(visible=False):
                            with gr.Column(min_width=42, scale=1):
                                historyDeleteBtn = gr.Button(
                                    i18n("🗑️"), elem_id="gr-history-delete-btn")
                            with gr.Column(min_width=42, scale=1):
                                historyDownloadBtn = gr.Button(
                                    i18n("⏬"), elem_id="gr-history-download-btn")
                            with gr.Column(min_width=42, scale=1):
                                historyMarkdownDownloadBtn = gr.Button(
                                    i18n("⤵️"), elem_id="gr-history-mardown-download-btn")
                    with gr.Row(visible=False):
                        with gr.Column(scale=6):
                            saveFileName = gr.Textbox(
                                show_label=True,
                                placeholder=i18n("设置文件名: 默认为.json,可选为.md"),
                                label=i18n("设置保存文件名"),
                                value=i18n("对话历史记录"),
                                elem_classes="no-container"
                                # container=False,
                            )
                        with gr.Column(scale=1):
                            renameHistoryBtn = gr.Button(
                                i18n("💾 Rename Chat"), elem_id="gr-history-save-btn")
                            exportMarkdownBtn = gr.Button(
                                i18n("📝 Export as Markdown"), elem_id="gr-markdown-export-btn")

            with gr.Column(elem_id="chuanhu-menu-footer"):
                with gr.Row(elem_id="chuanhu-func-nav"):
                    gr.HTML(get_html("func_nav.html"))
                # gr.HTML(get_html("footer.html").format(versions=versions_html()), elem_id="footer")
                # gr.Markdown(CHUANHU_DESCRIPTION, elem_id="chuanhu-author")

        with gr.Column(elem_id="chuanhu-area", scale=5):
            with gr.Column(elem_id="chatbot-area"):
                with gr.Row(elem_id="chatbot-header"):
                    model_select_dropdown = gr.Dropdown(
                        label=i18n("选择模型"), choices=MODELS, multiselect=False, value=MODELS[DEFAULT_MODEL], interactive=True,
                        show_label=False, container=False, elem_id="model-select-dropdown"
                    )
                    lora_select_dropdown = gr.Dropdown(
                        label=i18n("选择LoRA模型"), choices=[], multiselect=False, interactive=True, visible=False,
                        container=False,
                    )
                    gr.HTML(get_html("chatbot_header_btn.html").format(
                        json_label=i18n("历史记录(JSON)"),
                        md_label=i18n("导出为 Markdown")
                    ), elem_id="chatbot-header-btn-bar")
                with gr.Row():
                    chatbot = gr.Chatbot(
                        label="Chuanhu Chat",
                        elem_id="chuanhu-chatbot",
                        latex_delimiters=latex_delimiters_set,
                        # height=700,
                        show_label=False,
                        avatar_images=[config.user_avatar, config.bot_avatar],
                        show_share_button=False,
                    )
                with gr.Row(elem_id="chatbot-footer"):
                    with gr.Box(elem_id="chatbot-input-box"):
                        with gr.Row(elem_id="chatbot-input-row"):
                            gr.HTML(get_html("chatbot_more.html").format(
                                single_turn_label=i18n("单轮对话"),
                                websearch_label=i18n("在线搜索"),
                                upload_file_label=i18n("上传文件"),
                                uploaded_files_label=i18n("知识库文件"),
                                uploaded_files_tip=i18n("在工具箱中管理知识库文件")
                            ))
                            with gr.Row(elem_id="chatbot-input-tb-row"):
                                with gr.Column(min_width=225, scale=12):
                                    user_input = gr.Textbox(
                                        elem_id="user-input-tb",
                                        show_label=False,
                                        placeholder=i18n("在这里输入"),
                                        elem_classes="no-container",
                                        max_lines=5,
                                        # container=False
                                    )
                                with gr.Column(min_width=42, scale=1, elem_id="chatbot-ctrl-btns"):
                                    submitBtn = gr.Button(
                                        value="", variant="primary", elem_id="submit-btn")
                                    cancelBtn = gr.Button(
                                        value="", variant="secondary", visible=False, elem_id="cancel-btn")
                        # Note: Buttons below are set invisible in UI. But they are used in JS.
                        with gr.Row(elem_id="chatbot-buttons", visible=False):
                            with gr.Column(min_width=120, scale=1):
                                emptyBtn = gr.Button(
                                    i18n("🧹 新的对话"), elem_id="empty-btn"
                                )
                            with gr.Column(min_width=120, scale=1):
                                retryBtn = gr.Button(
                                    i18n("🔄 重新生成"), elem_id="gr-retry-btn")
                            with gr.Column(min_width=120, scale=1):
                                delFirstBtn = gr.Button(i18n("🗑️ 删除最旧对话"))
                            with gr.Column(min_width=120, scale=1):
                                delLastBtn = gr.Button(
                                    i18n("🗑️ 删除最新对话"), elem_id="gr-dellast-btn")
                            with gr.Row(visible=False) as like_dislike_area:
                                with gr.Column(min_width=20, scale=1):
                                    likeBtn = gr.Button(
                                        i18n("👍"), elem_id="gr-like-btn")
                                with gr.Column(min_width=20, scale=1):
                                    dislikeBtn = gr.Button(
                                        i18n("👎"), elem_id="gr-dislike-btn")

        with gr.Column(elem_id="toolbox-area", scale=1):
            # For CSS setting, there is an extra box. Don't remove it.
            with gr.Box(elem_id="chuanhu-toolbox"):
                with gr.Row():
                    gr.Markdown("## "+i18n("工具箱"))
                    gr.HTML(get_html("close_btn.html").format(
                        obj="toolbox"), elem_classes="close-btn")
                with gr.Tabs(elem_id="chuanhu-toolbox-tabs"):
                    with gr.Tab(label=i18n("对话")):
                        with gr.Accordion(label="Prompt", open=True):
                            systemPromptTxt = gr.Textbox(
                                show_label=True,
                                placeholder=i18n("在这里输入System Prompt..."),
                                label="System prompt",
                                value=INITIAL_SYSTEM_PROMPT,
                                lines=8
                            )
                            with gr.Accordion(label=i18n("加载Prompt模板"), open=False):
                                with gr.Column():
                                    with gr.Row():
                                        with gr.Column(scale=6):
                                            templateFileSelectDropdown = gr.Dropdown(
                                                label=i18n("选择Prompt模板集合文件"),
                                                choices=get_template_names(),
                                                multiselect=False,
                                                value=get_template_names()[0],
                                                container=False,
                                            )
                                        with gr.Column(scale=1):
                                            templateRefreshBtn = gr.Button(
                                                i18n("🔄 刷新"))
                                    with gr.Row():
                                        with gr.Column():
                                            templateSelectDropdown = gr.Dropdown(
                                                label=i18n("从Prompt模板中加载"),
                                                choices=load_template(
                                                    get_template_names()[
                                                        0], mode=1
                                                ),
                                                multiselect=False,
                                                container=False,
                                            )
                        gr.Markdown("---", elem_classes="hr-line")
                        with gr.Accordion(label=i18n("知识库"), open=True):
                            use_websearch_checkbox = gr.Checkbox(label=i18n(
                                "使用在线搜索"), value=False, elem_classes="switch-checkbox", elem_id="gr-websearch-cb", visible=False)
                            index_files = gr.Files(label=i18n(
                                "上传"), type="file", elem_id="upload-index-file")
                            two_column = gr.Checkbox(label=i18n(
                                "双栏pdf"), value=advance_docs["pdf"].get("two_column", False))
                            summarize_btn = gr.Button(i18n("总结"))
                            # TODO: 公式ocr
                            # formula_ocr = gr.Checkbox(label=i18n("识别公式"), value=advance_docs["pdf"].get("formula_ocr", False))

                    with gr.Tab(label=i18n("参数")):
                        gr.Markdown(i18n("# ⚠️ 务必谨慎更改 ⚠️"),
                                    elem_id="advanced-warning")
                        with gr.Accordion(i18n("参数"), open=True):
                            temperature_slider = gr.Slider(
                                minimum=-0,
                                maximum=2.0,
                                value=1.0,
                                step=0.1,
                                interactive=True,
                                label="temperature",
                            )
                            top_p_slider = gr.Slider(
                                minimum=-0,
                                maximum=1.0,
                                value=1.0,
                                step=0.05,
                                interactive=True,
                                label="top-p",
                            )
                            n_choices_slider = gr.Slider(
                                minimum=1,
                                maximum=10,
                                value=1,
                                step=1,
                                interactive=True,
                                label="n choices",
                            )
                            stop_sequence_txt = gr.Textbox(
                                show_label=True,
                                placeholder=i18n("停止符,用英文逗号隔开..."),
                                label="stop",
                                value="",
                                lines=1,
                            )
                            max_context_length_slider = gr.Slider(
                                minimum=1,
                                maximum=32768,
                                value=2000,
                                step=1,
                                interactive=True,
                                label="max context",
                            )
                            max_generation_slider = gr.Slider(
                                minimum=1,
                                maximum=32768,
                                value=1000,
                                step=1,
                                interactive=True,
                                label="max generations",
                            )
                            presence_penalty_slider = gr.Slider(
                                minimum=-2.0,
                                maximum=2.0,
                                value=0.0,
                                step=0.01,
                                interactive=True,
                                label="presence penalty",
                            )
                            frequency_penalty_slider = gr.Slider(
                                minimum=-2.0,
                                maximum=2.0,
                                value=0.0,
                                step=0.01,
                                interactive=True,
                                label="frequency penalty",
                            )
                            logit_bias_txt = gr.Textbox(
                                show_label=True,
                                placeholder=f"word:likelihood",
                                label="logit bias",
                                value="",
                                lines=1,
                            )
                            user_identifier_txt = gr.Textbox(
                                show_label=True,
                                placeholder=i18n("用于定位滥用行为"),
                                label=i18n("用户名"),
                                value=user_name.value,
                                lines=1,
                            )
                    with gr.Tab(label=i18n("拓展")):
                        gr.Markdown(
                            "Will be here soon...\n(We hope)\n\nAnd we hope you can help us to make more extensions!")

                    # changeAPIURLBtn = gr.Button(i18n("🔄 切换API地址"))

    with gr.Row(elem_id="popup-wrapper"):
        with gr.Box(elem_id="chuanhu-popup"):
            with gr.Box(elem_id="chuanhu-setting"):
                with gr.Row():
                    gr.Markdown("## "+i18n("设置"))
                    gr.HTML(get_html("close_btn.html").format(
                        obj="box"), elem_classes="close-btn")
                with gr.Tabs(elem_id="chuanhu-setting-tabs"):
                    with gr.Tab(label=i18n("模型")):
                        keyTxt = gr.Textbox(
                            show_label=True,
                            placeholder=f"Your API-key...",
                            value=hide_middle_chars(user_api_key.value),
                            type="password",
                            visible=not HIDE_MY_KEY,
                            label="API-Key",
                        )
                        if multi_api_key:
                            usageTxt = gr.Markdown(i18n(
                                "多账号模式已开启,无需输入key,可直接开始对话"), elem_id="usage-display", elem_classes="insert-block", visible=show_api_billing)
                        else:
                            usageTxt = gr.Markdown(i18n(
                                "**发送消息** 或 **提交key** 以显示额度"), elem_id="usage-display", elem_classes="insert-block", visible=show_api_billing)
                        # model_select_dropdown = gr.Dropdown(
                        #     label=i18n("选择模型"), choices=MODELS, multiselect=False, value=MODELS[DEFAULT_MODEL], interactive=True
                        # )
                        # lora_select_dropdown = gr.Dropdown(
                        #     label=i18n("选择LoRA模型"), choices=[], multiselect=False, interactive=True, visible=False
                        # )
                        # with gr.Row():

                        language_select_dropdown = gr.Dropdown(
                            label=i18n("选择回复语言(针对搜索&索引功能)"),
                            choices=REPLY_LANGUAGES,
                            multiselect=False,
                            value=REPLY_LANGUAGES[0],
                        )

                    with gr.Tab(label=i18n("高级")):
                        gr.HTML(get_html("appearance_switcher.html").format(
                            label=i18n("切换亮暗色主题")), elem_classes="insert-block", visible=False)
                        use_streaming_checkbox = gr.Checkbox(
                            label=i18n("实时传输回答"), value=True, visible=ENABLE_STREAMING_OPTION, elem_classes="switch-checkbox"
                        )
                        name_chat_method = gr.Dropdown(
                            label=i18n("对话命名方式"), 
                            choices=HISTORY_NAME_METHODS, 
                            multiselect=False,
                            interactive=True,
                            value=HISTORY_NAME_METHODS[chat_name_method_index], 
                        )
                        single_turn_checkbox = gr.Checkbox(label=i18n(
                            "单轮对话"), value=False, elem_classes="switch-checkbox", elem_id="gr-single-session-cb", visible=False)
                        # checkUpdateBtn = gr.Button(i18n("🔄 检查更新..."), visible=check_update)

                    with gr.Tab(i18n("网络")):
                        gr.Markdown(
                            i18n("⚠️ 为保证API-Key安全,请在配置文件`config.json`中修改网络设置"), elem_id="netsetting-warning")
                        default_btn = gr.Button(i18n("🔙 恢复默认网络设置"))
                        # 网络代理
                        proxyTxt = gr.Textbox(
                            show_label=True,
                            placeholder=i18n("未设置代理..."),
                            label=i18n("代理地址"),
                            value=config.http_proxy,
                            lines=1,
                            interactive=False,
                            # container=False,
                            elem_classes="view-only-textbox no-container",
                        )
                        # changeProxyBtn = gr.Button(i18n("🔄 设置代理地址"))

                        # 优先展示自定义的api_host
                        apihostTxt = gr.Textbox(
                            show_label=True,
                            placeholder="api.openai.com",
                            label="OpenAI API-Host",
                            value=config.api_host or shared.API_HOST,
                            lines=1,
                            interactive=False,
                            # container=False,
                            elem_classes="view-only-textbox no-container",
                        )

                    with gr.Tab(label=i18n("关于"), elem_id="about-tab"):
                        gr.Markdown(
                            '<img alt="Chuanhu Chat logo" src="file=web_assets/icon/any-icon-512.png" style="max-width: 144px;">')
                        gr.Markdown("# "+i18n("川虎Chat"))
                        gr.HTML(get_html("footer.html").format(
                            versions=versions_html()), elem_id="footer")
                        gr.Markdown(CHUANHU_DESCRIPTION, elem_id="description")

            with gr.Box(elem_id="chuanhu-training"):
                with gr.Row():
                    gr.Markdown("## "+i18n("训练"))
                    gr.HTML(get_html("close_btn.html").format(
                        obj="box"), elem_classes="close-btn")
                with gr.Tabs(elem_id="chuanhu-training-tabs"):
                    with gr.Tab(label="OpenAI "+i18n("微调")):
                        openai_train_status = gr.Markdown(label=i18n("训练状态"), value=i18n(
                            "查看[使用介绍](https://github.com/GaiZhenbiao/ChuanhuChatGPT/wiki/使用教程#微调-gpt-35)"))

                        with gr.Tab(label=i18n("准备数据集")):
                            dataset_preview_json = gr.JSON(
                                label=i18n("数据集预览"), readonly=True)
                            dataset_selection = gr.Files(label=i18n("选择数据集"), file_types=[
                                                         ".xlsx", ".jsonl"], file_count="single")
                            upload_to_openai_btn = gr.Button(
                                i18n("上传到OpenAI"), variant="primary", interactive=False)

                        with gr.Tab(label=i18n("训练")):
                            openai_ft_file_id = gr.Textbox(label=i18n(
                                "文件ID"), value="", lines=1, placeholder=i18n("上传到 OpenAI 后自动填充"))
                            openai_ft_suffix = gr.Textbox(label=i18n(
                                "模型名称后缀"), value="", lines=1, placeholder=i18n("可选,用于区分不同的模型"))
                            openai_train_epoch_slider = gr.Slider(label=i18n(
                                "训练轮数(Epochs)"), minimum=1, maximum=100, value=3, step=1, interactive=True)
                            openai_start_train_btn = gr.Button(
                                i18n("开始训练"), variant="primary", interactive=False)

                        with gr.Tab(label=i18n("状态")):
                            openai_status_refresh_btn = gr.Button(i18n("刷新状态"))
                            openai_cancel_all_jobs_btn = gr.Button(
                                i18n("取消所有任务"))
                            add_to_models_btn = gr.Button(
                                i18n("添加训练好的模型到模型列表"), interactive=False)

            with gr.Box(elem_id="web-config", visible=False):
                gr.HTML(get_html('web_config.html').format(
                    enableCheckUpdate_config=check_update,
                    hideHistoryWhenNotLoggedIn_config=hide_history_when_not_logged_in,
                    forView_i18n=i18n("仅供查看"),
                    deleteConfirm_i18n_pref=i18n("你真的要删除 "),
                    deleteConfirm_i18n_suff=i18n(" 吗?"),
                    usingLatest_i18n=i18n("您使用的就是最新版!"),
                    updatingMsg_i18n=i18n("正在尝试更新..."),
                    updateSuccess_i18n=i18n("更新成功,请重启本程序"),
                    updateFailure_i18n=i18n(
                        '更新失败,请尝试<a href="https://github.com/GaiZhenbiao/ChuanhuChatGPT/wiki/使用教程#手动更新" target="_blank">手动更新</a>'),
                    regenerate_i18n=i18n("重新生成"),
                    deleteRound_i18n=i18n("删除这轮问答"),
                    renameChat_i18n=i18n("重命名该对话"),
                ))
            with gr.Box(elem_id="fake-gradio-components", visible=False):
                updateChuanhuBtn = gr.Button(
                    visible=False, elem_classes="invisible-btn", elem_id="update-chuanhu-btn")
                changeSingleSessionBtn = gr.Button(
                    visible=False, elem_classes="invisible-btn", elem_id="change-single-session-btn")
                changeOnlineSearchBtn = gr.Button(
                    visible=False, elem_classes="invisible-btn", elem_id="change-online-search-btn")
                historySelectBtn = gr.Button(
                    visible=False, elem_classes="invisible-btn", elem_id="history-select-btn")  # Not used

    # https://github.com/gradio-app/gradio/pull/3296

    def create_greeting(request: gr.Request):
        if hasattr(request, "username") and request.username:  # is not None or is not ""
            logging.info(f"Get User Name: {request.username}")
            user_info, user_name = gr.Markdown.update(
                value=f"User: {request.username}"), request.username
        else:
            user_info, user_name = gr.Markdown.update(
                value=f"", visible=False), ""
        current_model = get_model(
            model_name=MODELS[DEFAULT_MODEL], access_key=my_api_key)[0]
        current_model.set_user_identifier(user_name)
        if not hide_history_when_not_logged_in or user_name:
            filename, system_prompt, chatbot = current_model.auto_load()
        else:
            system_prompt = gr.update()
            filename = gr.update()
            chatbot = gr.Chatbot.update(label=MODELS[DEFAULT_MODEL])
        return user_info, user_name, current_model, toggle_like_btn_visibility(DEFAULT_MODEL), filename, system_prompt, chatbot, init_history_list(user_name)
    demo.load(create_greeting, inputs=None, outputs=[
              user_info, user_name, current_model, like_dislike_area, saveFileName, systemPromptTxt, chatbot, historySelectList], api_name="load")
    chatgpt_predict_args = dict(
        fn=predict,
        inputs=[
            current_model,
            user_question,
            chatbot,
            use_streaming_checkbox,
            use_websearch_checkbox,
            index_files,
            language_select_dropdown,
        ],
        outputs=[chatbot, status_display],
        show_progress=True,
    )

    start_outputing_args = dict(
        fn=start_outputing,
        inputs=[],
        outputs=[submitBtn, cancelBtn],
        show_progress=True,
    )

    end_outputing_args = dict(
        fn=end_outputing, inputs=[], outputs=[submitBtn, cancelBtn]
    )

    reset_textbox_args = dict(
        fn=reset_textbox, inputs=[], outputs=[user_input]
    )

    transfer_input_args = dict(
        fn=transfer_input, inputs=[user_input], outputs=[
            user_question, user_input, submitBtn, cancelBtn], show_progress=True
    )

    get_usage_args = dict(
        fn=billing_info, inputs=[current_model], outputs=[
            usageTxt], show_progress=False
    )

    load_history_from_file_args = dict(
        fn=load_chat_history,
        inputs=[current_model, historySelectList, user_name],
        outputs=[saveFileName, systemPromptTxt, chatbot]
    )

    refresh_history_args = dict(
        fn=get_history_list, inputs=[user_name], outputs=[historySelectList]
    )

    auto_name_chat_history_args = dict(
        fn=auto_name_chat_history,
        inputs=[current_model, name_chat_method, user_question, chatbot, user_name, language_select_dropdown],
        outputs=[historySelectList],
        show_progress=False,
    )

    # Chatbot
    cancelBtn.click(interrupt, [current_model], [])

    user_input.submit(**transfer_input_args).then(**
                                                  chatgpt_predict_args).then(**end_outputing_args).then(**auto_name_chat_history_args)
    user_input.submit(**get_usage_args)

    # user_input.submit(auto_name_chat_history, [current_model, user_question, chatbot, user_name], [historySelectList], show_progress=False)

    submitBtn.click(**transfer_input_args).then(**chatgpt_predict_args,
                                                api_name="predict").then(**end_outputing_args).then(**auto_name_chat_history_args)
    submitBtn.click(**get_usage_args)

    # submitBtn.click(auto_name_chat_history, [current_model, user_question, chatbot, user_name], [historySelectList], show_progress=False)

    index_files.change(handle_file_upload, [current_model, index_files, chatbot, language_select_dropdown], [
                       index_files, chatbot, status_display])
    summarize_btn.click(handle_summarize_index, [
                        current_model, index_files, chatbot, language_select_dropdown], [chatbot, status_display])

    emptyBtn.click(
        reset,
        inputs=[current_model],
        outputs=[chatbot, status_display, historySelectList],
        show_progress=True,
        _js='clearChatbot',
    )

    retryBtn.click(**start_outputing_args).then(
        retry,
        [
            current_model,
            chatbot,
            use_streaming_checkbox,
            use_websearch_checkbox,
            index_files,
            language_select_dropdown,
        ],
        [chatbot, status_display],
        show_progress=True,
    ).then(**end_outputing_args)
    retryBtn.click(**get_usage_args)

    delFirstBtn.click(
        delete_first_conversation,
        [current_model],
        [status_display],
    )

    delLastBtn.click(
        delete_last_conversation,
        [current_model, chatbot],
        [chatbot, status_display],
        show_progress=False
    )

    likeBtn.click(
        like,
        [current_model],
        [status_display],
        show_progress=False
    )

    dislikeBtn.click(
        dislike,
        [current_model],
        [status_display],
        show_progress=False
    )

    two_column.change(update_doc_config, [two_column], None)

    # LLM Models
    keyTxt.change(set_key, [current_model, keyTxt], [
                  user_api_key, status_display], api_name="set_key").then(**get_usage_args)
    keyTxt.submit(**get_usage_args)
    single_turn_checkbox.change(
        set_single_turn, [current_model, single_turn_checkbox], None)
    model_select_dropdown.change(get_model, [model_select_dropdown, lora_select_dropdown, user_api_key, temperature_slider, top_p_slider, systemPromptTxt, user_name], [
                                 current_model, status_display, chatbot, lora_select_dropdown, user_api_key, keyTxt], show_progress=True, api_name="get_model")
    model_select_dropdown.change(toggle_like_btn_visibility, [model_select_dropdown], [
                                 like_dislike_area], show_progress=False)
    lora_select_dropdown.change(get_model, [model_select_dropdown, lora_select_dropdown, user_api_key, temperature_slider,
                                top_p_slider, systemPromptTxt, user_name], [current_model, status_display, chatbot], show_progress=True)

    # Template
    systemPromptTxt.change(set_system_prompt, [
                           current_model, systemPromptTxt], None)
    templateRefreshBtn.click(get_template_dropdown, None, [
                             templateFileSelectDropdown])
    templateFileSelectDropdown.input(
        load_template,
        [templateFileSelectDropdown],
        [promptTemplates, templateSelectDropdown],
        show_progress=True,
    )
    templateSelectDropdown.change(
        get_template_content,
        [promptTemplates, templateSelectDropdown, systemPromptTxt],
        [systemPromptTxt],
        show_progress=True,
    )

    # S&L
    renameHistoryBtn.click(
        rename_chat_history,
        [current_model, saveFileName, chatbot, user_name],
        [historySelectList],
        show_progress=True,
        _js='(a,b,c,d)=>{return saveChatHistory(a,b,c,d);}'
    )
    exportMarkdownBtn.click(
        export_markdown,
        [current_model, saveFileName, chatbot, user_name],
        [],
        show_progress=True,
    )
    historyRefreshBtn.click(**refresh_history_args)
    historyDeleteBtn.click(delete_chat_history, [current_model, historySelectList, user_name], [status_display, historySelectList, chatbot], _js='(a,b,c)=>{return showConfirmationDialog(a, b, c);}').then(
        reset,
        inputs=[current_model],
        outputs=[chatbot, status_display, historySelectList],
        show_progress=True,
        _js='clearChatbot',
    )
    historySelectList.input(**load_history_from_file_args)
    uploadFileBtn.upload(upload_chat_history, [current_model, uploadFileBtn, user_name], [
                        saveFileName, systemPromptTxt, chatbot]).then(**refresh_history_args)
    historyDownloadBtn.click(None, [
                             user_name, historySelectList], None, _js='(a,b)=>{return downloadHistory(a,b,".json");}')
    historyMarkdownDownloadBtn.click(None, [
                                     user_name, historySelectList], None, _js='(a,b)=>{return downloadHistory(a,b,".md");}')
    historySearchTextbox.input(
        filter_history,
        [user_name, historySearchTextbox],
        [historySelectList]
    )

    # Train
    dataset_selection.upload(handle_dataset_selection, dataset_selection, [
                             dataset_preview_json, upload_to_openai_btn, openai_train_status])
    dataset_selection.clear(handle_dataset_clear, [], [
                            dataset_preview_json, upload_to_openai_btn])
    upload_to_openai_btn.click(upload_to_openai, [dataset_selection], [
                               openai_ft_file_id, openai_train_status], show_progress=True)

    openai_ft_file_id.change(lambda x: gr.update(interactive=True) if len(
        x) > 0 else gr.update(interactive=False), [openai_ft_file_id], [openai_start_train_btn])
    openai_start_train_btn.click(start_training, [
                                 openai_ft_file_id, openai_ft_suffix, openai_train_epoch_slider], [openai_train_status])

    openai_status_refresh_btn.click(get_training_status, [], [
                                    openai_train_status, add_to_models_btn])
    add_to_models_btn.click(add_to_models, [], [
                            model_select_dropdown, openai_train_status], show_progress=True)
    openai_cancel_all_jobs_btn.click(
        cancel_all_jobs, [], [openai_train_status], show_progress=True)

    # Advanced
    max_context_length_slider.change(
        set_token_upper_limit, [current_model, max_context_length_slider], None)
    temperature_slider.change(
        set_temperature, [current_model, temperature_slider], None)
    top_p_slider.change(set_top_p, [current_model, top_p_slider], None)
    n_choices_slider.change(
        set_n_choices, [current_model, n_choices_slider], None)
    stop_sequence_txt.change(
        set_stop_sequence, [current_model, stop_sequence_txt], None)
    max_generation_slider.change(
        set_max_tokens, [current_model, max_generation_slider], None)
    presence_penalty_slider.change(
        set_presence_penalty, [current_model, presence_penalty_slider], None)
    frequency_penalty_slider.change(
        set_frequency_penalty, [current_model, frequency_penalty_slider], None)
    logit_bias_txt.change(
        set_logit_bias, [current_model, logit_bias_txt], None)
    user_identifier_txt.change(set_user_identifier, [
                               current_model, user_identifier_txt], None)

    default_btn.click(
        reset_default, [], [apihostTxt, proxyTxt, status_display], show_progress=True
    )
    # changeAPIURLBtn.click(
    #     change_api_host,
    #     [apihostTxt],
    #     [status_display],
    #     show_progress=True,
    # )
    # changeProxyBtn.click(
    #     change_proxy,
    #     [proxyTxt],
    #     [status_display],
    #     show_progress=True,
    # )
    # checkUpdateBtn.click(fn=None, _js='manualCheckUpdate')

    # Invisible elements
    updateChuanhuBtn.click(
        update_chuanhu,
        [],
        [status_display],
        show_progress=True,
    )
    changeSingleSessionBtn.click(
        fn=lambda value: gr.Checkbox.update(value=value),
        inputs=[single_turn_checkbox],
        outputs=[single_turn_checkbox],
        _js='(a)=>{return bgChangeSingleSession(a);}'
    )
    changeOnlineSearchBtn.click(
        fn=lambda value: gr.Checkbox.update(value=value),
        inputs=[use_websearch_checkbox],
        outputs=[use_websearch_checkbox],
        _js='(a)=>{return bgChangeOnlineSearch(a);}'
    )
    historySelectBtn.click(  # This is an experimental feature... Not actually used.
        fn=load_chat_history,
        inputs=[current_model, historySelectList],
        outputs=[saveFileName, systemPromptTxt, chatbot],
        _js='(a,b)=>{return bgSelectHistory(a,b);}'
    )


logging.info(
    colorama.Back.GREEN
    + "\n川虎的温馨提示:访问 http://localhost:7860 查看界面"
    + colorama.Style.RESET_ALL
)
# 默认开启本地服务器,默认可以直接从IP访问,默认不创建公开分享链接
demo.title = i18n("川虎Chat 🚀")

if __name__ == "__main__":
    reload_javascript()
    demo.queue(concurrency_count=CONCURRENT_COUNT).launch(
        blocked_paths=["config.json"],
        server_name=server_name,
        server_port=server_port,
        share=share,
        auth=auth_from_conf if authflag else None,
        favicon_path="./web_assets/favicon.ico",
        inbrowser=not dockerflag,  # 禁止在docker下开启inbrowser
    )