  <!-- index.html -->
  <!DOCTYPE html>
  <html lang="ja">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=0.5">
    <title>頭部型シュミレーターロボット</title>
    <style>
        /* スイッチのスタイル */
        body, html {
            height: 100%;
            margin: 0;
            padding: 0;
        }

        body {
            display: flex;
        }

        h1{
            margin: 2px;
        }

        .switch {
            margin: 1px;
            padding: 12px;
            position: relative;
            display: inline-block;
            width: 40px;
            height: 10px;
        }

        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            -webkit-transition: .4s;
            transition: .4s;
        }

        .slider:before {
            position: absolute;
            content: "";
            height: 26px;
            width: 26px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            -webkit-transition: .4s;
            transition: .4s;
        }

        input:checked + .slider {
            background-color: #2196F3;
        }

        input:focus + .slider {
            box-shadow: 0 0 1px #2196F3;
        }

        input:checked + .slider:before {
            -webkit-transform: translateX(26px);
            -ms-transform: translateX(26px);
            transform: translateX(26px);
        }

        /* スイッチの有効/無効時のテキスト表示 */
        .switch-label {
            margin-left: 2px;
        }

        #result {
            border: 0.5px solid #000; /* 枠線のスタイルを指定 */
            width: 100%;
            padding: 0; /* 内側の余白を指定（お好みで調整） */
            font-size: 25px;
        }

        #left-section, #right-section {
            height: 90%;
            max-height: 90%;
            padding: 20px;
            padding: .2rem;
        }

        #left-section{
            width: 50%;
        }

        #right-section{
            width: 50%;
        }

        .debugpanel {
            padding-top: 10px;
            padding-bottom: 10px;
            display: none;
            background-color: lightgray;
        }

        .inputpanel {
            padding: 0px;
            display: block;
            background-color: white;
        }

        .left-section {
            display: block;
        }

        .left-align {
            text-align: left;
        }
        .right-align {
            text-align: right;
        }

        .chat-container {
            display: flex;
            flex-direction: column;
            background-color: lightcyan;
            overflow-x: hidden;
            overflow-y: auto;
            max-height: 100%;
        }
        .chat-bubble {
            max-width: 60%;
            padding: 10px;
            margin: 5px;
            border-radius: 10px;
            position: relative;
        }
        .user-bubble {
            background-color: #DCF8C6;
            align-self: flex-start;
        }
        .assistant-bubble {
            background-color: #E5E5EA;
            align-self: flex-end;
        }
        .chat-bubble::after {
            content: "";
            position: absolute;
            width: 0;
            height: 0;
            border-style: solid;
        }
        .user-bubble::after {
            border-width: 10px 10px 0 0;
            border-color: #DCF8C6 transparent transparent transparent;
            top: 0;
            left: -10px;
        }
        .assistant-bubble::after {
            border-width: 10px 0 0 10px;
            border-color: #E5E5EA transparent transparent transparent;
            top: 0;
            right: -10px;
        }
        .section {
            width: 100%;
            box-sizing: border-box;
        }
        textarea {
            width: 98%;
            box-sizing: border-box;
            font-size: 20px;
        }

        #user_description, #name_description{
            width: 30%;
            box-sizing: border-box;
        }

        #facerecognition_text,#Interviewsheet_text,#Confirmeditems_text{
            height: 100px;
            box-sizing: border-box;
        }
        select{
            font-size: 20px;
        }

        /* input要素を非表示にする */
        #csvFileInput {
            display: none;
        }

    </style>
  </head>
  <body>
    <div id="left-section" class="section">
        <h1>頭部型シュミレーターロボット</h1>
        <!-- スイッチの有効/無効時のテキスト表示 -->
        <br>
        <label for="nameSelect">◆名前◆</label>
        <br>

        <div  id="hiddenPanelname" class = "inputpanel">
            <textarea id="name_description">はなこ</textarea>
        </div>
        <br/>
        <span>◆どんな人◆</span>
        <br/>
        <div  id="hiddenPanelchara" class = "inputpanel">
            <textarea id="character_description" >女性の患者</textarea>
        </div>
        <br/>
        <span>◆どこで◆</span>
        <br/>
        <div  id="hiddenPanelenvironment" class = "inputpanel">
            <textarea id="environment_description" >病院</textarea>
        </div>
        <br/>

        <span>◆何をしている◆</span>
        <br/>
        <div  id="hiddenPanelcharadoing" class = "inputpanel">
            <textarea id="charadoing_description" >医療面接を受けている</textarea>
        </div>
        <br/>

        <span>◆使用者◆</span>
        <br/>
        <div  id="hiddenPaneluser" class = "inputpanel">
            <textarea id="user_description">医者</textarea>
        </div>        
        <br/>

        <button id="accordion">▼</button>

        <br/>
        <div  id="hiddenPanel" class = "debugpanel">
            <label>Debug</label>
            <br>
            <label class="switch">
                <input type="checkbox" id="switchatq">
                <span class="slider"></span>
            </label>
                <span class="switch-label" id="switchLabel3">自動質問</span>
            <br>
            <label class="switch">
                <input type="checkbox" id="switchatagreement">
                <span class="slider"></span>
            </label>
                <span class="switch-label" id="switchatagreement">あいづち</span>
            <br>
            <label class="switch">
                <input type="checkbox" id="switchfacerecognitionSpeak">
                <span class="slider"></span>
            </label>
                <span class="switch-label" id="switchfacerecognitionSpeak">顔認証で発話</span>
            <br>
            <!-- 声色の選択セレクトボックス -->
            <label for="voiceSelect">◆Voice:</label>
            <select id="voiceSelect">
                <option value="nova" selected>nova</option>
                <option value="alloy">alloy</option>
                <option value="echo">echo</option>
                <option value="fable">fable</option>
                <option value="onyx">onyx</option>
                <option value="nova">nova</option>
                <option value="shimmer">shimmer</option>
            </select>
            <br/>
            <!-- ChatGPT Ver選択プルダウンメニュー -->
            <label for="ChatGPTSelect">◆ChatGPT_Ver:</label>
            <select id="ChatGPTSelect" onchange="ChatGPTSelect()">
                <option value="gpt-4o-mini" selected>Chatgpt-4o-mini</option>
                <option value="gpt-4o">ChatGPT-4o</option>
            </select>
            <br>
            <!-- 音声合成の選択プルダウンメニュー -->
            <label for="speechsynthesis">◆Speech Synthesis:</label>
            <select id="speechsynthesis">
                <option value="OpenAI" selected>OpenAI</option>
                <option value="Google">Google</option>
            </select>
            <br>
            <span>◆Question◆</span>
            <br/>
            <textarea id="input_text"></textarea>
            <br/>
            <button class="directional-button" onmousedown="対話AIデバッグ()">↑</button>

            <br/>
            <span>◆Answer◆</span>
            <br/>
            <textarea id="response_text" disabled></textarea>
            <div id="chat-container"></div>
            <br>
            <span>◆Recognition of instructions◆</span>
            <br/>
            <textarea id="result2" disabled></textarea>
            <br>

            <span>◆Instruction Recognition history◆</span>
            <br/>
            <textarea id="resulthis" disabled></textarea>
            <br>

            <span>◆Face Recognition◆</span>
            <br/>
            <textarea id="facerecognition_text" disabled></textarea>
            <div id="facerecognition-container"></div>

            <span>◆Interview sheet◆</span>
            <br/>
            <textarea id="Interviewsheet_text" disabled></textarea>
            <div id="Interviewsheet-container"></div>

            <span>◆Confirmed items for medical interviews◆</span>
            <br/>
            <textarea id="Confirmeditems_text" disabled></textarea>
            <div id="Confirmeditems_text-container"></div>

            <span>◆Conversation history summary◆</span>
            <br/>
            <textarea id="Conversation_history_summarytext" disabled></textarea>
            <div id="Conversation_history_summarytext-container"></div>

            <span>◆Event Buttons◆</span>
            <br>
            <button class="directional-button" onmousedown="generateResponseSentenceCreation()">例文作成</button>
            <button class="directional-button" onmousedown="generateResponseSummaryCreation()">キャラクタ情報セット</button>
            <button class="directional-button" onmousedown="datareset()">リセット</button>
            <button class="directional-button" onmousedown="generateResponsehistorySummary()">要約</button>
            <button class="directional-button" onmousedown="generateResponsespokenlanguage()">発話生成</button>
            <button class="directional-button" onmousedown="PLC_読み出し()">PLC読み出し</button>
            <br>
            <span>◆Action Buttons◆</span>
            <br>
            <button class="directional-button" onmousedown="OUTPUT('原点復帰:ON')">原点復帰</button>
            <button class="directional-button" onmousedown="OUTPUT('首上:ON')">首上(小)</button>
            <button class="directional-button" onmousedown="OUTPUT('首下:ON')">首下(小)</button>
            <button class="directional-button" onmousedown="OUTPUT('首上高:ON')">首上</button>
            <button class="directional-button" onmousedown="OUTPUT('首下高:ON')">首下</button>
            <br>
            <button class="directional-button" onmousedown="OUTPUT('まばたき開:ON')">まぶた開</button>
            <button class="directional-button" onmousedown="OUTPUT('まばたき閉:ON')">まぶた閉</button>
            <br>
            <button class="directional-button" onmousedown="OUTPUT('Left')">目左</button>
            <button class="directional-button" onmousedown="OUTPUT('Left-Center')">目左中</button>
            <button class="directional-button" onmousedown="OUTPUT('Center')">目中央</button>
            <button class="directional-button" onmousedown="OUTPUT('Right-Center')">目右中</button>
            <button class="directional-button" onmousedown="OUTPUT('Right')">目右</button>
            <br>
            <button class="directional-button" onmousedown="OUTPUT('口開:ON')">口開</button>
            <button class="directional-button" onmousedown="OUTPUT('口閉:ON')">口閉</button>
            <button class="directional-button" onmousedown="OUTPUT('舌上:ON')">舌上</button>
            <button class="directional-button" onmousedown="OUTPUT('舌前:ON')">舌前</button>
            <button class="directional-button" onmousedown="OUTPUT('舌下:ON')">舌下</button>
            <button class="directional-button" onmousedown="OUTPUT('舌戻:ON')">舌戻</button>
            <br>

            <span>◆Response Time◆</span>
            <textarea class="resulttim1" id="resulttim1">音声の文章化完了</textarea><br/>
            <textarea class="resulttim2" id="resulttim2">文章生成AIへの出力開始</textarea><br/>
            <textarea class="resulttim3" id="resulttim3">文章生成AIからの返答完了</textarea><br/>
            <textarea class="resulttim4" id="resulttim4">音声合成AIへの出力開始</textarea><br/>
            <textarea class="resulttim5" id="resulttim5">音声合成AIからの返答完了</textarea><br/>
            
            <span>◆Browser-to-browser communication◆</span>
            <div id="abssegmentname_text"></div>
            <div id="ordsegmentname_text"></div>
            <div id="faceTalking_text"></div>
            <audio id="audioPlayer"></audio>
            <br>

            <span>◆Editing Utterance Data◆</span>
            <br>
            <label for="patientSelect">発話データ:</label>
            <select id="patientSelect">
            </select>

            <label for="selectedText"></label>
            <textarea id="selectedText" rows="4" cols="50"></textarea>

            <button id="updateButton">Create</button>
            <button id="testStartButton">Play</button>
            <br>
            <button class="directional-button" onmousedown="saveCSV();">SAVE</button>
            <input type="file" id="csvFileInput" onchange="loadCSV(event)" />
            <button onclick="document.getElementById('csvFileInput').click()">LOAD</button>            

        </div>
    </div>

    <div id="right-section" class="section">
        <button class="directionalf-button" onmousedown="Reset_history()">リセット</button>
        <input type="text" id="inputFileName" placeholder="Please input file name">
        <button class="download-record" onclick="downloadRecord()">保存</button>
        <br>
        <!-- 言語切り替えプルダウンメニュー -->
        <label for="languageSelect">◆language:</label>
        <select id="languageSelect" onchange="languageChange()">
            <option value="ja-JP" selected>ja-JP</option>
        </select>
        <br>
        <span class="switch-label" id="switchLabel">対話停止中</span>
        <button class="directional-button" onmousedown="generateResponseJudgement()">判定</button>
        <br>
        <label class="switch">
            <input type="checkbox" id="enableSwitch" onchange="toggleSwitch()">
            <span class="slider"></span>
        </label>
        <br/>
        <div id="result" class="chat-container" cols="100" rows="10"></div>
    </div>
    <script src="plcMcProtocol.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script src="https://unpkg.com/axios@0.24.0/dist/axios.min.js"></script>
    <script src="https://unpkg.com/sweetalert@2.1.2/dist/sweetalert.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tone/14.8.39/Tone.min.js"></script>
    <script>
        //テムザックアカウント
        const API_KEY = 'sk-proj-9J93sYX78UNreq0xpy5sT3BlbkFJDrsZdxlTUQhWRNlMGDGm';
        //個人デバッグ用(瀧本)
        //const API_KEY = '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';
        const CahtGPT_URL = "https://api.openai.com/v1/chat/completions";
        let currentLanguage = 'ja-JP'; // デフォルト言語は日本語

        var debug = false;
        let recognition;
        let 口パク = false
        let 音声認識 = false
        let ChatGPT_Use = true;
        let restarttimer1 = 0;
        let restarttimer2 = 0;
        let restarttimer3 = 500;
        let restarttimer4 = 500;

        let 口を開けて = false;

        let languageSelect = document.getElementById('languageSelect');
        let voiceSelect = document.getElementById('voiceSelect');
        let voices = speechSynthesis.getVoices();

        let ChatGPTresponse = true;

        let flag = false;
        
        let conversationHistory = [];

        var audioElement;
        let recognitioning = false;

        // Web Speech APIの初期化が完了したらvoicesを更新
        window.speechSynthesis.onvoiceschanged = updateVoices;
        //認識結果のコンテナ
        let resultDiv = document.getElementById('result');

        let chatGPT_Ver = "gpt-4o-mini"; //gpt-3.5-turbo　gpt-4 gpt-4o

        let isRecognitionStarted = false;

        let 動作時発話 = true; 

        let exampleSentence = [];

        let PLC = true;

        let inputOpenAI = false;

        let audioChunks = [];
        let mediaRecorder;
        let test1 = false;

        //falseで長文を返してくる事がある。
        let characterlimit = true;

        let 目の追従 = false;
        let AT_eyesMv = false;

        //計測用のタイマ
        let response_timer1;
        let response_timer2;
        let response_timer3;
        let response_timer4;
        let response_timer5;
        let response_timer6;

        OUTPUT("頭部自動:OFF");
        OUTPUT("原点復帰:ON");        
        // 関数を実行
        checkConditionAndChangeBackground(API_KEY);
         // 100ミリ秒ごとにperiodicTask関数を実行する
        setInterval(periodicTask, 100);

        // プルダウンメニューを更新する
        function updateDropdown() {
            const patientSelect = document.getElementById('patientSelect');
            // PatientInformation のキーをオプションとして追加
            for (const key in PatientInformation) {
                const option = document.createElement('option');
                option.value = key;
                option.text = key;
                patientSelect.appendChild(option);
            }
        }

        // 選択された項目に基づいてテキストフィールドを更新する
        function updateSelectedText() {
            const selectedKey = document.getElementById('patientSelect').value;
            const selectedText = PatientInformation[selectedKey]; // 選択されたキーの値を取得
            document.getElementById('selectedText').value = selectedText; // テキストエリアに表示
        }

        // ボタンを押した時に getResponsespokenlanguage 関数を呼び出す
        document.getElementById('updateButton').addEventListener('click', function() {
            const selectedKey = document.getElementById('patientSelect').value; // 選択されたキーを取得
            updateSpecificKey(selectedKey); // 選択されたキーを引数として関数を呼び出す
        });

        let speakTextOTTS2_debugPlay = false;
        // ボタンを押した時に speakTextOTTS2 関数を呼び出す
        document.getElementById('testStartButton').addEventListener('click', function() {
            const selectedKey = document.getElementById('patientSelect').value; // 選択されたキーを取得
            speakTextOTTS2_debugPlay = true;
            speakTextOTTS2(selectedKey); // 選択されたキーを引数として関数を呼び出す
        });


        // ページが読み込まれた時にプルダウンメニューを設定
        window.onload = function() {
            firstloadCSV('user1.csv'); // ファイルパスを指定
            // プルダウンが変更された時にテキストエリアも更新
            document.getElementById('patientSelect').addEventListener('change', updateSelectedText);
        };

        //ChatGPTへの出力(応答は発話)
        function generateResponsehistorySummary() {
            let messages = "";

            // 特定の人物名を省く
            var nameToExclude = 'unknown';
            var filteredFacerecognitions = facerecognitions.filter(function(name) {
                return name !== nameToExclude;
            });
            
            var message3 = "今までの内容を要約してください。";
            messages =[{"role": "system", "content": message3 },];

            //頭部ロボットの情報と質問内容と履歴を1つにする
            messages = conversationHistory.concat(messages);
            //messages = exampleSentence.concat(messages);
            getResponseSummaryCreation(messages);
        }

        //ChatGPTへ出力を行い、要約してもらう
        function getResponseSummaryCreation(messages) {
            async function fetchResponse() {
                try {
                    const response = await axios.post(
                        CahtGPT_URL,
                        {
                            "model": chatGPT_Ver,
                            "messages": messages,
                            "max_tokens": 500  // 応答のトークン数を制限
                        },
                        {
                            headers: {
                                "Content-Type": "application/json",
                                Authorization: `Bearer ${API_KEY}`,
                            },
                        }
                    );
                    $("#Conversation_history_summarytext").val(response.data.choices[0].message.content);   
                    } catch (error) {
                        console.error('OpenAI API error:', error);
                        swal("Error", "OpenAI API error. Check console for details.", "error");
                    }
                }
                fetchResponse();
        }

        //keyコードの変更間違い防止
        function checkConditionAndChangeBackground(key) {
            if (key === "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") {
                document.body.style.backgroundColor = "lightyellow";
            } else {
                document.body.style.backgroundColor = ""; // デフォルトの背景色に戻す場合
            }
        }

        function Reset_history(){
            //履歴を削除
            resultDiv.innerHTML = "";
            conversationHistory = [];
            $("#resulthis").val("");
            PatientInformationBuffer = {}; // PatientInformationVoiceBufferのリセット
            // PatientInformationVoiceからPatientInformationVoiceBufferに直接代入
            PatientInformationBuffer = { ...PatientInformation }; // スプレッド構文でコピー
            PatientInformationVoiceBuffer = {}; // PatientInformationVoiceBufferのリセット
            // PatientInformationVoiceからPatientInformationVoiceBufferに直接代入
            PatientInformationVoiceBuffer = { ...PatientInformationVoice }; // スプレッド構文でコピー
        }

        const languageNames = {
            'af': 'Afrikaans',
            'sq': 'Albanian',
            'ar-SA': 'Arabic (Saudi Arabia)',
            'hy': 'Armenian',
            'az': 'Azerbaijani',
            'eu': 'Basque',
            'be': 'Belarusian',
            'bn': 'Bengali',
            'bs': 'Bosnian',
            'bg': 'Bulgarian',
            'ca': 'Catalan',
            'zh-CN': '中文 (简体字)',
            'zh-TW': '中文 (繁體字)',
            'hr': 'Croatian',
            'cs': 'Czech',
            'da': 'Danish',
            'nl': 'Dutch',
            'en-AU': 'English (Australia)',
            'en-CA': 'English (Canada)',
            'en-GB': 'English (United Kingdom)',
            'en-IN': 'English (India)',
            'en-NZ': 'English (New Zealand)',
            'en-US': 'English (United States)',
            'eo': 'Esperanto',
            'et': 'Estonian',
            'fil': 'Filipino',
            'fi': 'Finnish',
            'fr-CA': 'French (Canada)',
            'fr-FR': 'French (France)',
            'gl': 'Galician',
            'ka': 'Georgian',
            'de-DE': 'German',
            'el': 'Greek',
            'gu': 'Gujarati',
            'he': 'Hebrew',
            'hi': 'Hindi',
            'hu': 'Hungarian',
            'is': 'Icelandic',
            'id': 'Indonesian',
            'it-IT': 'Italian',
            'ja-JP': '日本語',
            'kn': 'Kannada',
            'kk': 'Kazakh',
            'ko-KR': '한국어',
            'lv': 'Latvian',
            'lt': 'Lithuanian',
            'mk': 'Macedonian',
            'ms': 'Malay',
            'ml': 'Malayalam',
            'mt': 'Maltese',
            'mr': 'Marathi',
            'mn': 'Mongolian',
            'ne': 'Nepali',
            'no': 'Norwegian',
            'fa': 'Persian',
            'pl': 'Polish',
            'pt-BR': 'Portuguese (Brazil)',
            'pt-PT': 'Portuguese (Portugal)',
            'pa': 'Punjabi',
            'ro': 'Romanian',
            'ru-RU': 'Russian',
            'sr': 'Serbian',
            'si': 'Sinhala',
            'sk': 'Slovak',
            'sl': 'Slovenian',
            'es-ES': 'Español (España)',
            'es-MX': 'Español (México)',
            'sw': 'Swahili',
            'sv-SE': 'Swedish',
            'ta': 'Tamil',
            'te': 'Telugu',
            'th-TH': 'Thai',
            'tr': 'Turkish',
            'uk': 'Ukrainian',
            'ur': 'Urdu',
            'uz': 'Uzbek',
            'vi': 'Vietnamese',
            'cy': 'Welsh',
            'xh': 'Xhosa',
            'zu': 'Zulu'
        };
        
        // 選択可能な言語のリストを更新
        function updateVoices() {
            languageSelect.innerHTML = ''; // 既存の選択肢をクリア

            const uniqueLanguages = new Set(); // 重複を避けるための Set

            voices = speechSynthesis.getVoices();
            voices.forEach(voice => {
                uniqueLanguages.add(voice.lang);
            });

            // 言語ごとの選択肢を生成
            uniqueLanguages.forEach(lang => {
                const option = document.createElement('option');
                option.value = lang;
                option.text = languageNames[lang] || lang; // 言語名が見つからない場合はコードを表示
                if (option.value === currentLanguage) {
                    option.selected = true;
                }
                languageSelect.add(option);
            });
        }

        //言語が選択されたら言語の切り替えと、音声の選択の更新を行う
        function languageChange() {
            changeLanguage();
            generateResponsespokenlanguage();
        }

        //言語の切り替えを行う
        function changeLanguage() {
            // プルダウンメニューで選択された言語に切り替える処理
            currentLanguage = document.getElementById("languageSelect").value;

            //連続的に音声を中断
            recognition.continuous = false;
            recognition.stop();

            //言語を変更
            recognition.lang = currentLanguage;

            //音声認識を再開
            recognition.continuous = true;
        }

        //ChaGPTのVerを変更
        function ChatGPTSelect() {
            // プルダウンメニューで選択されたChat_GPTのVerに切り替える処理
            chatGPT_Ver = document.getElementById("ChatGPTSelect").value;
        }

        //音声認識の有効/無効の切り替え
        function toggleSwitch() {
            const enableSwitch = document.getElementById("enableSwitch");
            const switchLabel = document.getElementById("switchLabel");
            const enableAutoQuestion = document.getElementById("switchatq");
            var rightSection = document.getElementById('right-section');
            var panel = document.getElementById('left-section');

            // スイッチが有効かどうかを確認
            if (enableSwitch.checked) {
                switchLabel.textContent = "対話中";
                音声認識 = true;
                panel.style.display = 'none';
                rightSection.style.width = '100%';
                AT_neckmv = true;
                // 次の動作までの時間をランダムに設定 (500msから1500msの間)
                nextMvTime1 = nodtime1 + Math.floor(Math.random() * 200) + 100;
                nextMvTime2 = nodtime2 + Math.floor(Math.random() * 200) + 100;

                AT_blink = true;
                目の追従 = false;
                AT_eyesMv = true;
                periodicAutoReply_reset();  //自動返答をリセット
                if(inputOpenAI){
                    startRecording();
                }
                if (enableAutoQuestion.checked) {
                    // スイッチがONのとき
                    自動返答 = true;
                } else {
                    // スイッチがOFFのとき
                    自動返答 = false;
                }
            } else {
                switchLabel.textContent = "対話停止中";
                音声認識 = false;
                recognition.stop();
                panel.style.display = 'block';
                rightSection.style.width = '50%';
                AT_neckmv = false;
                AT_blink = false;
                AT_neckmving = false;
                OUTPUT("頭部自動:OFF");
                OUTPUT("原点復帰:ON");
                目の追従 = false;
                AT_eyesMv = false;
                OUTPUT("Center");
                AT_eyesmving = false;
                if(inputOpenAI){
                    stopRecording();
                }
                自動返答 = false;
                nodtime1 = 0;
                nodtime2 = 0;
                口パク = false;
            }
        }

        //対話AIの使用/未使用の切り替え
        function chatGPTSwitch() {
            const enableSwitch = document.getElementById("enableSwitch2");
            const switchLabel = document.getElementById("switchLabel2");

            // スイッチが有効かどうかを確認
            if (enableSwitch.checked) {
                switchLabel.textContent = "対話AI有効";
                ChatGPT_Use = true;
            } else {
                switchLabel.textContent = "対話AI無効";
                ChatGPT_Use = false;
            }
        }

        function removeLastLog() {
            // 吹き出しが存在する場合は、最後の吹き出しを削除する
            if (resultDiv.lastChild) {
                resultDiv.removeChild(resultDiv.lastChild);
            }

            // conversationHistory の最後のメッセージを削除する
            if (conversationHistory.length > 0) {
                conversationHistory.pop(); // 最後の要素を削除
            }
        }

        //会話のログを更新
        function Loghoge(man, text) {
            // 吹き出しのクラスを決定する
            let bubbleClass = (man === "user") ? 'user-bubble' : 'assistant-bubble';
            
            // 吹き出しの要素を作成する
            let bubble = document.createElement('div');
            bubble.className = `chat-bubble ${bubbleClass}`;
            //bubble.innerHTML = `${text}`;

            // 吹き出しにcleanedTextを設定する
            bubble.innerHTML = `${text}`;

            // 吹き出しをコンテナに追加する
            resultDiv.appendChild(bubble);

            // コンテナを自動スクロールして、最新のメッセージが表示されるようにする
            resultDiv.scrollTop = resultDiv.scrollHeight;
            
            // メッセージを履歴に追加
            let message;
            if (man === "user") {
                message = [{ "role": man, "content": text }];
            } else {
                message = [{ "role": "assistant", "content": "  " + text }];
            }
            conversationHistory = conversationHistory.concat(message);
        }

        let lastBubble = null;  // 直前の吹き出しを保持する変数
        let logflag = false;

        function Log(man, text) {
            // 吹き出しのクラスを決定する
            let bubbleClass = (man === "user") ? 'user-bubble' : 'assistant-bubble';

            // 吹き出しを作成するか、上書きするかを決定
            if (lastBubble && lastBubble.className.includes(bubbleClass) && !logflag) {
                // 直前の吹き出しが存在し、かつ同じクラスの吹き出しであり、かつflagがfalseの場合上書きする
                lastBubble.innerHTML = `${text}`;
            } else {
   