RamAnanth1 commited on
Commit
c43093e
·
1 Parent(s): f800d33

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -55
app.py CHANGED
@@ -1,75 +1,114 @@
1
- from pyChatGPT import ChatGPT
2
  import gradio as gr
3
- import os, json
4
- from loguru import logger
5
- import random
6
- from transformers import pipeline
7
- import torch
8
 
9
  device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
10
 
11
  whisper = gr.Interface.load(name="spaces/sanchit-gandhi/whisper-large-v2")
12
- openai_chatgpt = gr.Interface.load(name="spaces/anzorq/chatgpt-demo")
13
 
14
  #input_message.submit([input_message, history], [input_message, chatbot, history])
15
  def translate_or_transcribe(audio, task):
16
  text_result = whisper(audio, None, task, fn_index=0)
17
  return text_result
18
 
19
- def get_response_from_chatbot(text, chat_history):
20
- r = openai_chatgpt(message, chat_history)
21
- response = "Sorry, the chatGPT queue is full. Please try again in some time"
22
- return response
23
 
24
- def chat(message, chat_history):
25
- out_chat = []
26
- if chat_history != '':
27
- out_chat = json.loads(chat_history)
28
- response = get_response_from_chatbot(message, chat_history)
29
- out_chat.append((message, response))
30
- chat_history = json.dumps(out_chat)
31
- logger.info(f"out_chat_: {len(out_chat)}")
32
- return out_chat, chat_history
33
 
 
 
34
 
35
 
36
- with gr.Blocks(title='Talk to chatGPT') as demo:
37
- gr.Markdown("## Talk to chatGPT with your voice in your native language ! ##")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- with gr.Group(elem_id="page_2") as page_2:
40
- with gr.Row(elem_id="chat_row"):
41
- chatbot = gr.Chatbot(elem_id="chat_bot").style(color_map=("green", "blue"))
42
- with gr.Row():
43
- prompt_input_audio = gr.Audio(
44
- source="microphone",
45
- type="filepath",
46
- label="Record Audio Input",
47
-
48
- )
49
- translate_btn = gr.Button("Check Whisper first ? 👍")
50
-
51
- whisper_task = gr.Radio(["translate", "transcribe"], value="transcribe", show_label=False)
52
- with gr.Row(elem_id="prompt_row"):
53
- prompt_input = gr.Textbox(lines=2, label="Input text",show_label=True)
54
- chat_history = gr.Textbox(lines=4, label="prompt", visible=False)
55
- submit_btn = gr.Button(value = "Send to chatGPT",elem_id="submit-btn").style(
56
- margin=True,
57
- rounded=(True, True, True, True),
58
- width=100
59
- )
60
-
61
-
62
 
63
- translate_btn.click(fn=translate_or_transcribe,
64
- inputs=[prompt_input_audio,whisper_task],
65
- outputs=prompt_input
66
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
-
69
- submit_btn.click(fn=chat,
70
- inputs=[prompt_input, chat_history],
71
- outputs=[chatbot, chat_history],
72
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  gr.HTML('''
74
  <p>Note: Please be aware that audio records from iOS devices will not be decoded as expected by Gradio. For the best experience, record your voice from a computer instead of your smartphone ;)</p>
75
  <div class="footer">
@@ -80,4 +119,4 @@ with gr.Blocks(title='Talk to chatGPT') as demo:
80
  ''')
81
  gr.Markdown("![visitor badge](https://visitor-badge.glitch.me/badge?page_id=RamAnanth1.chatGPT_voice)")
82
 
83
- demo.launch(debug = True)
 
 
1
  import gradio as gr
2
+ import os
3
+ import json
4
+ import requests
 
 
5
 
6
  device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
7
 
8
  whisper = gr.Interface.load(name="spaces/sanchit-gandhi/whisper-large-v2")
 
9
 
10
  #input_message.submit([input_message, history], [input_message, chatbot, history])
11
  def translate_or_transcribe(audio, task):
12
  text_result = whisper(audio, None, task, fn_index=0)
13
  return text_result
14
 
 
 
 
 
15
 
 
 
 
 
 
 
 
 
 
16
 
17
+ #Streaming endpoint
18
+ API_URL = "https://api.openai.com/v1/chat/completions" #os.getenv("API_URL") + "/generate_stream"
19
 
20
 
21
+ def predict(inputs, top_p, temperature, openai_api_key, history=[]):
22
+
23
+ payload = {
24
+ "model": "gpt-3.5-turbo",
25
+ "messages": [{"role": "user", "content": f"{inputs}"}],
26
+ "temperature" : 1.0,
27
+ "top_p":1.0,
28
+ "n" : 1,
29
+ "stream": True,
30
+ "presence_penalty":0,
31
+ "frequency_penalty":0,
32
+ }
33
+
34
+ headers = {
35
+ "Content-Type": "application/json",
36
+ "Authorization": f"Bearer {openai_api_key}"
37
+ }
38
+
39
 
40
+ history.append(inputs)
41
+ # make a POST request to the API endpoint using the requests.post method, passing in stream=True
42
+ response = requests.post(API_URL, headers=headers, json=payload, stream=True)
43
+ #response = requests.post(API_URL, headers=headers, json=payload, stream=True)
44
+ token_counter = 0
45
+ partial_words = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
+ counter=0
48
+ for chunk in response.iter_lines():
49
+ if counter == 0:
50
+ counter+=1
51
+ continue
52
+ counter+=1
53
+ # check whether each line is non-empty
54
+ if chunk :
55
+ # decode each line as response data is in bytes
56
+ if len(json.loads(chunk.decode()[6:])['choices'][0]["delta"]) == 0:
57
+ break
58
+ #print(json.loads(chunk.decode()[6:])['choices'][0]["delta"]["content"])
59
+ partial_words = partial_words + json.loads(chunk.decode()[6:])['choices'][0]["delta"]["content"]
60
+ if token_counter == 0:
61
+ history.append(" " + partial_words)
62
+ else:
63
+ history[-1] = partial_words
64
+ chat = [(history[i], history[i + 1]) for i in range(0, len(history) - 1, 2) ] # convert to tuples of list
65
+ token_counter+=1
66
+ yield chat, history # resembles {chatbot: chat, state: history}
67
 
68
+
69
+ def reset_textbox():
70
+ return gr.update(value='')
71
+
72
+ title = """<h1 align="center">🔥ChatGPT API 🚀Streaming🚀</h1>"""
73
+ description = """Language models can be conditioned to act like dialogue agents through a conversational prompt that typically takes the form:
74
+ ```
75
+ User: <utterance>
76
+ Assistant: <utterance>
77
+ User: <utterance>
78
+ Assistant: <utterance>
79
+ ...
80
+ ```
81
+ In this app, you can explore the outputs of a 20B large language model.
82
+ """
83
+ #<a href="https://huggingface.co/spaces/ysharma/ChatGPTwithAPI?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>Duplicate Space with GPU Upgrade for fast Inference & no queue<br>
84
+
85
+ with gr.Blocks(css = """#col_container {width: 700px; margin-left: auto; margin-right: auto;}
86
+ #chatbot {height: 400px; overflow: auto;}""") as demo:
87
+ gr.HTML(title)
88
+ gr.HTML()
89
+ gr.HTML('''<center><a href="https://huggingface.co/spaces/ysharma/ChatGPTwithAPI?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>Duplicate the Space and run securely with your OpenAI API Key</center>''')
90
+ with gr.Column(elem_id = "col_container"):
91
+ openai_api_key = gr.Textbox(type='password', label="Enter your OpenAI API key here")
92
+ chatbot = gr.Chatbot(elem_id='chatbot') #c
93
+ inputs = gr.Textbox(placeholder= "Hi there!", label= "Type an input and press Enter") #t
94
+ state = gr.State([]) #s
95
+ b1 = gr.Button()
96
+
97
+ #inputs, top_p, temperature, top_k, repetition_penalty
98
+ with gr.Accordion("Parameters", open=False):
99
+ top_p = gr.Slider( minimum=-0, maximum=1.0, value=0.95, step=0.05, interactive=True, label="Top-p (nucleus sampling)",)
100
+ temperature = gr.Slider( minimum=-0, maximum=5.0, value=0.5, step=0.1, interactive=True, label="Temperature",)
101
+ #top_k = gr.Slider( minimum=1, maximum=50, value=4, step=1, interactive=True, label="Top-k",)
102
+ #repetition_penalty = gr.Slider( minimum=0.1, maximum=3.0, value=1.03, step=0.01, interactive=True, label="Repetition Penalty", )
103
+
104
+
105
+ inputs.submit( predict, [inputs, top_p, temperature, openai_api_key, state], [chatbot, state],)
106
+ b1.click( predict, [inputs, top_p, temperature, openai_api_key, state], [chatbot, state],)
107
+ b1.click(reset_textbox, [], [inputs])
108
+ inputs.submit(reset_textbox, [], [inputs])
109
+
110
+ #gr.Markdown(description)
111
+
112
  gr.HTML('''
113
  <p>Note: Please be aware that audio records from iOS devices will not be decoded as expected by Gradio. For the best experience, record your voice from a computer instead of your smartphone ;)</p>
114
  <div class="footer">
 
119
  ''')
120
  gr.Markdown("![visitor badge](https://visitor-badge.glitch.me/badge?page_id=RamAnanth1.chatGPT_voice)")
121
 
122
+ demo.queue().launch(debug=True)