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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: MIT
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

import gradio as gr
import subprocess
from ui.configuration import Configuration
import math
import uuid
import sys
import os
import kaizen_theme as kaizen
import re
import threading
import webbrowser
import socket
import random
            

class MainInterface:

    _dataset_path_key = 'dataset'
    _models_path_key = 'models'
    _dataset_directory_label_text = ".txt, .pdf, .doc files supported"
    _dataset_path_updated_callback = None
    _dataset_source_updated_callback = None
    _shutdown_callback = None
    _reset_chat_callback = None
    _undo_last_chat_callback = None
    _model_change_callback = None
    _regenerate_index_callback = None
    _query_handler = None
    _state = None
    _interface = None
    _streaming = False
    _models_list = {}

    def _get_enable_disable_elemet_list(self):
        ret_val = [
            self._chat_query_input_textbox,
            self._chat_bot_window,
            self._chat_submit_button,
            self._chat_retry_button,
            self._chat_reset_button,
            self._models_dropdown,
            self._dataset_source_dropdown,
            self._dataset_update_source_edit_button,
            self._dataset_regenerate_index_button
        ]

        if self._chat_undo_button is not None:
            ret_val.append(self._chat_undo_button)
        
        return ret_val
    
    def _before_change_element_state(self, request: gr.Request):
        self._validate_session(request)
        ret_val = [
            gr.Textbox("", interactive=False),
            gr.Chatbot(),
            gr.Button(interactive=False),
            gr.Button(interactive=False),
            gr.Button(interactive=False),
            gr.Dropdown(interactive=False),
            gr.Dropdown(interactive=False),
            gr.Button(interactive=False),
            gr.Button(interactive=False)
        ]

        if self._chat_undo_button is not None:
            ret_val.append(gr.Button(interactive=False))

        return ret_val
    
    def _after_change_element_state(self, request: gr.Request):
        self._validate_session(request)
        ret_val = [
            gr.Textbox(interactive=True),
            [],
            gr.Button(interactive=True),
            gr.Button(interactive=True),
            gr.Button(interactive=True),
            gr.Dropdown(interactive=True),
            gr.Dropdown(interactive=True),
            gr.Button(interactive=True),
            gr.Button(interactive=True)
        ]

        if self._chat_undo_button is not None:
            ret_val.append(gr.Button(interactive=True))

        return ret_val
    
    def __init__(self, chatbot=None, streaming = False) -> None:
        self._interface = None
        self._query_handler = chatbot
        self._streaming = streaming
        self.config = Configuration()
        self._dataset_path = self._get_dataset_path()
        self._default_dataset_path = self._get_default_dataset_path()
        pass

    def _get_dataset_path(self):
        _dataset_path = ""
        dataset_config = self.config.get_config(self._dataset_path_key) or {}
        if 'path' in dataset_config:
            _dataset_path = dataset_config['path']
            if 'isRelative' in dataset_config and dataset_config['isRelative'] is True:
                _dataset_path = os.path.join(os.getcwd(), _dataset_path)
        
        return _dataset_path
    
    def _get_default_dataset_path(self):
        _dataset_path = ""
        dataset_config = self.config.get_config_from_file(self._dataset_path_key, "config/config.json") or {}
        if 'path' in dataset_config:
            _dataset_path = dataset_config['path']
            if 'isRelative' in dataset_config and dataset_config['isRelative'] is True:
                _dataset_path = os.path.join(os.getcwd(), _dataset_path)
        
        return _dataset_path

    def on_dataset_path_updated(self, callback):
        self._dataset_path_updated_callback = callback

    def on_dataset_source_updated(self, callback):
        self._dataset_source_updated_callback = callback

    def on_shutdown(self, callback):
        self._shutdown_callback = callback

    def on_reset_chat(self, callback):
        self._reset_chat_callback = callback

    def on_undo_last_chat(self, callback):
        self._undo_last_chat_callback = callback

    def on_model_change(self, callback):
        self._model_change_callback = callback

    def on_regenerate_index(self, callback):
        self._regenerate_index_callback = callback

    def _get_theme(self):
        primary_hue = gr.themes.Color("#76B900", "#76B900", "#76B900", "#76B900", "#76B900", "#76B900", "#76B900", "#76B900", "#76B900", "#76B900", "#76B900")
        neutral_hue = gr.themes.Color("#292929", "#292929", "#292929", "#292929", "#292929", "#292929", "#292929", "#292929", "#292929", "#292929", "#292929")
        return gr.Theme(
            primary_hue=primary_hue,
            neutral_hue=neutral_hue
        ).set(
            body_background_fill="#191919",
            body_background_fill_dark="#191919",
            block_background_fill="#292929",
            block_background_fill_dark="#292929",
            block_label_background_fill="#292929",
            block_label_background_fill_dark="#292929",
            border_color_primary="#191919",#components background
            border_color_primary_dark="#191919",
            background_fill_primary="#292929",#dropdown
            background_fill_primary_dark="#292929",
            background_fill_secondary="#393939",#response chatbot bubble
            background_fill_secondary_dark="#393939",
            color_accent_soft="#393939",#request chatbot bubble
            color_accent_soft_dark="#393939",
            #text colors
            block_label_text_color="#FFFFFF",
            block_label_text_color_dark="#FFFFFF",
            body_text_color="#FFFFFF",
            body_text_color_dark="#FFFFFF",
            body_text_color_subdued="#FFFFFF",
            body_text_color_subdued_dark="#FFFFFF",
            button_secondary_text_color="#FFFFFF",
            button_secondary_text_color_dark="#FFFFFF",
            button_primary_text_color="#FFFFFF",
            button_primary_text_color_dark="#FFFFFF",
            input_placeholder_color="#FFFFFF",#placeholder text color
            input_placeholder_color_dark="#FFFFFF",
        )

    def get_css(self):
        return kaizen.css() + open(os.path.join(os.path.dirname(__file__), 'www/app.css')).read()

    def render(self):
        with gr.Blocks(
            title="Chat with RTX",
            analytics_enabled=False,
            theme=kaizen.theme(),
            css=self.get_css(),
            js=os.path.join(os.path.dirname(__file__), 'www/app.js')
        ) as interface:
            self._interface = interface
            self._state = gr.State({})
            (
                self._shutdown_button,
                self._shutdown_post_shutdown_group,
                self._shutdown_memory_released_markdown,
                self._shutdown_invalid_session_markdown
            ) = self._render_logo_shut_down()
            with gr.Row():
                self._models_dropdown, self._models_group = self._render_models()
                (
                    self._dataset_source_textbox,
                    self._dataset_update_source_edit_button,
                    self._dataset_source_dropdown,
                    self._dataset_regenerate_index_button,
                    self._dataset_label_markdown,
                    self._dataset_group
                ) = self._render_dataset_picker()
            (
                self._sample_question_components,
                self._sample_question_rows,
                self._sample_question_empty_space_component,
                self._sample_qustion_default_dataset_markdown
            ) = self._render_sample_question()
            (
                self._chat_bot_window,
                self._chat_query_input_textbox,
                self._chat_submit_button,
                self._chat_retry_button,
                self._chat_undo_button,
                self._chat_reset_button,
                self._chat_query_group,
                self._chat_disclaimer_markdown
            ) = self._render_chatbot(show_chatbot=len(self._sample_question_components) == 0)
            self._handle_events()
        interface.queue()
        port = self._get_free_port()
        self._open_app(port)
        interface.launch(
            favicon_path=os.path.join(os.path.dirname(__file__), 'assets/nvidia_logo.png'),
            show_api=False,
            server_port=port,share=True
        )

    def _get_free_port(self):
        # Create a socket object
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # Set a short timeout for the connection attempt
        sock.settimeout(1)
        port = None
        while port is None:
            port = 1048
            try:
                # Attempt to bind to the port
                sock.bind((socket.gethostbyname(socket.gethostname()), port))
                print(socket.gethostbyname(socket.gethostname()), port)
            except OSError as e:
                port = None
                if e.errno != 98:  # errno 98: Address already in use
                    print('OS error', e)
                    break 
        sock.close()
        return port

    def _open_app(self, port):
        def launch_thread(cookie):
            launch_url = f'http://127.0.0.1:{port}?cookie={cookie}&__theme=dark'
            print(f'Open {launch_url} in browser to start Chat with RTX')
            webbrowser.open(launch_url)
            return None
        
        self._secure_cookie = str(uuid.uuid4())
        threading.Thread(target=launch_thread, args=(self._secure_cookie,)).start()
        return None

    def _validate_request(self, request: gr.Request):
        return True

    def _get_session_id(self, state):
        if isinstance(state, object):
            if not 'session-id' in state:
                state['session-id'] = str(uuid.uuid4())
            return state['session-id']
        return None

    def _render_models(self):
        models = self.config.get_config(self._models_path_key)
        model_names = []
        for model in models['supported']:
            if model['installed'] is True:
                model_names.append(model['name'])
                self._models_list[model['name']] = model

        with gr.Column():
            with gr.Group(elem_classes="padding-8p model-goup") as models_group:
                gr.Markdown("<b>AI model</b>")
                gr.Markdown(
                    'Select AI model',
                    elem_classes="description-secondary-markdown"
                )
                def get_selected_value():
                    selected = self.config.get_config('models/selected')
                    if len(self._models_list) > 0:
                        if not selected in self._models_list:
                            selected = self.config.get_config_from_file('models/selected', "config/config.json")
                        if not selected in self._models_list:
                            selected = list(self._models_list.keys())[0]
                    return selected
                return gr.Dropdown(
                    model_names,
                    elem_classes="height-40p",
                    value=get_selected_value,
                    container=False,
                    filterable=False
                ), models_group

    def _render_logo_shut_down(self):
        with gr.Row():
            gr.Image(os.path.join(os.path.dirname(__file__), "assets/nvidia_logo.png"),
                interactive=False,
                show_label=False,
                show_download_button=False,
                width=40,
                scale=0,
                container=False,
                min_width=40
            )
            gr.HTML("""
                <h1 style="font-size:32px; line-height:40px; margin:0; padding:0">Chat with RTX</h1>
            """)
            shutdown_button = gr.Button(
                "",
                scale=0,
                icon=os.path.join(os.path.dirname(__file__), 'assets/shutdown.png'),
                elem_classes="icon-button tooltip-component",
                elem_id="shutdown-btn"
            )
        
        with gr.Group(visible=False, elem_classes="shutdown-group") as post_shutdown_group:
            with gr.Row():
                gr.HTML("")
                gr.Image(os.path.join(os.path.dirname(__file__), "assets/info.png"),
                    interactive=False,
                    show_label=False,
                    show_download_button=False,
                    width=40,
                    scale=0,
                    container=False,
                    min_width=40
                )
                gr.HTML("")
            with gr.Row():
                shutdown_memory_released_markdown = gr.Markdown(
                    "Video memory released. Reopen RTX Chat from desktop to continue chatting.",
                    elem_classes="text-align-center"
                )
                shutdown_invalid_session_markdown = gr.Markdown(
                    "Invalid session. Reopen RTX Chat from desktop to continue chatting.",
                    elem_classes="text-align-center"
                )

        return shutdown_button, post_shutdown_group, shutdown_memory_released_markdown, shutdown_invalid_session_markdown

    def _render_dataset_picker(self):
        sources = self.config.get_config("dataset/sources")
        self._dataset_selected_source = self.config.get_config("dataset/selected")
        with gr.Column(elem_classes="dataset-column"):
            with gr.Group(elem_classes="padding-8p dataset-goup") as dataset_group:
                with gr.Row():
                    with gr.Column():
                        gr.Markdown("<b>Dataset</b>")
                        dataset_label_markdown = gr.Markdown(
                            self._dataset_directory_label_text,
                            elem_classes="description-secondary-markdown",
                            elem_id="dataset-description-label"
                        )
                    regenerate_vector_button = gr.Button(
                        "", 
                        icon=os.path.join(os.path.dirname(__file__), 'assets/regenerate.png'),
                        elem_classes="icon-button tooltip-component",
                        elem_id="dataset-regenerate-index-btn",
                        scale=0
                    )
                dataset_source_dropdown = gr.Dropdown(
                    self.config.get_display_strings(sources),
                    value=lambda: self.config.get_display_strings(self._dataset_selected_source),
                    show_label=False,
                    container=False,
                    filterable=False,
                    elem_classes="margin-bottom-8p height-40p"
                )
                with gr.Row():
                    dataset_source_textbox = gr.Textbox(
                        lambda: self._dataset_path,
                        scale=9,
                        container=False,
                        elem_classes="height-40p margin-right-8p",
                        interactive=False,
                        placeholder="Enter URL...",
                        max_lines=1,
                        autoscroll=True
                    )
                    dataset_update_source_edit_button = gr.Button(
                        "",
                        icon=os.path.join(os.path.dirname(__file__), 'assets/edit.png'),
                        elem_classes="icon-button tooltip-component",
                        elem_id="dataset-update-source-edit-button",
                        visible=self._dataset_selected_source=="directory",
                        scale=0
                    )
                    return (
                        dataset_source_textbox,
                        dataset_update_source_edit_button,
                        dataset_source_dropdown,
                        regenerate_vector_button,
                        dataset_label_markdown,
                        dataset_group
                    )


    def _render_sample_question(self):
        question_butons = []
        question_rows = []
        sample_questions: list = self.config.get_config("sample_questions")
        if sample_questions is None or len(sample_questions) == 0:
            return question_butons, question_rows
        
        chat_window_height = 500
        row_height = 16
        button_height = 42
        elem_per_row = 2
        row_count = math.ceil(len(sample_questions) / elem_per_row)
        height = chat_window_height - (row_count*(row_height + button_height))
        empty_space_component = gr.HTML(f'<div style="height: {height}px"></div>')
        default_dataset_label = gr.Markdown(
            "Default dataset is a sampling of articles recently published on GeForce News",
            elem_classes="description-secondary-markdown chat-disclaimer-message margin-"
        )
        for i in range(0, len(sample_questions), 2):
            row_questions = sample_questions[:2]
            sample_questions = sample_questions[2:]
            with gr.Row() as question_row:
                for index, question in enumerate(row_questions):
                    query = question["query"]
                    button = gr.Button(
                        query,
                        elem_classes="sample-question-button"
                    )
                    question_butons.append({
                        "question": query,
                        "component": button
                    })
                    question_rows.append(question_row)
        return question_butons, question_rows, empty_space_component, default_dataset_label

    def _render_chatbot(self, show_chatbot):
        chatbot_window = gr.Chatbot(
            show_label=False,
            elem_classes="chat-window",
            visible=show_chatbot,
            elem_id="main-chatbot-window",
            sanitize_html=True
        )
        with gr.Group() as query_group:
            with gr.Row():
                query_input = gr.Textbox(placeholder="Chat with RTX...", scale=9, container=False)
                submit_button = gr.Button("SEND", variant="primary", scale=1)
        with gr.Row():
            gr.HTML("")
            retry_button = gr.Button(
                "",
                elem_classes="icon-button tooltip-component",
                elem_id="chatbot-retry-button",
                scale=0,
                icon=os.path.join(os.path.dirname(__file__), 'assets/retry.png'),
            )
            undo_button = None
            if self.config.get_config_from_file("is_chat_engine", os.path.join(os.path.curdir, "config/app_config.json")) == False:
                undo_button = gr.Button(
                    "",
                    scale=0,
                    icon=os.path.join(os.path.dirname(__file__), 'assets/undo.png'),
                    elem_classes="icon-button tooltip-component",
                    elem_id="chatbot-undo-button"
                )
            reset_button = gr.Button(
                "",
                elem_classes="icon-button tooltip-component",
                elem_id="chatbot-reset-button",
                scale=0,
                icon=os.path.join(os.path.dirname(__file__), 'assets/reset.png'),
            )
            gr.HTML("")
        chat_disclaimer_markdown = gr.Markdown(
            "Chat with RTX response quality depends on the AI model's accuracy and the input dataset. Please verify important information.",
            elem_classes="description-secondary-markdown chat-disclaimer-message margin-"
        )
        return (chatbot_window, query_input, submit_button, retry_button, undo_button, reset_button, query_group, chat_disclaimer_markdown)

    def _handle_events(self):
        self._handle_load_events()
        self._handle_shutdown_events()
        self._handle_model_events()
        self._handle_dataset_events()
        self._handle_chatbot_events()
        return None

    def _validate_session_and_raise(self, request: gr.Request):
        try:
            self._validate_request(request)
        except Exception as e:
            raise gr.Error('Invalid session')

    def _validate_session(self, request: gr.Request):
        try:
            self._validate_request(request)
        except Exception as e:
            return [
                gr.Group(visible=False),
                gr.Group(visible=False),
                gr.Chatbot(visible=False),
                gr.Group(visible=False),
                gr.Button(visible=False),
                gr.Button(visible=False),
                gr.Group(visible=True),
                gr.Button(visible=False),
                gr.Button(visible=False),
                gr.Markdown(visible=False),
                gr.Markdown(visible=True),
                gr.Markdown(visible=False)
             ] + self._get_sample_question_components_new(True)
        return [
            gr.Group(),
            gr.Group(),
            gr.Chatbot(),
            gr.Group(),
            gr.Button(),
            gr.Button(),
            gr.Group(),
            gr.Button(),
            gr.Button(),
            gr.Markdown(),
            gr.Markdown(),
            gr.Markdown()
         ] + self._get_sample_question_components_new()
    
    def _get_validate_session_output(self):
        return [
            self._models_group,
            self._dataset_group,
            self._chat_bot_window,
            self._chat_query_group,
            self._chat_reset_button,
            self._chat_retry_button,
            self._shutdown_post_shutdown_group,
            self._shutdown_button,
            self._chat_undo_button,
            self._chat_disclaimer_markdown,
            self._shutdown_invalid_session_markdown,
            self._shutdown_memory_released_markdown
        ] + self._get_sample_question_components()

    def _handle_load_events(self):
        self._interface.load(
            self._validate_session,
            None,
            self._get_validate_session_output()
        ).then(
            self._validate_session_and_raise,
            None,
            None
        ).success(
            self._show_hide_sample_questions,
            self._get_show_hide_sample_questions_inputs(),
            self._get_show_hide_sample_questions_outputs()
        )
        return None

    def _handle_shutdown_events(self):
        def close_thread(session_id):
            if self._shutdown_callback:
                self._shutdown_callback(session_id)
            self._interface.close()
            self._interface = None
            print('exiting')
            os._exit(0)
            
        def handle_shutdown(state, request: gr.Request):
            self._validate_session(request)
            if self._interface is not None:
                _close_thread = threading.Thread(target=close_thread, args=(self._get_session_id(state),))
                _close_thread.start()
            else:
                print("Interface not initialized or already closed")
            return state
        def before_shutdown(request: gr.Request):
            self._validate_session(request)
            ret_val = [
                gr.Group(visible=False),
                gr.Group(visible=False),
                gr.Chatbot(visible=False),
                gr.Group(visible=False),
                gr.Button(visible=False),
                gr.Button(visible=False),
                gr.Group(visible=True),
                gr.Button(visible=False),
                gr.Button(visible=False),
                gr.Markdown(visible=False),
                gr.Markdown(visible=False),
                gr.Markdown(visible=True)
            ] + self._get_sample_question_components_new(True)
            return ret_val
        

        self._shutdown_button.click(
            self._validate_session,
            None,
            self._get_validate_session_output()
        ).then(
            self._validate_session_and_raise,
            None,
            None
        ).success(
            before_shutdown,
            None,
            [
                self._models_group,
                self._dataset_group,
                self._chat_bot_window,
                self._chat_query_group,
                self._chat_reset_button,
                self._chat_retry_button,
                self._shutdown_post_shutdown_group,
                self._shutdown_button,
                self._chat_undo_button,
                self._chat_disclaimer_markdown,
                self._shutdown_invalid_session_markdown,
                self._shutdown_memory_released_markdown
            ] + self._get_sample_question_components()
        ).then(
            handle_shutdown,
            self._state,
            self._state
        )

    def _handle_model_events(self):
        
        def on_selection_change(newModel, state, request: gr.Request):
            self._validate_session(request)
            if self._model_change_callback:
                self._model_change_callback(
                    self._models_list[newModel]['name'],
                    self._models_list[newModel]['metadata'],
                    self._get_session_id(state)
                )
            self.config.set_config("models/selected", newModel)
            return newModel, state
        
        self._models_dropdown.change(
            self._validate_session,
            None,
            self._get_validate_session_output()
        ).then(
            self._validate_session_and_raise,
            None,
            None
        ).success(
            self._before_change_element_state,
            None,
            self._get_enable_disable_elemet_list()
        ).then(
            on_selection_change,
            [self._models_dropdown, self._state],
            [self._models_dropdown, self._state]
        ).then(
            self._after_change_element_state,
            None,
            self._get_enable_disable_elemet_list(),
            show_progress=False
        )
    
    def _handle_dataset_events(self):
        
        def select_folder(path, state, request: gr.Request):
            self._validate_session(request)
            if self._dataset_selected_source == "directory":
                command = [sys.executable, "./ui/select_folder.py"]
                process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                output, _ = process.communicate()
                # Check if the command was successful
                result_string = ""
                if process.returncode == 0:
                    result_string = output.decode().strip()
                else:
                    print("Error executing script:", process.returncode)
                if len(result_string) > 0:
                    self._dataset_path = result_string
                    self.config.set_config(self._dataset_path_key, {"path": self._dataset_path, "isRelative": False})
            else:
                self._dataset_path = path

            if self._dataset_path_updated_callback:
                self._dataset_path_updated_callback(
                    self._dataset_selected_source,
                    self._dataset_path,
                    None,
                    self._get_session_id(state)
                )
            return self._dataset_path, state
        
        self._dataset_update_source_edit_button.click(
            self._validate_session,
            None,
            self._get_validate_session_output()
        ).then(
            self._validate_session_and_raise,
            None,
            None
        ).success(
            self._before_change_element_state,
            None,
            self._get_enable_disable_elemet_list()
        ).then(
            select_folder,
            [self._dataset_source_textbox, self._state],
            [self._dataset_source_textbox, self._state]
        ).then(
            self._after_change_element_state,
            None,
            self._get_enable_disable_elemet_list(),
            show_progress=False
        ).then(
            self._show_hide_sample_questions,
            self._get_show_hide_sample_questions_inputs(),
            self._get_show_hide_sample_questions_outputs(),
            show_progress=False
        )

        def on_dataset_source_changed(source, state, request: gr.Request):
            self._validate_session(request)
            self._dataset_selected_source = self.config.get_display_string_keys(source)
            source = self._dataset_selected_source
            self._dataset_path = self._get_dataset_path() if source=="directory" else ""
            if self._dataset_source_updated_callback:
                self._dataset_source_updated_callback(
                    self._dataset_selected_source,
                    self._dataset_path,
                    self._get_session_id(state)
                )
            return [
                gr.Textbox(
                    interactive=False,
                    visible=source!="nodataset",
                    value=self._dataset_path
                ),
                gr.Button(visible=source=="directory"),
                gr.Button(visible=source!="nodataset"),
                state
            ]
        
        change_source_description = """
            (source) => {
                let element = document.querySelector('[id="dataset-description-label"]');
                let label = ".txt, .pdf, .doc files supported";
                if(element) {
                    element.querySelector('p').textContent = label;
                } else {
                    console.error("failed to update");
                }
                return source;
            }
        """

        self._dataset_source_dropdown.change(
            self._validate_session,
            None,
            self._get_validate_session_output()
        ).then(
            self._validate_session_and_raise,
            None,
            None
        ).success(
            self._before_change_element_state,
            None,
            self._get_enable_disable_elemet_list(),
            show_progress=False
        ).then(            
            on_dataset_source_changed,
            [self._dataset_source_dropdown, self._state],
            [
                self._dataset_source_textbox,
                self._dataset_update_source_edit_button,
                self._dataset_regenerate_index_button,
                self._state
            ],
            show_progress=False
        ).then(
            lambda x: x,
            self._dataset_source_dropdown,
            self._dataset_source_dropdown,
            show_progress=False,
            js=change_source_description
        ).then(
            self._after_change_element_state,
            None,
            self._get_enable_disable_elemet_list(),
            show_progress=False
        ).then(
            self._show_hide_sample_questions,
            self._get_show_hide_sample_questions_inputs(),
            self._get_show_hide_sample_questions_outputs(),
            show_progress=False
        )

        def regenerate_index(state, request: gr.Request):
            self._validate_session(request)
            if self._regenerate_index_callback:
                self._regenerate_index_callback(self._dataset_selected_source, self._dataset_path, self._get_session_id(state))
            return self._dataset_path, state

        self._dataset_regenerate_index_button.click(
            self._validate_session,
            None,
            self._get_validate_session_output()
        ).then(
            self._validate_session_and_raise,
            None,
            None
        ).success(
            self._before_change_element_state,
            None,
            self._get_enable_disable_elemet_list()
        ).then(
            regenerate_index,
            self._state,
            [self._dataset_source_textbox, self._state]
        ).then(
            self._after_change_element_state,
            None,
            self._get_enable_disable_elemet_list(),
            show_progress=False
        )


# dataset events ends
    def _show_hide_sample_questions(self, query, history, dataset_source, state, request: gr.Request):
        self._validate_session(request)
        dataset_source = self.config.get_display_string_keys(dataset_source)
        sample_question_shown = state['sample_question_shown'] if isinstance(state, object) and 'sample_question_shown' in state else False
        hide_sample_ques = \
            len(query) > 0 or \
            len(history) > 0 or \
            sample_question_shown or \
            (os.path.normpath(self._dataset_path) != os.path.normpath(self._default_dataset_path))
        if isinstance(state, object):
            state['sample_question_shown'] = hide_sample_ques
        ret_val = [gr.Button(visible=not hide_sample_ques) for _ in self._sample_question_components]
        ret_val.insert(0, gr.Chatbot(history, visible=hide_sample_ques))
        [ret_val.append(gr.Row(visible=not hide_sample_ques)) for _ in self._sample_question_rows]
        ret_val.append(gr.HTML(visible=not hide_sample_ques))
        ret_val.append(gr.Markdown(visible=not hide_sample_ques))
        ret_val.append(state)
        return ret_val
    
    def _get_show_hide_sample_questions_inputs(self):
        return [
            self._chat_query_input_textbox ,self._chat_bot_window, self._dataset_source_dropdown, self._state
        ]
    
    def _get_sample_question_components_new(self, hide_sample_ques: bool = None):
        if hide_sample_ques is None: # neither show nor hide
            ret_val = [gr.Button() for _ in self._sample_question_components]
            [ret_val.append(gr.Row()) for _ in self._sample_question_rows]
            ret_val.append(gr.HTML())
            ret_val.append(gr.Markdown())
        else:
            ret_val = [gr.Button(visible=not hide_sample_ques) for _ in self._sample_question_components]
            [ret_val.append(gr.Row(visible=not hide_sample_ques)) for _ in self._sample_question_rows]
            ret_val.append(gr.HTML(visible=not hide_sample_ques))
            ret_val.append(gr.Markdown(visible=not hide_sample_ques))
        return ret_val
            

    def _get_sample_question_components(self):
        sample_questions_buttons = [question['component'] for question in self._sample_question_components]
        return sample_questions_buttons + self._sample_question_rows + [self._sample_question_empty_space_component, self._sample_qustion_default_dataset_markdown]

    def _get_show_hide_sample_questions_outputs(self):
        return [self._chat_bot_window] + self._get_sample_question_components() + [self._state]

# chat bot events
    def _handle_chatbot_events(self):
        def process_input(query, history, request: gr.Request):
            self._validate_session(request)
            if len(query) == 0:
                return "", history
            history.append([query, None])
            return "", history
        
        def process_output(history, state, request: gr.Request):
            self._validate_session(request)
            if len(history) == 0:
                yield history, state
            else:
                query = history[-1]
                if query[1] != None:
                    yield history, state
                elif self._query_handler:
                    for response in self._query_handler(query[0], history[:-1], self._get_session_id(state)):
                        history[-1][1] = response
                        yield history, state
                else:
                    history[-1][1] = "ChatBot not ready..."
                    yield history, state
            
        #undo handler
        def process_undo_last_chat(history: list, state, request: gr.Request):
            self._validate_session(request)
            if len(history) == 0:
                return history, state

            history = history[:len(history) - 1]
            if self._undo_last_chat_callback:
                self._undo_last_chat_callback(history, self._get_session_id(state))
            
            return history, state

        #retry handler
        def process_retry(history: list, request: gr.Request):
            self._validate_session(request)
            if len(history) == 0:
                return history

            lastChat = history[-1]
            history = history[:len(history) - 1]
            _, history = process_input(lastChat[0], history, request)
            return history

        def reset(state, request: gr.Request):
            self._validate_session(request)
            if self._reset_chat_callback:
                self._reset_chat_callback(self._get_session_id(state))
            return "", [], state

        gr.on(
            [self._chat_query_input_textbox.submit, self._chat_submit_button.click],
            self._validate_session,
            None,
            self._get_validate_session_output()
        ).then(
            self._validate_session_and_raise,
            None,
            None
        ).success(
            self._show_hide_sample_questions,
            self._get_show_hide_sample_questions_inputs(),
            self._get_show_hide_sample_questions_outputs()
        ).then(
            process_input,
            [self._chat_query_input_textbox, self._chat_bot_window], 
            [self._chat_query_input_textbox, self._chat_bot_window]
        ).then(
            process_output,
            [self._chat_bot_window, self._state],
            [self._chat_bot_window, self._state]
        )

        self._chat_retry_button.click(
            self._validate_session,
            None,
            self._get_validate_session_output()
        ).then(
            self._validate_session_and_raise,
            None,
            None
        ).success(
            process_retry,
            [self._chat_bot_window],
            [self._chat_bot_window]
        ).then(
            process_output,
            [self._chat_bot_window, self._state],
            [self._chat_bot_window, self._state]
        )

        if self._chat_undo_button:
            self._chat_undo_button.click(
                self._validate_session,
                None,
                self._get_validate_session_output()
            ).then(
                self._validate_session_and_raise,
                None,
                None
            ).success(
                process_undo_last_chat,
                [self._chat_bot_window, self._state],
                [self._chat_bot_window, self._state]
            )
        self._chat_reset_button.click(
            self._validate_session,
            None,
            self._get_validate_session_output()
        ).then(
            self._validate_session_and_raise,
            None,
            None
        ).success(
            reset, 
            self._state,
            [self._chat_query_input_textbox, self._chat_bot_window, self._state]
        )

        def handle_sample_question_click(evt: gr.EventData, request: gr.Request):
            self._validate_session(request)
            return evt.target.value
        
        for sample in self._sample_question_components:
            button: gr.Button = sample['component']
            button.click(
                self._validate_session,
                None,
                self._get_validate_session_output()
            ).then(
                self._validate_session_and_raise,
                None,
                None
            ).success(
                handle_sample_question_click,
                None,
                self._chat_query_input_textbox
            ).then(
                self._show_hide_sample_questions,
                self._get_show_hide_sample_questions_inputs(),
                self._get_show_hide_sample_questions_outputs()
            ).then(
                process_input,
                [self._chat_query_input_textbox, self._chat_bot_window], 
                [self._chat_query_input_textbox, self._chat_bot_window]
            ).then(
                process_output,
                [self._chat_bot_window, self._state],
                [self._chat_bot_window, self._state]
            )