shukdevdatta123 commited on
Commit
9fe39cc
·
verified ·
1 Parent(s): bdd31b0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +101 -61
app.py CHANGED
@@ -1,68 +1,108 @@
 
 
1
  import streamlit as st
 
 
 
 
2
  from audio_recorder_streamlit import audio_recorder
3
- import openai
4
-
5
- # Prompt the user to input their OpenAI API key
6
- API_KEY = st.text_input("Enter your OpenAI API Key", type="password")
7
-
8
- # Check if the API key is provided
9
- if API_KEY:
10
- openai.api_key = API_KEY # Set the API key
11
-
12
- def transcribe_text_to_voice(audio_location):
13
- # Transcribe audio to text using Whisper API
14
- with open(audio_location, "rb") as audio_file:
15
- transcript = openai.Audio.transcribe(
16
- model="whisper-1", file=audio_file
17
- )
18
- return transcript['text']
19
-
20
- def chat_completion_call(text):
21
- # Send the text to GPT-3.5 for chat completion
22
- response = openai.ChatCompletion.create(
23
- model="gpt-3.5-turbo-1106",
24
- messages=[{"role": "user", "content": text}]
25
- )
26
- return response['choices'][0]['message']['content']
27
-
28
- def text_to_speech_ai(speech_file_path, api_response):
29
- # Convert the text to speech using OpenAI's TTS API
30
- response = openai.Audio.speech.create(
31
- model="text-to-speech-1", # TTS model name may differ
32
- voice="nova", # Specify a voice (choose one that is available)
33
- input=api_response
34
- )
35
- # Save the speech response to a file
36
- with open(speech_file_path, "wb") as f:
37
- f.write(response['audio'])
38
-
39
- # Streamlit interface for voice assistant
40
- st.title("🧑‍💻 Skolo Online 💬 Talking Assistant")
41
- """
42
- Hi🤖 just click on the voice recorder and let me know how I can help you today?
43
- """
44
-
45
- audio_bytes = audio_recorder()
46
- if audio_bytes:
47
- # Save the Recorded Audio File
48
- audio_location = "audio_file.wav"
49
- with open(audio_location, "wb") as f:
50
- f.write(audio_bytes)
51
 
52
- # Transcribe the saved file to text
53
- text = transcribe_text_to_voice(audio_location)
54
- st.write("You said:", text)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
- # Get AI response from GPT-3.5
57
- api_response = chat_completion_call(text)
58
- st.write("AI says:", api_response)
 
 
 
59
 
60
- # Convert the response to speech and save it as a file
61
- speech_file_path = 'audio_response.mp3'
62
- text_to_speech_ai(speech_file_path, api_response)
 
 
 
 
 
 
 
 
 
 
63
 
64
- # Play the audio response in the app
65
- st.audio(speech_file_path)
66
 
67
- else:
68
- st.warning("Please enter your OpenAI API key to continue.")
 
1
+ # app.py
2
+
3
  import streamlit as st
4
+ import hmac
5
+ import os
6
+ from helpers import text_to_speech, autoplay_audio, speech_to_text, get_api_key
7
+ from generate_answer import base_model_chatbot, with_pdf_chatbot
8
  from audio_recorder_streamlit import audio_recorder
9
+ from streamlit_float import *
10
+
11
+ def main(answer_mode: str):
12
+ # Float feature initialization
13
+ float_init()
14
+
15
+ # Prompt for API key
16
+ api_key = get_api_key()
17
+ if not api_key:
18
+ st.error("You must provide a valid OpenAI API Key to proceed.")
19
+ st.stop()
20
+
21
+ def check_password():
22
+ """Returns `True` if the user had a correct password."""
23
+ def login_form():
24
+ """Form with widgets to collect user information"""
25
+ with st.form("Credentials"):
26
+ st.text_input("Username", key="username")
27
+ st.text_input("Password", type="password", key="password")
28
+ st.form_submit_button("Log in", on_click=password_entered)
29
+
30
+ def password_entered():
31
+ """Checks whether a password entered by the user is correct."""
32
+ if st.session_state["username"] in st.secrets[
33
+ "passwords"
34
+ ] and hmac.compare_digest(
35
+ st.session_state["password"],
36
+ st.secrets.passwords[st.session_state["username"]],
37
+ ):
38
+ st.session_state["password_correct"] = True
39
+ del st.session_state["password"]
40
+ del st.session_state["username"]
41
+ else:
42
+ st.session_state["password_correct"] = False
43
+
44
+ # Return True if the username + password is validated.
45
+ if st.session_state.get("password_correct", False):
46
+ return True
47
+
48
+ # Show inputs for username + password.
49
+ login_form()
50
+ if "password_correct" in st.session_state:
51
+ st.error("😕 User not known or password incorrect")
52
+ return False
 
 
 
 
53
 
54
+ if not check_password():
55
+ st.stop()
56
+
57
+ def initialize_session_state():
58
+ if "messages" not in st.session_state:
59
+ st.session_state.messages = [
60
+ {"role": "assistant", "content": "Hi! How may I assist you today?"}
61
+ ]
62
+
63
+ initialize_session_state()
64
+
65
+ st.title("OpenAI Conversational Chatbot 🤖")
66
+
67
+ # Create footer container for the microphone
68
+ footer_container = st.container()
69
+ with footer_container:
70
+ audio_bytes = audio_recorder()
71
+
72
+ for message in st.session_state.messages:
73
+ with st.chat_message(message["role"]):
74
+ st.write(message["content"])
75
+
76
+ if audio_bytes:
77
+ # Write the audio bytes to a file
78
+ with st.spinner("Transcribing..."):
79
+ webm_file_path = "temp_audio.mp3"
80
+ with open(webm_file_path, "wb") as f:
81
+ f.write(audio_bytes)
82
 
83
+ transcript = speech_to_text(webm_file_path)
84
+ if transcript:
85
+ st.session_state.messages.append({"role": "user", "content": transcript})
86
+ with st.chat_message("user"):
87
+ st.write(transcript)
88
+ os.remove(webm_file_path)
89
 
90
+ if st.session_state.messages[-1]["role"] != "assistant":
91
+ with st.chat_message("assistant"):
92
+ with st.spinner("Thinking🤔..."):
93
+ if answer_mode == 'base_model':
94
+ final_response = base_model_chatbot(st.session_state.messages)
95
+ elif answer_mode == 'pdf_chat':
96
+ final_response = with_pdf_chatbot(st.session_state.messages)
97
+ with st.spinner("Generating audio response..."):
98
+ audio_file = text_to_speech(final_response)
99
+ autoplay_audio(audio_file)
100
+ st.write(final_response)
101
+ st.session_state.messages.append({"role": "assistant", "content": final_response})
102
+ os.remove(audio_file)
103
 
104
+ # Float the footer container and provide CSS to target it with
105
+ footer_container.float("bottom: 0rem;")
106
 
107
+ if __name__ == "__main__":
108
+ main(answer_mode='base_model') # Or: answer_mode='base_model'