File size: 15,476 Bytes
124cee1
47b1e4a
 
 
 
 
b04499b
e1d5556
47b1e4a
5f15ad1
 
 
 
26e18bf
5f15ad1
319bb21
5f15ad1
28218a0
5f15ad1
 
 
 
 
b8c48dd
47b1e4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26e18bf
47b1e4a
 
 
8764ad0
 
 
 
 
 
 
 
f87a54b
cc0603d
 
 
 
b8c48dd
cc0603d
 
 
f87a54b
47b1e4a
b8c48dd
 
47b1e4a
 
 
b8c48dd
47b1e4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26e18bf
47b1e4a
26e18bf
 
47b1e4a
 
cc0603d
 
 
47b1e4a
 
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
import openai
import gradio as gr
import os, sys, json
from loguru import logger
import random

openai.api_key = os.environ.get('SessionToken')     
logger.info(f"session_token_: {openai.api_key}")

conversation = ""
user_name = "MH"
bot_name = "bbDemo"

def get_response_from_chatgpt(text):
    #try:
    response_api = openai.Completion.create(engine='text-davinci-003', prompt=str(text), max_tokens=50)
    response_str = response_api["choices"][0]["text"].replace("\n", "")
    response_str = response_str.split(user_name + ": ",  1)[0].split(bot_name + ": ", 1)[0]
    print("RESPONSE response_api", response_api)
    print("RESPONSE response_str ", response_str)
    response = response_str
    logger.info(f"Response: [{response_api}]")
    logger.info(f"conversation_id_: [{response}]")  

    return response

start_work = """async() => {
    function isMobile() {
        try {
            document.createEvent("TouchEvent"); return true;
        } catch(e) {
            return false; 
        }
    }
	function getClientHeight()
	{
	  var clientHeight=0;
	  if(document.body.clientHeight&&document.documentElement.clientHeight) {
		var clientHeight = (document.body.clientHeight<document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;
	  } else {
		var clientHeight = (document.body.clientHeight>document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;
	  }
	  return clientHeight;
	}
 
    function setNativeValue(element, value) {
      const valueSetter = Object.getOwnPropertyDescriptor(element.__proto__, 'value').set;
      const prototype = Object.getPrototypeOf(element);
      const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
      
      if (valueSetter && valueSetter !== prototypeValueSetter) {
            prototypeValueSetter.call(element, value);
      } else {
            valueSetter.call(element, value);
      }
    }
    function save_conversation(chatbot) {        
        var conversations = new Array();
        for (var i = 0; i < chatbot.children.length; i++) {
            conversations[i] = chatbot.children[i].innerHTML;
        }
        var json_str = JSON.stringify(conversations);
        localStorage.setItem('chatgpt_conversations', json_str);
    }
    function load_conversation(chatbot) {
        var json_str = localStorage.getItem('chatgpt_conversations');
        if (json_str) {
            conversations = JSON.parse(json_str);
            for (var i = 0; i < conversations.length; i++) {
                var new_div = document.createElement("div");
                if((i%2)===0){
                    new_div.className = "px-3 py-2 rounded-[22px] rounded-br-none text-white text-sm chat-message svelte-rct66g";
                    new_div.style.backgroundColor = "#16a34a"; 
                } else {
                    new_div.className = "px-3 py-2 rounded-[22px] rounded-bl-none place-self-start text-white text-sm chat-message svelte-rct66g";
                    new_div.style.backgroundColor = "#2563eb"; 
                    if (conversations[i].indexOf("<img ") == 0) { 
                        new_div.style.width = "80%"; 
                        new_div.style.padding = "0.2rem"; 
                    }                
                }
                new_div.innerHTML = conversations[i];
                chatbot.appendChild(new_div);
            }
        }
    }
    var gradioEl = document.querySelector('body > gradio-app').shadowRoot;
    if (!gradioEl) {
        gradioEl = document.querySelector('body > gradio-app');
    }
    
    if (typeof window['gradioEl'] === 'undefined') {
        window['gradioEl'] = gradioEl;
       
        const page1 = window['gradioEl'].querySelectorAll('#page_1')[0];
        const page2 = window['gradioEl'].querySelectorAll('#page_2')[0]; 
    
        page1.style.display = "none";
        page2.style.display = "block";
        window['div_count'] = 0;
        window['chat_bot'] = window['gradioEl'].querySelectorAll('#chat_bot')[0];
        window['chat_bot1'] = window['gradioEl'].querySelectorAll('#chat_bot1')[0];   
        chat_row = window['gradioEl'].querySelectorAll('#chat_row')[0]; 
        prompt_row = window['gradioEl'].querySelectorAll('#prompt_row')[0]; 
        window['chat_bot1'].children[1].textContent = '';
        
        clientHeight = getClientHeight();
        if (isMobile()) {
            output_htmls = window['gradioEl'].querySelectorAll('.output-html');
            for (var i = 0; i < output_htmls.length; i++) {
               output_htmls[i].style.display = "none";
            }
            new_height = (clientHeight - 250) + 'px';
        } else {
            new_height = (clientHeight - 350) + 'px';
        }
        chat_row.style.height = new_height;
        window['chat_bot'].style.height = new_height;
        window['chat_bot'].children[2].style.height = new_height;
        window['chat_bot1'].style.height = new_height;
        window['chat_bot1'].children[2].style.height = new_height;
        prompt_row.children[0].style.flex = 'auto';
        prompt_row.children[0].style.width = '100%';
        window['gradioEl'].querySelectorAll('#chat_radio')[0].style.flex = 'auto';
        window['gradioEl'].querySelectorAll('#chat_radio')[0].style.width = '100%';        
        prompt_row.children[0].setAttribute('style','flex-direction: inherit; flex: 1 1 auto; width: 100%;border-color: green;border-width: 1px !important;')
        window['chat_bot1'].children[1].setAttribute('style', 'border-bottom-right-radius:0;top:unset;bottom:0;padding-left:0.1rem');
        window['gradioEl'].querySelectorAll('#btns_row')[0].children[0].setAttribute('style', 'min-width: min(10px, 100%); flex-grow: 1');
        window['gradioEl'].querySelectorAll('#btns_row')[0].children[1].setAttribute('style', 'min-width: min(10px, 100%); flex-grow: 1');
        
        load_conversation(window['chat_bot1'].children[2].children[0]);
        window['chat_bot1'].children[2].scrollTop = window['chat_bot1'].children[2].scrollHeight;
        
        window['gradioEl'].querySelectorAll('#clear-btn')[0].onclick = function(e){
            if (confirm('Clear all outputs?')==true) {
                 window['chat_bot1'].children[2].children[0].innerHTML = '';
                 save_conversation(window['chat_bot1'].children[2].children[0]);
            }
        }
 
        window['prevPrompt'] = '';
        window['doCheckPrompt'] = 0;
        window['prevImgSrc'] = '';
        window['checkChange'] = function checkChange() {
            try {
                if (window['gradioEl'].querySelectorAll('.gr-radio')[0].checked) {
                    if (window['chat_bot'].children[2].children[0].children.length > window['div_count']) {
                        new_len = window['chat_bot'].children[2].children[0].children.length - window['div_count'];
                        for (var i = 0; i < new_len; i++) { 
                            new_div = window['chat_bot'].children[2].children[0].children[window['div_count'] + i].cloneNode(true);
                            window['chat_bot1'].children[2].children[0].appendChild(new_div);
                        }
                        window['div_count'] = chat_bot.children[2].children[0].children.length;
                        window['chat_bot1'].children[2].scrollTop = window['chat_bot1'].children[2].scrollHeight;
                        save_conversation(window['chat_bot1'].children[2].children[0]);
                    }
                    if (window['chat_bot'].children[0].children.length > 1) {
                        window['chat_bot1'].children[1].textContent = window['chat_bot'].children[0].children[1].textContent;
                    } else {
                        window['chat_bot1'].children[1].textContent = '';
                    }
                } else {
                    texts = window['gradioEl'].querySelectorAll('textarea');
                    text0 = texts[0];    
                    text1 = texts[1];
                    img_index = 0;
                    text_value = text1.value;
                    if (window['doCheckPrompt'] === 0 && window['prevPrompt'] !== text_value) {
                            console.log('_____new prompt___[' + text_value + ']_');
                            window['doCheckPrompt'] = 1;
                            window['prevPrompt'] = text_value;
 
                            tabitems = window['gradioEl'].querySelectorAll('.tabitem');
                            for (var i = 0; i < tabitems.length; i++) {   
                                inputText = tabitems[i].children[0].children[1].children[0].querySelectorAll('.gr-text-input')[0];
                                setNativeValue(inputText, text_value);
                                inputText.dispatchEvent(new Event('input', { bubbles: true }));
                            }                            
                            setTimeout(function() {
                                btns = window['gradioEl'].querySelectorAll('button');
                                for (var i = 0; i < btns.length; i++) {
                                    if (['Generate image','Run'].includes(btns[i].innerText)) {
                                        btns[i].click();                
                                    }
                                }
                                window['doCheckPrompt'] = 0;
                            }, 10);                   
                    }
                    tabitems = window['gradioEl'].querySelectorAll('.tabitem');
                    imgs = tabitems[img_index].children[0].children[1].children[1].querySelectorAll("img");
                    if (imgs.length > 0) {
                        if (window['prevImgSrc'] !== imgs[0].src) {
                            var user_div = document.createElement("div");
                            user_div.className = "px-3 py-2 rounded-[22px] rounded-br-none text-white text-sm chat-message svelte-rct66g";
                            user_div.style.backgroundColor = "#16a34a"; 
                            user_div.innerHTML = "<p>" + text0.value + "</p>";
                            window['chat_bot1'].children[2].children[0].appendChild(user_div);
                            var bot_div = document.createElement("div");
                            bot_div.className = "px-3 py-2 rounded-[22px] rounded-bl-none place-self-start text-white text-sm chat-message svelte-rct66g";
                            bot_div.style.backgroundColor = "#2563eb"; 
                            bot_div.style.width = "80%"; 
                            bot_div.style.padding = "0.2rem"; 
                            bot_div.appendChild(imgs[0].cloneNode(true));
                            window['chat_bot1'].children[2].children[0].appendChild(bot_div);
                            
                            window['chat_bot1'].children[2].scrollTop = window['chat_bot1'].children[2].scrollHeight;
                            window['prevImgSrc'] = imgs[0].src;
                            save_conversation(window['chat_bot1'].children[2].children[0]);
                        }
                    }
                    if (tabitems[img_index].children[0].children[1].children[1].children[0].children.length > 1) {
                        window['chat_bot1'].children[1].textContent = tabitems[img_index].children[0].children[1].children[1].children[0].textContent;
                    } else {
                        window['chat_bot1'].children[1].textContent = '';
                    }                              
                }
              
            } catch(e) {
            }        
        }
        window['checkChange_interval'] = window.setInterval("window.checkChange()", 500);         
    }
   
    return false;
}"""

space_ids = {
            "spaces/stabilityai/stable-diffusion":"Stable Diffusion 2.1",
            }

tab_actions = []
tab_titles = []

for space_id in space_ids.keys():
    print(space_id, space_ids[space_id])
    try:
        tab = gr.Interface.load(space_id)
        tab_actions.append(tab)
        tab_titles.append(space_ids[space_id])
    except Exception as e:
        logger.info(f"load_fail__{space_id}_{e}")
        
def chat(input0, input1, chat_radio, chat_history):
    out_chat = []
    if chat_history != '':
        out_chat = json.loads(chat_history)
    #if chat_radio == "Talk to chatGPT":
    response = get_response_from_chatgpt(input0)
    out_chat.append((input0, response))
    chat_history = json.dumps(out_chat)

    logger.info(f"out_chat_input0 and input1 {input0} --  {input1}")
    logger.info(f"chat history {chat_history}")
    return out_chat, input1, chat_history

article = """
    <div class="footer">
        <p><a href="https://chat.openai.com/chat" target="_blank">chatGPT</a> 
        by <a href="https://openai.com/" style="text-decoration: underline;" target="_blank">OpenAI</a> - 
        Gradio Demo by 🤗 <a href="https://englishphonetics.net/about-us.html" target="_blank">Eriberto Oliveira</a>
        </p>
    </div>
"""

with gr.Blocks(title='Talk to chatGPT') as demo:
    gr.HTML("<p> This is a demo of the GPT-3 model applied in the chatbot context. </p>")
    gr.HTML("<p> Ask questions and be surprised by the answers</p>")
    with gr.Group(elem_id="page_1", visible=True) as page_1:
        with gr.Box():            
            with gr.Row():
                start_button = gr.Button("Click here to chat!", elem_id="start-btn", visible=True) 
                start_button.click(fn=None, inputs=[], outputs=[], _js=start_work)
                
    with gr.Group(elem_id="page_2", visible=False) as page_2:        
        with gr.Row(elem_id="chat_row"):
            chatbot = gr.Chatbot(elem_id="chat_bot", visible=False).style(color_map=("green", "blue"))
            chatbot1 = gr.Chatbot(elem_id="chat_bot1").style(color_map=("green", "blue"))
        with gr.Row(elem_id="prompt_row"):
            prompt_input0 = gr.Textbox(lines=2, label="prompt",show_label=False)
            prompt_input1 = gr.Textbox(lines=4, label="prompt", visible=False)
            chat_history = gr.Textbox(lines=4, label="prompt", visible=False)
            chat_radio = gr.Radio(["Talk to chatGPT", "Text to Image"], elem_id="chat_radio",value="Talk to chatGPT", show_label=False)
        with gr.Row(elem_id="btns_row"):
            with gr.Column(id="submit_col"):
                submit_btn = gr.Button(value = "submit",elem_id="submit-btn").style(
                        margin=True,
                        rounded=(True, True, True, True),
                        width=100
                    )
            with gr.Column(id="clear_col"):
                clear_btn = gr.Button(value = "clear outputs", elem_id="clear-btn").style(
                        margin=True,
                        rounded=(True, True, True, True),
                        width=100
                    )

            submit_btn.click(fn=chat, 
                             inputs=[prompt_input0, prompt_input1, chat_radio, chat_history], 
                             outputs=[chatbot, prompt_input1, chat_history],
                            )
        with gr.Row(elem_id='tab_img', visible=False).style(height=5):
           tab_img = gr.TabbedInterface(tab_actions, tab_titles) 
    
    gr.HTML(article)
demo.launch(debug = True)