File size: 37,494 Bytes
4e1f4a3
 
 
 
 
 
4c1add8
4e1f4a3
 
 
 
 
 
 
 
 
 
 
 
4c1add8
4e1f4a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c1add8
 
4e1f4a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c1add8
 
 
 
4e1f4a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c1add8
 
 
 
 
4e1f4a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c1add8
 
4e1f4a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c1add8
 
 
 
4e1f4a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c1add8
 
 
 
 
 
 
4e1f4a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c1add8
 
4e1f4a3
 
 
4c1add8
 
 
 
4e1f4a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c1add8
 
 
 
 
 
 
 
4e1f4a3
 
 
 
 
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
# Character_Interaction_tab.py
# Description: This file contains the functions that are used for Character Interactions in the Gradio UI.
#
# Imports
import base64
import io
import uuid
from datetime import datetime as datetime
import logging
import json
import os
from typing import List, Dict, Tuple, Union

#
# External Imports
import gradio as gr
from PIL import Image
#
# Local Imports
from App_Function_Libraries.Chat import chat, load_characters, save_chat_history_to_db_wrapper
from App_Function_Libraries.Gradio_UI.Chat_ui import chat_wrapper
from App_Function_Libraries.Gradio_UI.Writing_tab import generate_writing_feedback
#
########################################################################################################################
#
# Single-Character chat Functions:


def chat_with_character(user_message, history, char_data, api_name_input, api_key):
    if char_data is None:
        return history, "Please import a character card first."

    bot_message = generate_writing_feedback(user_message, char_data['name'], "Overall", api_name_input,
                                            api_key)
    history.append((user_message, bot_message))
    return history, ""


def import_character_card(file):
    if file is None:
        logging.warning("No file provided for character card import")
        return None
    try:
        if file.name.lower().endswith(('.png', '.webp')):
            logging.info(f"Attempting to import character card from image: {file.name}")
            json_data = extract_json_from_image(file)
            if json_data:
                logging.info("JSON data extracted from image, attempting to parse")
                card_data = import_character_card_json(json_data)
                if card_data:
                    # Save the image data
                    with Image.open(file) as img:
                        img_byte_arr = io.BytesIO()
                        img.save(img_byte_arr, format='PNG')
                        card_data['image'] = base64.b64encode(img_byte_arr.getvalue()).decode('utf-8')
                return card_data
            else:
                logging.warning("No JSON data found in the image")
        else:
            logging.info(f"Attempting to import character card from JSON file: {file.name}")
            content = file.read().decode('utf-8')
            return import_character_card_json(content)
    except Exception as e:
        logging.error(f"Error importing character card: {e}")
    return None


def import_character_card_json(json_content):
    try:
        # Remove any leading/trailing whitespace
        json_content = json_content.strip()

        # Log the first 100 characters of the content
        logging.debug(f"JSON content (first 100 chars): {json_content[:100]}...")

        card_data = json.loads(json_content)
        logging.debug(f"Parsed JSON data keys: {list(card_data.keys())}")
        if 'spec' in card_data and card_data['spec'] == 'chara_card_v2':
            logging.info("Detected V2 character card")
            return card_data['data']
        else:
            logging.info("Assuming V1 character card")
            return card_data
    except json.JSONDecodeError as e:
        logging.error(f"JSON decode error: {e}")
        logging.error(f"Problematic JSON content: {json_content[:500]}...")
    except Exception as e:
        logging.error(f"Unexpected error parsing JSON: {e}")
    return None


def extract_json_from_image(image_file):
    logging.debug(f"Attempting to extract JSON from image: {image_file.name}")
    try:
        with Image.open(image_file) as img:
            logging.debug("Image opened successfully")
            metadata = img.info
            if 'chara' in metadata:
                logging.debug("Found 'chara' in image metadata")
                chara_content = metadata['chara']
                logging.debug(f"Content of 'chara' metadata (first 100 chars): {chara_content[:100]}...")
                try:
                    decoded_content = base64.b64decode(chara_content).decode('utf-8')
                    logging.debug(f"Decoded content (first 100 chars): {decoded_content[:100]}...")
                    return decoded_content
                except Exception as e:
                    logging.error(f"Error decoding base64 content: {e}")

            logging.debug("'chara' not found in metadata, checking for base64 encoded data")
            raw_data = img.tobytes()
            possible_json = raw_data.split(b'{', 1)[-1].rsplit(b'}', 1)[0]
            if possible_json:
                try:
                    decoded = base64.b64decode(possible_json).decode('utf-8')
                    if decoded.startswith('{') and decoded.endswith('}'):
                        logging.debug("Found and decoded base64 JSON data")
                        return '{' + decoded + '}'
                except Exception as e:
                    logging.error(f"Error decoding base64 data: {e}")

            logging.warning("No JSON data found in the image")
    except Exception as e:
        logging.error(f"Error extracting JSON from image: {e}")
    return None


def load_chat_history(file):
    try:
        content = file.read().decode('utf-8')
        chat_data = json.loads(content)
        return chat_data['history'], chat_data['character']
    except Exception as e:
        logging.error(f"Error loading chat history: {e}")
        return None, None


def create_character_card_interaction_tab():
    with gr.TabItem("Chat with a Character Card"):
        gr.Markdown("# Chat with a Character Card")
        with gr.Row():
            with gr.Column(scale=1):
                character_image = gr.Image(label="Character Image", type="filepath")
                character_card_upload = gr.File(label="Upload Character Card")
                import_card_button = gr.Button("Import Character Card")
                load_characters_button = gr.Button("Load Existing Characters")
                from App_Function_Libraries.Chat import get_character_names
                character_dropdown = gr.Dropdown(label="Select Character", choices=get_character_names())
                user_name_input = gr.Textbox(label="Your Name", placeholder="Enter your name here")
                api_name_input = gr.Dropdown(
                    choices=[None, "Local-LLM", "OpenAI", "Anthropic", "Cohere", "Groq", "DeepSeek", "Mistral",
                             "OpenRouter", "Llama.cpp", "Kobold", "Ooba", "Tabbyapi", "VLLM", "ollama", "HuggingFace",
                             "Custom-OpenAI-API"],
                    value=None,
                    # FIXME - make it so the user cant' click `Send Message` without first setting an API + Chatbot
                    label="API for Interaction(Mandatory)"
                )
                api_key_input = gr.Textbox(label="API Key (if not set in Config_Files/config.txt)",
                                           placeholder="Enter your API key here", type="password")
                temperature_slider = gr.Slider(minimum=0.0, maximum=2.0, value=0.7, step=0.05, label="Temperature")
                import_chat_button = gr.Button("Import Chat History")
                chat_file_upload = gr.File(label="Upload Chat History JSON", visible=False)

            with gr.Column(scale=2):
                chat_history = gr.Chatbot(label="Conversation", height=800)
                user_input = gr.Textbox(label="Your message")
                send_message_button = gr.Button("Send Message")
                regenerate_button = gr.Button("Regenerate Last Message")
                clear_chat_button = gr.Button("Clear Chat")
                chat_media_name = gr.Textbox(label="Custom Chat Name(optional)", visible=True)
                save_chat_history_to_db = gr.Button("Save Chat History to DataBase")
                save_status = gr.Textbox(label="Save Status", interactive=False)

        character_data = gr.State(None)
        user_name = gr.State("")

    def import_chat_history(file, current_history, char_data):
        loaded_history, char_name = load_chat_history(file)
        if loaded_history is None:
            return current_history, char_data, "Failed to load chat history."

        # Check if the loaded chat is for the current character
        if char_data and char_data.get('name') != char_name:
            return current_history, char_data, f"Warning: Loaded chat is for character '{char_name}', but current character is '{char_data.get('name')}'. Chat not imported."

        # If no character is selected, try to load the character from the chat
        if not char_data:
            new_char_data = load_character(char_name)[0]
            if new_char_data:
                char_data = new_char_data
            else:
                return current_history, char_data, f"Warning: Character '{char_name}' not found. Please select the character manually."

        return loaded_history, char_data, f"Chat history for '{char_name}' imported successfully."

    def import_character(file):
        card_data = import_character_card(file)
        if card_data:
            from App_Function_Libraries.Chat import save_character
            save_character(card_data)
            return card_data, gr.update(choices=get_character_names())
        else:
            return None, gr.update()

    def load_character(name):
        from App_Function_Libraries.Chat import load_characters
        characters = load_characters()
        char_data = characters.get(name)
        if char_data:
            first_message = char_data.get('first_mes', "Hello! I'm ready to chat.")
            return char_data, [(None, first_message)] if first_message else [], None
        return None, [], None

    def load_character_image(name):
        from App_Function_Libraries.Chat import load_characters
        characters = load_characters()
        char_data = characters.get(name)
        if char_data and 'image_path' in char_data:
            image_path = char_data['image_path']
            if os.path.exists(image_path):
                return image_path
            else:
                logging.warning(f"Image file not found: {image_path}")
        return None

    def load_character_and_image(name):
        char_data, chat_history, _ = load_character(name)
        image_path = load_character_image(name)
        logging.debug(f"Character: {name}")
        logging.debug(f"Character data: {char_data}")
        logging.debug(f"Image path: {image_path}")
        return char_data, chat_history, image_path

    def character_chat_wrapper(message, history, char_data, api_endpoint, api_key, temperature, user_name):
        logging.debug("Entered character_chat_wrapper")
        if char_data is None:
            return "Please select a character first.", history

        if not user_name:
            user_name = "User"

        char_name = char_data.get('name', 'AI Assistant')

        # Prepare the character's background information
        char_background = f"""

        Name: {char_name}

        Description: {char_data.get('description', 'N/A')}

        Personality: {char_data.get('personality', 'N/A')}

        Scenario: {char_data.get('scenario', 'N/A')}

        """

        # Prepare the system prompt for character impersonation
        system_message = f"""You are roleplaying as {char_name}, the character described below. Respond to the user's messages in character, maintaining the personality and background provided. Do not break character or refer to yourself as an AI. Always refer to yourself as "{char_name}" and refer to the user as "{user_name}".



        {char_background}



        Additional instructions: {char_data.get('post_history_instructions', '')}

        """

        # Prepare media_content and selected_parts
        media_content = {
            'id': char_name,
            'title': char_name,
            'content': char_background,
            'description': char_data.get('description', ''),
            'personality': char_data.get('personality', ''),
            'scenario': char_data.get('scenario', '')
        }
        selected_parts = ['description', 'personality', 'scenario']

        prompt = char_data.get('post_history_instructions', '')

        # Prepare the input for the chat function
        if not history:
            full_message = f"{prompt}\n\n{user_name}: {message}" if prompt else f"{user_name}: {message}"
        else:
            full_message = f"{user_name}: {message}"

        # Call the chat function
        bot_message = chat(
            full_message,
            history,
            media_content,
            selected_parts,
            api_endpoint,
            api_key,
            prompt,
            temperature,
            system_message
        )

        # Update history
        history.append((message, bot_message))
        return history

    def save_chat_history(history, character_name):
        # Create the Saved_Chats folder if it doesn't exist
        save_directory = "Saved_Chats"
        os.makedirs(save_directory, exist_ok=True)

        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"chat_history_{character_name}_{timestamp}.json"
        filepath = os.path.join(save_directory, filename)

        chat_data = {
            "character": character_name,
            "timestamp": timestamp,
            "history": history
        }

        try:
            with open(filepath, 'w', encoding='utf-8') as f:
                json.dump(chat_data, f, ensure_ascii=False, indent=2)
            return filepath
        except Exception as e:
            return f"Error saving chat: {str(e)}"

    def save_current_chat(history, char_data):
        if not char_data or not history:
            return "No chat to save or character not selected."

        character_name = char_data.get('name', 'Unknown')
        result = save_chat_history(history, character_name)
        if result.startswith("Error"):
            return result
        return f"Chat saved successfully as {result}"

    def regenerate_last_message(history, char_data, api_name, api_key, temperature, user_name):
        if not history:
            return history

        last_user_message = history[-1][0]
        new_history = history[:-1]

        return character_chat_wrapper(last_user_message, new_history, char_data, api_name, api_key, temperature,
                                      user_name)

    import_chat_button.click(
        fn=lambda: gr.update(visible=True),
        outputs=chat_file_upload
    )

    chat_file_upload.change(
        fn=import_chat_history,
        inputs=[chat_file_upload, chat_history, character_data],
        outputs=[chat_history, character_data, save_status]
    )

    def update_character_info(name):
        from App_Function_Libraries.Chat import load_characters
        characters = load_characters()
        char_data = characters.get(name)

        image_path = char_data.get('image_path') if char_data else None

        logging.debug(f"Character: {name}")
        logging.debug(f"Character data: {char_data}")
        logging.debug(f"Image path: {image_path}")

        if image_path:
            if os.path.exists(image_path):
                logging.debug(f"Image file exists at {image_path}")
                if os.access(image_path, os.R_OK):
                    logging.debug(f"Image file is readable")
                else:
                    logging.warning(f"Image file is not readable: {image_path}")
                    image_path = None
            else:
                logging.warning(f"Image file does not exist: {image_path}")
                image_path = None
        else:
            logging.warning("No image path provided for the character")

        return char_data, None, image_path  # Return None for chat_history

    def on_character_select(name):
        logging.debug(f"Character selected: {name}")
        return update_character_info_with_error_handling(name)

    def clear_chat_history():
        return [], None  # Return empty list for chat_history and None for character_data

    def update_character_info_with_error_handling(name):
        logging.debug(f"Entering update_character_info_with_error_handling for character: {name}")
        try:
            char_data, _, image_path = update_character_info(name)
            logging.debug(f"Retrieved data: char_data={bool(char_data)}, image_path={image_path}")

            if char_data:
                first_message = char_data.get('first_mes', "Hello! I'm ready to chat.")
                chat_history = [(None, first_message)] if first_message else []
            else:
                chat_history = []

            logging.debug(f"Created chat_history with length: {len(chat_history)}")

            if image_path and os.path.exists(image_path):
                logging.debug(f"Image file exists at {image_path}")
                return char_data, chat_history, image_path
            else:
                logging.warning(f"Image not found or invalid path: {image_path}")
                return char_data, chat_history, None
        except Exception as e:
            logging.error(f"Error updating character info: {str(e)}", exc_info=True)
            return None, [], None
        finally:
            logging.debug("Exiting update_character_info_with_error_handling")

    # Define States for conversation_id and media_content, which are required for saving chat history
    conversation_id = gr.State(str(uuid.uuid4()))
    media_content = gr.State({})

    import_card_button.click(
        fn=import_character,
        inputs=[character_card_upload],
        outputs=[character_data, character_dropdown]
    )

    load_characters_button.click(
        fn=lambda: gr.update(choices=get_character_names()),
        outputs=character_dropdown
    )

    clear_chat_button.click(
        fn=clear_chat_history,
        inputs=[],
        outputs=[chat_history, character_data]
    )

    character_dropdown.change(
        fn=on_character_select,
        inputs=[character_dropdown],
        outputs=[character_data, chat_history, character_image]
    )

    send_message_button.click(
        fn=character_chat_wrapper,
        inputs=[user_input, chat_history, character_data, api_name_input, api_key_input, temperature_slider,
                user_name_input],
        outputs=[chat_history]
    ).then(lambda: "", outputs=user_input)

    regenerate_button.click(
        fn=regenerate_last_message,
        inputs=[chat_history, character_data, api_name_input, api_key_input, temperature_slider, user_name_input],
        outputs=[chat_history]
    )

    user_name_input.change(
        fn=lambda name: name,
        inputs=[user_name_input],
        outputs=[user_name]
    )

    # FIXME - Implement saving chat history to database; look at Chat_UI.py for reference
    save_chat_history_to_db.click(
        save_chat_history_to_db_wrapper,
        inputs=[chat_history, conversation_id, media_content, chat_media_name],
        outputs=[conversation_id, gr.Textbox(label="Save Status")]
    )

    return character_data, chat_history, user_input, user_name, character_image


#
# End of Character chat tab
######################################################################################################################
#
# Multi-Character Chat Interface

def character_interaction_setup():
    characters = load_characters()
    return characters, [], None, None


def extract_character_response(response: Union[str, Tuple]) -> str:
    if isinstance(response, tuple):
        # If it's a tuple, try to extract the first string element
        for item in response:
            if isinstance(item, str):
                return item.strip()
        # If no string found, return a default message
        return "I'm not sure how to respond."
    elif isinstance(response, str):
        # If it's already a string, just return it
        return response.strip()
    else:
        # For any other type, return a default message
        return "I'm having trouble forming a response."

# def process_character_response(response: str) -> str:
#     # Remove any leading explanatory text before the first '---'
#     parts = response.split('---')
#     if len(parts) > 1:
#         return '---' + '---'.join(parts[1:])
#     return response.strip()
def process_character_response(response: Union[str, Tuple]) -> str:
    if isinstance(response, tuple):
        response = ' '.join(str(item) for item in response if isinstance(item, str))

    if isinstance(response, str):
        # Remove any leading explanatory text before the first '---'
        parts = response.split('---')
        if len(parts) > 1:
            return '---' + '---'.join(parts[1:])
        return response.strip()
    else:
        return "I'm having trouble forming a response."

def character_turn(characters: Dict, conversation: List[Tuple[str, str]],

                   current_character: str, other_characters: List[str],

                   api_endpoint: str, api_key: str, temperature: float,

                   scenario: str = "") -> Tuple[List[Tuple[str, str]], str]:
    if not current_character or current_character not in characters:
        return conversation, current_character

    if not conversation and scenario:
        conversation.append(("Scenario", scenario))

    current_char = characters[current_character]
    other_chars = [characters[char] for char in other_characters if char in characters and char != current_character]

    prompt = f"{current_char['name']}'s personality: {current_char['personality']}\n"
    for char in other_chars:
        prompt += f"{char['name']}'s personality: {char['personality']}\n"
    prompt += "Conversation so far:\n" + "\n".join([f"{sender}: {message}" for sender, message in conversation])
    prompt += f"\n\nHow would {current_char['name']} respond?"

    try:
        response = chat_wrapper(prompt, conversation, {}, [], api_endpoint, api_key, "", None, False, temperature, "")
        processed_response = process_character_response(response)
        conversation.append((current_char['name'], processed_response))
    except Exception as e:
        error_message = f"Error generating response: {str(e)}"
        conversation.append((current_char['name'], error_message))

    return conversation, current_character


def character_interaction(character1: str, character2: str, api_endpoint: str, api_key: str,

                          num_turns: int, scenario: str, temperature: float,

                          user_interjection: str = "") -> List[str]:
    characters = load_characters()
    char1 = characters[character1]
    char2 = characters[character2]
    conversation = []
    current_speaker = char1
    other_speaker = char2

    # Add scenario to the conversation start
    if scenario:
        conversation.append(f"Scenario: {scenario}")

    for turn in range(num_turns):
        # Construct the prompt for the current speaker
        prompt = f"{current_speaker['name']}'s personality: {current_speaker['personality']}\n"
        prompt += f"{other_speaker['name']}'s personality: {other_speaker['personality']}\n"
        prompt += f"Conversation so far:\n" + "\n".join(
            [msg if isinstance(msg, str) else f"{msg[0]}: {msg[1]}" for msg in conversation])

        # Add user interjection if provided
        if user_interjection and turn == num_turns // 2:
            prompt += f"\n\nUser interjection: {user_interjection}\n"
            conversation.append(f"User: {user_interjection}")

        prompt += f"\n\nHow would {current_speaker['name']} respond?"

        # FIXME - figure out why the double print is happening
        # Get response from the LLM
        response = chat_wrapper(prompt, conversation, {}, [], api_endpoint, api_key, "", None, False, temperature, "")

        # Add the response to the conversation
        conversation.append((current_speaker['name'], response))

        # Switch speakers
        current_speaker, other_speaker = other_speaker, current_speaker

    # Convert the conversation to a list of strings for output
    return [f"{msg[0]}: {msg[1]}" if isinstance(msg, tuple) else msg for msg in conversation]


def create_multiple_character_chat_tab():
    with gr.TabItem("Multi-Character Chat"):
        characters, conversation, current_character, other_character = character_interaction_setup()

        with gr.Blocks() as character_interaction:
            gr.Markdown("# Multi-Character Chat")

            with gr.Row():
                num_characters = gr.Dropdown(label="Number of Characters", choices=["2", "3", "4"], value="2")
                character_selectors = [gr.Dropdown(label=f"Character {i + 1}", choices=list(characters.keys())) for i in
                                       range(4)]

            api_endpoint = gr.Dropdown(label="API Endpoint",
                                       choices=["OpenAI", "Anthropic", "Local-LLM", "Cohere", "Groq", "DeepSeek",
                                                "Mistral", "OpenRouter"])
            api_key = gr.Textbox(label="API Key (if required)", type="password")
            temperature = gr.Slider(label="Temperature", minimum=0.1, maximum=1.0, step=0.1, value=0.7)
            scenario = gr.Textbox(label="Scenario (optional)", lines=3)

            chat_display = gr.Chatbot(label="Character Interaction")
            current_index = gr.State(0)

            next_turn_btn = gr.Button("Next Turn")
            narrator_input = gr.Textbox(label="Narrator Input", placeholder="Add a narration or description...")
            add_narration_btn = gr.Button("Add Narration")
            error_box = gr.Textbox(label="Error Messages", visible=False)
            reset_btn = gr.Button("Reset Conversation")
            chat_media_name = gr.Textbox(label="Custom Chat Name(optional)", visible=True)
            save_chat_history_to_db = gr.Button("Save Chat History to DataBase")

            def update_character_selectors(num):
                return [gr.update(visible=True) if i < int(num) else gr.update(visible=False) for i in range(4)]

            num_characters.change(
                update_character_selectors,
                inputs=[num_characters],
                outputs=character_selectors
            )

            def reset_conversation():
                return [], 0, gr.update(value=""), gr.update(value="")

            def take_turn(conversation, current_index, char1, char2, char3, char4, api_endpoint, api_key, temperature,

                          scenario):
                char_selectors = [char for char in [char1, char2, char3, char4] if char]  # Remove None values
                num_chars = len(char_selectors)

                if num_chars == 0:
                    return conversation, current_index  # No characters selected, return without changes

                if not conversation:
                    conversation = []
                    if scenario:
                        conversation.append(("Scenario", scenario))

                current_character = char_selectors[current_index % num_chars]
                next_index = (current_index + 1) % num_chars

                prompt = f"Character speaking: {current_character}\nOther characters: {', '.join(char for char in char_selectors if char != current_character)}\n"
                prompt += "Generate the next part of the conversation, including character dialogues and actions. Characters should speak in first person."

                response, new_conversation, _ = chat_wrapper(prompt, conversation, {}, [], api_endpoint, api_key, "",
                                                             None, False, temperature, "")

                # Format the response
                formatted_lines = []
                for line in response.split('\n'):
                    if ':' in line:
                        speaker, text = line.split(':', 1)
                        formatted_lines.append(f"**{speaker.strip()}**: {text.strip()}")
                    else:
                        formatted_lines.append(line)

                formatted_response = '\n'.join(formatted_lines)

                # Update the last message in the conversation with the formatted response
                if new_conversation:
                    new_conversation[-1] = (new_conversation[-1][0], formatted_response)
                else:
                    new_conversation.append((current_character, formatted_response))

                return new_conversation, next_index

            def add_narration(narration, conversation):
                if narration:
                    conversation.append(("Narrator", narration))
                return conversation, ""

            def take_turn_with_error_handling(conversation, current_index, char1, char2, char3, char4, api_endpoint,

                                              api_key, temperature, scenario):
                try:
                    new_conversation, next_index = take_turn(conversation, current_index, char1, char2, char3, char4,
                                                             api_endpoint, api_key, temperature, scenario)
                    return new_conversation, next_index, gr.update(visible=False, value="")
                except Exception as e:
                    error_message = f"An error occurred: {str(e)}"
                    return conversation, current_index, gr.update(visible=True, value=error_message)

            # Define States for conversation_id and media_content, which are required for saving chat history
            media_content = gr.State({})
            conversation_id = gr.State(str(uuid.uuid4()))

            next_turn_btn.click(
                take_turn_with_error_handling,
                inputs=[chat_display, current_index] + character_selectors + [api_endpoint, api_key, temperature,
                                                                              scenario],
                outputs=[chat_display, current_index, error_box]
            )

            add_narration_btn.click(
                add_narration,
                inputs=[narrator_input, chat_display],
                outputs=[chat_display, narrator_input]
            )

            reset_btn.click(
                reset_conversation,
                outputs=[chat_display, current_index, scenario, narrator_input]
            )

        # FIXME - Implement saving chat history to database; look at Chat_UI.py for reference
        save_chat_history_to_db.click(
            save_chat_history_to_db_wrapper,
            inputs=[chat_display, conversation_id, media_content, chat_media_name],
            outputs=[conversation_id, gr.Textbox(label="Save Status")]
        )

        return character_interaction

#
# End of Multi-Character chat tab
########################################################################################################################
#
# Narrator-Controlled Conversation Tab

# From `Fuzzlewumper` on Reddit.
def create_narrator_controlled_conversation_tab():
    with gr.TabItem("Narrator-Controlled Conversation"):
        gr.Markdown("# Narrator-Controlled Conversation")

        with gr.Row():
            with gr.Column(scale=1):
                api_endpoint = gr.Dropdown(
                    label="API Endpoint",
                    choices=["OpenAI", "Anthropic", "Local-LLM", "Cohere", "Groq", "DeepSeek", "Mistral", "OpenRouter"],
                    value="OpenAI"
                )
                api_key = gr.Textbox(label="API Key (if required)", type="password")
                temperature = gr.Slider(label="Temperature", minimum=0.1, maximum=1.0, step=0.1, value=0.7)

            with gr.Column(scale=2):
                narrator_input = gr.Textbox(
                    label="Narrator Input",
                    placeholder="Set the scene or provide context...",
                    lines=3
                )

        character_inputs = []
        for i in range(4):  # Allow up to 4 characters
            with gr.Row():
                name = gr.Textbox(label=f"Character {i + 1} Name")
                description = gr.Textbox(label=f"Character {i + 1} Description", lines=3)
                character_inputs.append((name, description))

        conversation_display = gr.Chatbot(label="Conversation", height=400)
        user_input = gr.Textbox(label="Your Input (optional)", placeholder="Add your own dialogue or action...")

        with gr.Row():
            generate_btn = gr.Button("Generate Next Interaction")
            reset_btn = gr.Button("Reset Conversation")
            chat_media_name = gr.Textbox(label="Custom Chat Name(optional)", visible=True)
            save_chat_history_to_db = gr.Button("Save Chat History to DataBase")

        error_box = gr.Textbox(label="Error Messages", visible=False)

        # Define States for conversation_id and media_content, which are required for saving chat history
        conversation_id = gr.State(str(uuid.uuid4()))
        media_content = gr.State({})

        def generate_interaction(conversation, narrator_text, user_text, api_endpoint, api_key, temperature,

                                 *character_data):
            try:
                characters = [{"name": name.strip(), "description": desc.strip()}
                              for name, desc in zip(character_data[::2], character_data[1::2])
                              if name.strip() and desc.strip()]

                if not characters:
                    raise ValueError("At least one character must be defined.")

                prompt = f"Narrator: {narrator_text}\n\n"
                for char in characters:
                    prompt += f"Character '{char['name']}': {char['description']}\n"
                prompt += "\nGenerate the next part of the conversation, including character dialogues and actions. "
                prompt += "Characters should speak in first person. "
                if user_text:
                    prompt += f"\nIncorporate this user input: {user_text}"
                prompt += "\nResponse:"

                response, conversation, _ = chat_wrapper(prompt, conversation, {}, [], api_endpoint, api_key, "", None,
                                                         False, temperature, "")

                # Format the response
                formatted_lines = []
                for line in response.split('\n'):
                    if ':' in line:
                        speaker, text = line.split(':', 1)
                        formatted_lines.append(f"**{speaker.strip()}**: {text.strip()}")
                    else:
                        formatted_lines.append(line)

                formatted_response = '\n'.join(formatted_lines)

                # Update the last message in the conversation with the formatted response
                if conversation:
                    conversation[-1] = (conversation[-1][0], formatted_response)
                else:
                    conversation.append((None, formatted_response))

                return conversation, gr.update(value=""), gr.update(value=""), gr.update(visible=False, value="")
            except Exception as e:
                error_message = f"An error occurred: {str(e)}"
                return conversation, gr.update(), gr.update(), gr.update(visible=True, value=error_message)

        def reset_conversation():
            return [], gr.update(value=""), gr.update(value=""), gr.update(visible=False, value="")

        generate_btn.click(
            generate_interaction,
            inputs=[conversation_display, narrator_input, user_input, api_endpoint, api_key, temperature] +
                   [input for char_input in character_inputs for input in char_input],
            outputs=[conversation_display, narrator_input, user_input, error_box]
        )

        reset_btn.click(
            reset_conversation,
            outputs=[conversation_display, narrator_input, user_input, error_box]
        )

        # FIXME - Implement saving chat history to database; look at Chat_UI.py for reference
        save_chat_history_to_db.click(
            save_chat_history_to_db_wrapper,
            inputs=[conversation_display, conversation_id, media_content, chat_media_name],
            outputs=[conversation_id, gr.Textbox(label="Save Status")]
        )


    return api_endpoint, api_key, temperature, narrator_input, conversation_display, user_input, generate_btn, reset_btn, error_box

#
# End of Multi-Character chat tab
########################################################################################################################