Update app.py
Browse files
app.py
CHANGED
|
@@ -3,83 +3,100 @@ import os
|
|
| 3 |
from openai import OpenAI
|
| 4 |
from datetime import datetime
|
| 5 |
|
| 6 |
-
#
|
| 7 |
-
|
|
|
|
| 8 |
|
| 9 |
-
#
|
| 10 |
-
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
|
| 20 |
-
# Get dateTime string
|
| 21 |
dt = datetime.now()
|
| 22 |
dt_string = str(dt)
|
| 23 |
|
| 24 |
-
# Define user ID and file
|
| 25 |
-
user_id = name if name else "unidentified"
|
| 26 |
-
user_hist_file = "jcTSS-" + user_id + ".txt"
|
| 27 |
-
|
| 28 |
-
# Check if user history file exists
|
| 29 |
-
if os.path.exists(user_hist_file):
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
file
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
with open(user_hist_file, "a+", encoding="UTF-8") as file:
|
| 43 |
-
file.write("\n\nDate/Time: " + datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
|
| 44 |
-
for message in history_openai_format[-2:]:
|
| 45 |
-
file.write(f"\n{message['role'].title()}: {message['content']}")
|
| 46 |
|
| 47 |
-
#
|
| 48 |
completion = client.chat.completions.create(
|
| 49 |
-
|
| 50 |
-
|
| 51 |
)
|
| 52 |
|
|
|
|
| 53 |
message_content = completion.choices[0].message.content.strip()
|
| 54 |
-
|
| 55 |
-
# Remove "Johnny"
|
| 56 |
if message_content.lower().startswith("johnny"):
|
| 57 |
-
|
|
|
|
| 58 |
|
| 59 |
-
# Append assistant
|
| 60 |
history_openai_format.append({"role": "assistant", "content": message_content})
|
| 61 |
|
| 62 |
-
#
|
| 63 |
response = client.audio.speech.create(
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
)
|
| 68 |
|
| 69 |
-
#
|
|
|
|
|
|
|
| 70 |
transcript = ""
|
| 71 |
for i, msg in enumerate(history_openai_format):
|
| 72 |
if msg['role'] != 'system':
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
with open(user_hist_file, "a+", encoding="UTF-8") as file:
|
| 77 |
file.write("\n\nDate/Time: " + datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
|
| 78 |
-
for message in history_openai_format[-2:]:
|
| 79 |
file.write(f"\n{message['role'].title()}: {message['content']}")
|
| 80 |
|
|
|
|
| 81 |
return response.content, transcript
|
| 82 |
|
| 83 |
-
#
|
| 84 |
-
iface = gr.Interface(
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from openai import OpenAI
|
| 4 |
from datetime import datetime
|
| 5 |
|
| 6 |
+
# Get dateTime strubg to build a filename reflecting the UserID + Timestamp
|
| 7 |
+
dt = datetime.now()
|
| 8 |
+
dt_string = str(dt)
|
| 9 |
|
| 10 |
+
# Initialize OpenAI API client with API key
|
| 11 |
+
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
| 12 |
|
| 13 |
+
# Initialize empty history list to maintain the conversation context
|
| 14 |
+
history_openai_format = [
|
| 15 |
+
{"role": "system", "content": (os.getenv("PROMPT"))}
|
| 16 |
+
]
|
| 17 |
|
| 18 |
+
# Define the function that takes a name and text input to generate the speech
|
| 19 |
+
def generate_speech(name, raw_input_text):
|
| 20 |
+
input_text = raw_input_text
|
| 21 |
+
global history_openai_format # Use the global history variable to maintain state
|
| 22 |
|
| 23 |
+
# Get dateTime string to build a filename reflecting the UserID + Timestamp
|
| 24 |
dt = datetime.now()
|
| 25 |
dt_string = str(dt)
|
| 26 |
|
| 27 |
+
# Define the user ID and construct the filename for the user's history file
|
| 28 |
+
user_id = name if name else "unidentified" # User identification, typically an email.
|
| 29 |
+
user_hist_file = "jcTSS-" + user_id + ".txt" # Filename where the user history will be stored.
|
| 30 |
+
|
| 31 |
+
# Check if the user's history file exists
|
| 32 |
+
if os.path.exists(user_hist_file):
|
| 33 |
+
# If it exists, open and read its contents, then print it
|
| 34 |
+
with open(user_hist_file, "r", encoding="UTF-8") as file:
|
| 35 |
+
user_hist = file.read().strip() # Remove leading/trailing whitespace
|
| 36 |
+
else:
|
| 37 |
+
# If it does not exist, create the file and initialize it with the user ID
|
| 38 |
+
with open(user_hist_file, "w", encoding="UTF-8") as file:
|
| 39 |
+
file.write("User ID: " + user_id)
|
| 40 |
+
|
| 41 |
+
# Append user message to history with the name included
|
| 42 |
+
input_text1 = f"I'm {name}. " + input_text
|
| 43 |
+
history_openai_format.append({"role": "user", "content": input_text1})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
+
# Build completion with OpenAI using the accumulated history
|
| 46 |
completion = client.chat.completions.create(
|
| 47 |
+
model="gpt-3.5-turbo-1106",
|
| 48 |
+
messages=history_openai_format
|
| 49 |
)
|
| 50 |
|
| 51 |
+
# Extract generated text (response by the assistant) from completion
|
| 52 |
message_content = completion.choices[0].message.content.strip()
|
| 53 |
+
|
| 54 |
+
# Remove "Johnny" from the beginning of the assistant's message if present
|
| 55 |
if message_content.lower().startswith("johnny"):
|
| 56 |
+
# Strip the leading "Johnny" from the message content
|
| 57 |
+
message_content = message_content[6:].strip()
|
| 58 |
|
| 59 |
+
# Append assistant's message to history
|
| 60 |
history_openai_format.append({"role": "assistant", "content": message_content})
|
| 61 |
|
| 62 |
+
# Use OpenAI's text-to-speech API to convert the text response to audio
|
| 63 |
response = client.audio.speech.create(
|
| 64 |
+
model="tts-1",
|
| 65 |
+
voice="onyx",
|
| 66 |
+
input=str(message_content)
|
| 67 |
)
|
| 68 |
|
| 69 |
+
# Prepare the transcript for the TextArea output
|
| 70 |
+
# Exclude the system message from the transcript and show the user's actual input
|
| 71 |
+
# Add line spaces between user and assistant output, and between user/assistant exchanges
|
| 72 |
transcript = ""
|
| 73 |
for i, msg in enumerate(history_openai_format):
|
| 74 |
if msg['role'] != 'system':
|
| 75 |
+
if msg['role'] == 'user':
|
| 76 |
+
transcript += "Date/Time: " + datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "\n"
|
| 77 |
+
transcript += f"Guest: {input_text}\n" # Change 'User' to 'Guest'
|
| 78 |
+
else:
|
| 79 |
+
transcript += f"Johnny: {msg['content']}\n\n" # Change 'Assistant' to 'Johnny'
|
| 80 |
+
|
| 81 |
+
# Write the user and assistant messages to the history file after the exchange
|
| 82 |
with open(user_hist_file, "a+", encoding="UTF-8") as file:
|
| 83 |
file.write("\n\nDate/Time: " + datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
|
| 84 |
+
for message in history_openai_format[-2:]: # Last 2 messages include the user and assistant responses
|
| 85 |
file.write(f"\n{message['role'].title()}: {message['content']}")
|
| 86 |
|
| 87 |
+
# Return the binary audio data and the transcript
|
| 88 |
return response.content, transcript
|
| 89 |
|
| 90 |
+
# Define the Gradio interface with inputs for name and user text
|
| 91 |
+
iface = gr.Interface(
|
| 92 |
+
fn=generate_speech,
|
| 93 |
+
inputs=[
|
| 94 |
+
gr.Textbox(label="Your Name (REQUIRED):", placeholder="Enter your FIRST NAME"),
|
| 95 |
+
gr.Textbox(label="Your question or comment for Johnny:")
|
| 96 |
+
],
|
| 97 |
+
outputs=[gr.Audio(autoplay=True, label="Johnny's response:"), gr.TextArea(label="Transcript", autoscroll="True", show_copy_button="True")],
|
| 98 |
+
live=False
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
# Launch the interface
|
| 102 |
+
iface.launch(show_api=False)
|