Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Continuous mode not working #148

Closed
wants to merge 40 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
9fde685
Update README.md for Transcribe
vivekuppal Jun 29, 2023
1483fea
Merge pull request #1 from vivekuppal/vu-readme-updates
vivekuppal Jun 29, 2023
391d728
Allow usage without a valid OPEN API key. (#2)
vivekuppal Jun 29, 2023
ab4245d
Update README.md (#3)
vivekuppal Jun 29, 2023
ebb6f2f
Allow user to choose model. Add arguments to main file.
vivekuppal Jun 29, 2023
8f5a595
Code clean up, add linting. (#4)
vivekuppal Jun 30, 2023
59d5c91
UI Text Chronology (#5)
vivekuppal Jun 30, 2023
f772bb8
Update readme with Enhancements. Allow copy of text from UI window. R…
vivekuppal Jun 30, 2023
87a38b1
Save conversation to text. (#9)
vivekuppal Jun 30, 2023
65d6dcf
Add Contextual Information to Responses (#11)
vivekuppal Jun 30, 2023
d1b3c45
Allow users to pause audio transcription. Change the default for gett…
vivekuppal Jul 3, 2023
cfca51a
Update main.py (#15)
abhinavuppal1 Jul 11, 2023
152bad3
Code reorg to separate UI code (#16)
vivekuppal Jul 12, 2023
addf17f
Add support for multiple languages (#18)
vivekuppal Jul 12, 2023
e5cda88
Easy install for non developers on windows (#20)
vivekuppal Jul 18, 2023
9896c1c
Disabled winrar UI (#22)
Adarsha-gg Jul 18, 2023
901501b
When using API, we do not need to specify language, absorb the lang p…
vivekuppal Jul 18, 2023
bd48b61
Language combo fix (#26)
Adarsha-gg Jul 19, 2023
7c9ca88
Added gdrive (#27)
Adarsha-gg Jul 19, 2023
2429c97
Allow usage of API Key in installed version of Transcribe (#28)
vivekuppal Jul 19, 2023
12ef846
updated the drive link (#30)
Adarsha-gg Jul 20, 2023
4be26c7
Add a duration class to easily measure the time taken for an operatio…
vivekuppal Jul 21, 2023
6e53b31
--api option was not working correctly (#34)
vivekuppal Jul 21, 2023
bd42b8c
Initial unit tests for the speech recognition library (#36)
vivekuppal Jul 24, 2023
af87eff
user reported defect fixes. (#39)
vivekuppal Jul 26, 2023
26cfaad
Optimize LLM usage (#40)
vivekuppal Jul 26, 2023
f8d5857
Bug fixes for exceptions observed during usage. Add further plumbing …
vivekuppal Jul 27, 2023
1356a78
Add logging infrastructure (#42)
vivekuppal Jul 27, 2023
a1cc48b
Get Response from LLM on demand (#44)
vivekuppal Jul 28, 2023
ea5f392
Models from open ai site (#43)
Adarsha-gg Jul 28, 2023
b4e03a4
List all active devices (#45)
vivekuppal Aug 1, 2023
85d09ed
Allow user to select input, output audio devices (#48)
vivekuppal Aug 21, 2023
28d1e9a
Disable mic speaker selectively (#49)
vivekuppal Aug 23, 2023
e48bdb8
Add Audio Response for LLM generated content (#50)
vivekuppal Aug 27, 2023
6baa77f
Update, upload latest binaries (#54)
Adarsha-gg Aug 30, 2023
fa55416
Multiturn prompts, bug fixes (#55)
vivekuppal Sep 5, 2023
ce5a1e1
Allow enable/disable speaker and microphone from UI (#56)
Adarsha-gg Sep 6, 2023
e445856
Update gdrive link (#58)
Adarsha-gg Sep 7, 2023
b50f58c
Bring readme up to date with current functionality. Describe content …
vivekuppal Sep 8, 2023
a7ea2cc
Continuous mode broke after updates to the UI.
vivekuppal Sep 8, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Multiturn prompts, bug fixes (#55)
* multiturn prompts, bug fixes
  • Loading branch information
vivekuppal committed Sep 5, 2023
commit fa55416558dfe23860df2a8e272fa0ec59bbc3ce
23 changes: 20 additions & 3 deletions AudioTranscriber.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
import os
import queue
from heapq import merge
import threading
import io
from datetime import timedelta
import pprint
import wave
import tempfile
import custom_speech_recognition as sr
import pyaudiowpatch as pyaudio
from heapq import merge
import conversation
import constants


PHRASE_TIMEOUT = 3.05


class AudioTranscriber:
def __init__(self, mic_source, speaker_source, model, convo: conversation.Conversation):
# Transcript_data should be replaced with the conversation object.
# We do not need to store transcription in 2 different places.
self.transcript_data = {"You": [], "Speaker": []}
self.transcript_changed_event = threading.Event()
self.audio_model = model
Expand Down Expand Up @@ -105,7 +109,7 @@ def update_transcript(self, who_spoke, text, time_spoken):
"""Update transcript with new data
Args:
who_spoke: Person this audio is attributed to
text: Actual spken words
text: Actual spoken words
time_spoken: Time at which audio was taken, relative to start time
"""
source_info = self.audio_sources[who_spoke]
Expand All @@ -129,11 +133,24 @@ def get_transcript(self, length: int = 0):
length: Get the last length elements from the audio transcript.
Default value = 0, gives the complete transcript
"""
# This data should be retrieved from the conversation object.
combined_transcript = list(merge(
self.transcript_data["You"], self.transcript_data["Speaker"],
key=lambda x: x[1], reverse=False))
combined_transcript = combined_transcript[-length:]
return "".join([t[0] for t in combined_transcript])
current_return_val = "".join([t[0] for t in combined_transcript])
sources = [
constants.PERSONA_YOU,
constants.PERSONA_SPEAKER
]
convo_object_return_value = self.conversation.get_conversation(sources=sources)
# print('---------- AudioTranscriber.py get_transcript convo object----------')
# pprint.pprint(convo_object_return_value, width=120)

# print('---------- AudioTranscriber.py get_transcript current implementation----------')
# pprint.pprint(current_return_val, width=120)

return convo_object_return_value

def clear_transcript_data(self):
"""
Expand Down
36 changes: 29 additions & 7 deletions GPTResponder.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ def __init__(self, convo: conversation.Conversation):
def generate_response_from_transcript_no_check(self, transcript) -> str:
"""Ping LLM to get a suggested response right away.
Gets a response even if the continuous suggestion option is disabled.
Updates the conversation object with the response from LLM.
"""
try:
prompt_api_message = prompts.create_single_turn_prompt_message(transcript)
Expand All @@ -42,28 +43,49 @@ def generate_response_from_transcript_no_check(self, transcript) -> str:
messages=prompt_api_message,
temperature=0.0
)
# Multi turn response is only effective when continuous mode is off.
# In continuous mode, there are far too many responses from LLM,
# they confuse the LLM if that many responses are replayed back to LLM.
multi_turn_response = openai.ChatCompletion.create(
model=self.model,
messages=multiturn_prompt_api_message,
temperature=0.0
)

# print('-------- Single Turn --------')
# pprint.pprint(f'message={prompt_api_message}', width=120)
# pprint.pprint(f'response={usual_response}', width=120)
# print('-------- Multi Turn --------')
# pprint.pprint(f'message={multiturn_prompt_api_message}', width=120)
# pprint.pprint(f'response={multi_turn_response}', width=120)
# print('-------- -------- -------- -------- -------- --------')

except Exception as exception:
print(exception)
root_logger.error('Error when attempting to get a response from LLM.')
root_logger.exception(exception)
return prompts.INITIAL_RESPONSE

usual_full_response = usual_response.choices[0].message.content
# single_turn_response_content = usual_response.choices[0].message.content
multi_turn_response_content = multi_turn_response.choices[0].message.content
# pprint.pprint(f'Prompt api response: {usual_response}')
try:
# The original way of processing the response. It used to cause issues when there
# were multiple questions in the transcript.
# response = usual_full_response.split('[')[1].split(']')[0]
processed_response = self.process_response(usual_full_response)
self.update_conversation(persona=constants.PERSONA_ASSISTANT, response=processed_response)
return processed_response
# The original way of processing the response.
# It causes issues when there are multiple questions in the transcript.
# response = single_turn_response_content.split('[')[1].split(']')[0]
# processed_single_turn_response = self.process_response(single_turn_response_content)
processed_multi_turn_response = self.process_response(multi_turn_response_content)
self.update_conversation(persona=constants.PERSONA_ASSISTANT,
response=processed_multi_turn_response)
return processed_multi_turn_response
except Exception as exception:
root_logger.error('Error parsing response from LLM.')
root_logger.exception(exception)
return prompts.INITIAL_RESPONSE

def process_response(self, input_str: str) -> str:
""" Extract relevant data from LLM response.
"""
lines = input_str.split(sep='\n')
response = ''
for line in lines:
Expand Down
3 changes: 3 additions & 0 deletions GlobalVars.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import AudioRecorder
import Singleton
import app_logging as al
import conversation


root_logger = al.get_logger()
Expand All @@ -30,6 +31,8 @@ class TranscriptionGlobals(Singleton.Singleton):
filemenu: tk.Menu = None
response_textbox: ctk.CTkTextbox = None

convo: conversation.Conversation = None

def __init__(self, key: str = 'API_KEY'):
root_logger.info(TranscriptionGlobals.__name__)
if self.audio_queue is None:
Expand Down
2 changes: 1 addition & 1 deletion audio_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def play_audio(self, speech: str):
os.remove(temp_audio_file[1])

def play_audio_loop(self):
"""Play text to audio continuously based on the signaling of event
"""Play text to audio based on signaling of event
"""
while True:
if self.speech_text_available.is_set():
Expand Down
1 change: 1 addition & 0 deletions constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@

LOG_NAME = 'Transcribe'
MAX_TRANSCRIPTION_PHRASES_FOR_LLM = 20
TRANSCRIPT_UI_UPDATE_DELAY_DURATION_MS = 500
17 changes: 11 additions & 6 deletions conversation.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,16 @@ def __init__(self):
constants.PERSONA_ASSISTANT: []}
config = configuration.Config().get_data()
prompt = config["OpenAI"]["system_prompt"]
self.update_conversation(persona=constants.PERSONA_SYSTEM, text=prompt,
self.update_conversation(persona=constants.PERSONA_SYSTEM, text=prompt,
time_spoken=datetime.datetime.now())
initial_convo: dict = config["OpenAI"]["initial_convo"]
# Read the initial conversation from parameters.yaml file and add to the convo
for _, value in initial_convo.items():
role = value['role']
content = value['content']
self.update_conversation(persona=role, text=content,
self.update_conversation(persona=role, text=content,
time_spoken=datetime.datetime.now())
self.last_update: datetime.datetime = datetime.datetime.now()

def clear_conversation_data(self):
"""Clear all conversation data
Expand All @@ -34,6 +35,7 @@ def clear_conversation_data(self):
self.transcript_data[constants.PERSONA_SPEAKER].clear()
self.transcript_data[constants.PERSONA_SYSTEM].clear()
self.transcript_data[constants.PERSONA_ASSISTANT].clear()
self.last_update = datetime.datetime.now()

def update_conversation(self, persona: str, text: str, time_spoken, pop: bool = False):
"""Update conversation with new data
Expand All @@ -46,15 +48,18 @@ def update_conversation(self, persona: str, text: str, time_spoken, pop: bool =
if pop:
transcript.pop()
transcript.append((f"{persona}: [{text}]\n\n", time_spoken))
self.last_update = datetime.datetime.now()

def get_conversation(self,
sources: list = None,
length: int = 0) -> list:
length: int = 0,
reverse: bool = False) -> list:
"""Get the transcript based on specified sources
Args:
sources: Get data from which sources (You, Speaker, Assistant, System)
length: Get the last length elements from the audio transcript.
Default value = 0, gives the complete transcript for chosen sources
reverse: reverse the sort order or keep it in chronological order
"""
if sources is None:
sources = [constants.PERSONA_YOU,
Expand All @@ -67,11 +72,11 @@ def get_conversation(self,
self.transcript_data[constants.PERSONA_SPEAKER][-length:] if constants.PERSONA_SPEAKER in sources else [],
self.transcript_data[constants.PERSONA_ASSISTANT][-length:] if constants.PERSONA_ASSISTANT in sources else [],
self.transcript_data[constants.PERSONA_SYSTEM][-length:] if constants.PERSONA_SYSTEM in sources else [],
key=lambda x: x[1]))
key=lambda x: x[1], reverse=reverse))
combined_transcript = combined_transcript[-length:]
return "".join([t[0] for t in combined_transcript])

def get_merged_conversation(self, length: int = 0) -> list:
def get_merged_conversation(self, length: int = 0, reverse: bool = False) -> list:
"""Creates a prompt to be sent to LLM (OpenAI by default)
length: Get the last length elements from the audio transcript.
Initial system prompt is always part of the return value
Expand All @@ -88,7 +93,7 @@ def get_merged_conversation(self, length: int = 0) -> list:
self.transcript_data[constants.PERSONA_YOU][-length:],
self.transcript_data[constants.PERSONA_SPEAKER][-length:],
self.transcript_data[constants.PERSONA_ASSISTANT][-length:],
key=lambda x: x[1]))
key=lambda x: x[1], reverse=reverse))
combined_transcript = combined_transcript[-length:]

return combined_transcript
12 changes: 6 additions & 6 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,11 @@ def main():
global_vars.speaker_audio_recorder.set_device(index=args.speaker_device_index)

if args.disable_mic:
print('[INFO] Disabling Microphone')
print('[INFO] Disabling Transcription from the Microphone')
global_vars.user_audio_recorder.disable()

if args.disable_speaker:
print('[INFO] Disabling Speaker')
print('[INFO] Disabling Transcription from the speaker')
global_vars.speaker_audio_recorder.disable()

try:
Expand Down Expand Up @@ -153,21 +153,21 @@ def main():

global_vars.speaker_audio_recorder.record_into_queue(global_vars.audio_queue)
global_vars.freeze_state = [True]
convo = conversation.Conversation()
global_vars.convo = conversation.Conversation()

# Transcribe and Respond threads, both work on the same instance of the AudioTranscriber class
global_vars.transcriber = AudioTranscriber(global_vars.user_audio_recorder.source,
global_vars.speaker_audio_recorder.source,
model,
convo=convo)
global_vars.audio_player = AudioPlayer(convo=convo)
convo=global_vars.convo)
global_vars.audio_player = AudioPlayer(convo=global_vars.convo)
transcribe_thread = threading.Thread(target=global_vars.transcriber.transcribe_audio_queue,
name='Transcribe',
args=(global_vars.audio_queue,))
transcribe_thread.daemon = True
transcribe_thread.start()

global_vars.responder = GPTResponder(convo=convo)
global_vars.responder = GPTResponder(convo=global_vars.convo)

respond_thread = threading.Thread(target=global_vars.responder.respond_to_transcriber,
name='Respond',
Expand Down
Loading