son9john commited on
Commit
2091088
·
1 Parent(s): 5292d69

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +193 -0
app.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import openai, subprocess
2
+ import gradio as gr
3
+ from gradio.components import Audio, Textbox
4
+
5
+ import os
6
+ import re
7
+ import tiktoken
8
+ from transformers import GPT2Tokenizer
9
+ tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
10
+ import whisper
11
+
12
+ import os
13
+ import dropbox
14
+ import datetime
15
+
16
+
17
+ ACCESS_TOKEN = os.environ["ACCESS_TOKEN"]
18
+ dbx = dropbox.Dropbox(ACCESS_TOKEN)
19
+ openai.api_key = os.environ["OPENAI_API_KEY"]
20
+
21
+ initial_message = {"role": "system", "content": 'You are a USMLE Tutor. Respond with ALWAYS layered "bullet points" (listing rather than sentences) to all input with a fun mneumonics to memorize that list. But you can answer up to 1200 words if the user requests longer response.'}
22
+ messages = [initial_message]
23
+
24
+ answer_count = 0
25
+
26
+ # set up whisper model
27
+ model = whisper.load_model("base")
28
+
29
+
30
+
31
+ def num_tokens_from_messages(messages, model="gpt-3.5-turbo-0301"):
32
+ """Returns the number of tokens used by a list of messages."""
33
+ try:
34
+ encoding = tiktoken.encoding_for_model(model)
35
+ except KeyError:
36
+ encoding = tiktoken.get_encoding("cl100k_base")
37
+ if model == "gpt-3.5-turbo-0301": # note: future models may deviate from this
38
+ num_tokens = 0
39
+ for message in messages:
40
+ num_tokens += 4 # every message follows <im_start>{role/name}\n{content}<im_end>\n
41
+ for key, value in message.items():
42
+ num_tokens += len(encoding.encode(value))
43
+ if key == "name": # if there's a name, the role is omitted
44
+ num_tokens += -1 # role is always required and always 1 token
45
+ num_tokens += 2 # every reply is primed with <im_start>assistant
46
+ return num_tokens
47
+ else:
48
+ raise NotImplementedError(f"""num_tokens_from_messages() is not presently implemented for model {model}.
49
+ See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens.""")
50
+
51
+ def transcribe(audio, text):
52
+
53
+ global messages
54
+ global answer_count
55
+ transcript = None
56
+
57
+ if audio is not None:
58
+ audio_file = open(audio, "rb")
59
+ transcript = openai.Audio.transcribe("whisper-1", audio_file, language="en")
60
+ # transcript = model.transcribe(audio_file, language="english")
61
+ messages.append({"role": "user", "content": transcript["text"]})
62
+
63
+ if transcript is None:
64
+ # Split the input text into sentences
65
+ sentences = re.split("(?<=[.!?]) +", text)
66
+
67
+ # Initialize a list to store the tokens
68
+ input_tokens = []
69
+
70
+ # Add each sentence to the input_tokens list
71
+ for sentence in sentences:
72
+ # Tokenize the sentence using the GPT-2 tokenizer
73
+ sentence_tokens = tokenizer.encode(sentence)
74
+ # Check if adding the sentence would exceed the token limit
75
+ if len(input_tokens) + len(sentence_tokens) < 1440:
76
+ # Add the sentence tokens to the input_tokens list
77
+ input_tokens.extend(sentence_tokens)
78
+ else:
79
+ # If adding the sentence would exceed the token limit, truncate it
80
+ sentence_tokens = sentence_tokens[:1440-len(input_tokens)]
81
+ input_tokens.extend(sentence_tokens)
82
+ break
83
+ # Decode the input tokens into text
84
+ input_text = tokenizer.decode(input_tokens)
85
+
86
+ # Add the input text to the messages list
87
+ messages.append({"role": "user", "content": input_text})
88
+
89
+ # Check if the accumulated tokens have exceeded 2096
90
+ num_tokens = num_tokens_from_messages(messages)
91
+ if num_tokens > 2096:
92
+ # Concatenate the chat history
93
+ chat_transcript = ""
94
+ for message in messages:
95
+ if message['role'] != 'system':
96
+ chat_transcript += f"[ANSWER {answer_count}]" + message['role'] + ": " + message['content'] + "\n\n"
97
+ # Append the number of tokens used to the end of the chat transcript
98
+
99
+ chat_transcript_copy = chat_transcript
100
+ chat_transcript_copy += f"Number of tokens used: {num_tokens}\n\n"
101
+ filename = datetime.datetime.now().strftime("%Y%m%d%H%M_conversation_history.txt")
102
+ dbx.files_upload(chat_transcript_copy.encode('utf-8'), f'/{filename}', mode=dropbox.files.WriteMode.overwrite, autorename=False, client_modified=None, mute=False)
103
+ dbx.files_upload(chat_transcript_copy.encode('utf-8'), '/conversation_history_note_backup.txt', mode=dropbox.files.WriteMode.overwrite, autorename=False, client_modified=None, mute=False)
104
+
105
+ if num_tokens > 2200:
106
+ # Reset the messages list and answer counter
107
+ messages = [initial_message]
108
+ answer_count = 0
109
+ input_text = 'input too many tokens to be corrected'
110
+ # Add the input text to the messages list
111
+ messages.append({"role": "user", "content": input_text})
112
+
113
+ # Increment the answer counter
114
+ answer_count += 1
115
+ # Add the answer counter to the system message
116
+ system_message = openai.ChatCompletion.create(
117
+ model="gpt-3.5-turbo",
118
+ messages=messages,
119
+ max_tokens=2000
120
+ )["choices"][0]["message"]
121
+ # Add the system message to the messages list
122
+ messages.append(system_message)
123
+
124
+ # Concatenate the chat history
125
+ chat_transcript = ""
126
+ for message in messages:
127
+ if message['role'] != 'system':
128
+ chat_transcript += f"[ANSWER {answer_count}]" + message['role'] + ": " + message['content'] + "\n\n"
129
+ # Append the number of tokens used to the end of the chat transcript
130
+
131
+ with open("conversation_history.txt", "a") as f:
132
+ f.write(chat_transcript)
133
+
134
+ chat_transcript_copy = chat_transcript
135
+ chat_transcript_copy += f"Number of tokens used: {num_tokens}\n\n"
136
+ filename = datetime.datetime.now().strftime("%Y%m%d%H_conversation_history.txt")
137
+ dbx.files_upload(chat_transcript_copy.encode('utf-8'), f'/{filename}', mode=dropbox.files.WriteMode.overwrite, autorename=False, client_modified=None, mute=False)
138
+ dbx.files_upload(chat_transcript_copy.encode('utf-8'), '/conversation_history.txt', mode=dropbox.files.WriteMode.overwrite, autorename=False, client_modified=None, mute=False)
139
+
140
+ return chat_transcript
141
+
142
+
143
+ audio_input = Audio(source="microphone", type="filepath", label="Record your message")
144
+ text_input = Textbox(label="Type your message", max_length=4096)
145
+
146
+ output_text = gr.outputs.Textbox(label="Response")
147
+ output_audio = Audio()
148
+
149
+ iface = gr.Interface(
150
+ fn=transcribe,
151
+ inputs=[audio_input, text_input],
152
+ # outputs=(["audio", "text"]),
153
+ outputs="text",
154
+ title="Your Excellence Never Abates (YENA)",
155
+ description="Talk to the AI Tutor YENA",
156
+ capture_session=True,
157
+ autoplay=True)
158
+
159
+
160
+ # Launch Gradio interface
161
+ iface.launch()
162
+
163
+
164
+
165
+
166
+
167
+
168
+ # from transformers import pipeline, T5Tokenizer
169
+ # import pyttsx3
170
+ # import threading
171
+ # import time
172
+
173
+
174
+
175
+
176
+ # Set up speech engine
177
+ # engine = pyttsx3.init()
178
+
179
+ # def speak(text):
180
+ # # Get the current rate of the engine
181
+ # rate = engine.getProperty('rate')
182
+
183
+ # # Calculate the estimated time in seconds based on the length of the message and the current rate
184
+ # estimated_time = len(text) / (rate / 10)
185
+
186
+ # # Speak the text using the text-to-speech engine
187
+
188
+ # engine.say(text)
189
+ # engine.runAndWait()
190
+ # if engine._inLoop:
191
+ # # Wait for the speech engine to finish speaking
192
+ # time.sleep(estimated_time*1.5)
193
+ # engine.endLoop()