Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +45 -111
src/streamlit_app.py
CHANGED
|
@@ -1,161 +1,95 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
-
import sys
|
| 3 |
import os
|
| 4 |
-
|
| 5 |
-
#-------------------------------------
|
| 6 |
-
import pyttsx3
|
| 7 |
-
import time
|
| 8 |
from llama_index.llms.groq import Groq
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
class TextToSpeechChat:
|
| 11 |
-
def __init__(self, api_key="
|
| 12 |
# Initialize the LLM
|
| 13 |
self.llm = Groq(model="llama3-70b-8192", api_key=api_key)
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
self.tts_engine = pyttsx3.init()
|
| 17 |
-
self.setup_tts()
|
| 18 |
-
|
| 19 |
-
# Initialize speech enabled flag
|
| 20 |
-
self.speech_enabled = True
|
| 21 |
-
|
| 22 |
-
def setup_tts(self):
|
| 23 |
-
"""Configure text-to-speech settings"""
|
| 24 |
-
# Get available voices
|
| 25 |
-
voices = self.tts_engine.getProperty('voices')
|
| 26 |
-
|
| 27 |
-
# Set voice (use first available voice)
|
| 28 |
-
if voices:
|
| 29 |
-
self.tts_engine.setProperty('voice', voices[0].id)
|
| 30 |
-
else:
|
| 31 |
-
print("⚠️ No voices available for text-to-speech")
|
| 32 |
-
|
| 33 |
-
# Set speech rate (words per minute)
|
| 34 |
-
self.tts_engine.setProperty('rate', 150)
|
| 35 |
-
|
| 36 |
-
# Set volume (0.0 to 1.0)
|
| 37 |
-
self.tts_engine.setProperty('volume', 0.9)
|
| 38 |
-
|
| 39 |
-
print("🔊 Text-to-speech engine initialized")
|
| 40 |
-
|
| 41 |
def speak_text(self, text):
|
| 42 |
-
"""Convert text to speech
|
| 43 |
-
if not text.strip():
|
| 44 |
return
|
| 45 |
-
|
| 46 |
try:
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
except Exception as e:
|
| 51 |
-
|
| 52 |
-
|
| 53 |
def get_llm_response(self, prompt):
|
| 54 |
"""Get response from LLM and speak paragraphs in real-time if enabled"""
|
| 55 |
try:
|
| 56 |
-
|
| 57 |
response = self.llm.stream_complete(prompt)
|
| 58 |
-
|
| 59 |
-
# Collect the full response and buffer for paragraphs
|
| 60 |
full_response = ""
|
| 61 |
buffer = ""
|
| 62 |
|
|
|
|
| 63 |
for r in response:
|
| 64 |
delta = r.delta
|
| 65 |
full_response += delta
|
| 66 |
buffer += delta
|
| 67 |
-
|
| 68 |
|
| 69 |
-
# Check for paragraph boundary (\n\n)
|
| 70 |
if self.speech_enabled and "\n\n" in buffer:
|
| 71 |
-
# Split buffer into paragraphs
|
| 72 |
paragraphs = buffer.split("\n\n")
|
| 73 |
-
# Speak all complete paragraphs (all but the last part)
|
| 74 |
for paragraph in paragraphs[:-1]:
|
| 75 |
if paragraph.strip():
|
| 76 |
self.speak_text(paragraph.strip())
|
| 77 |
-
# Keep the last part (incomplete paragraph) in buffer
|
| 78 |
buffer = paragraphs[-1]
|
| 79 |
|
| 80 |
-
# Speak any remaining buffered text
|
| 81 |
if self.speech_enabled and buffer.strip():
|
| 82 |
self.speak_text(buffer.strip())
|
| 83 |
|
| 84 |
-
print() # New line after response
|
| 85 |
return full_response
|
| 86 |
-
|
| 87 |
except Exception as e:
|
| 88 |
error_msg = f"❌ Error getting LLM response: {e}"
|
| 89 |
-
|
| 90 |
if self.speech_enabled:
|
| 91 |
self.speak_text(error_msg)
|
| 92 |
return error_msg
|
| 93 |
-
|
| 94 |
-
def chat_with_speech(self):
|
| 95 |
-
"""Interactive chat with text-to-speech output"""
|
| 96 |
-
print("🎯 TEXT-TO-SPEECH CHAT")
|
| 97 |
-
print("=" * 50)
|
| 98 |
-
print("💡 Type your message and press Enter")
|
| 99 |
-
print("🗣️ The AI response will be spoken aloud paragraph by paragraph as it generates")
|
| 100 |
-
print("💬 Type 'quit' or 'exit' to end the chat")
|
| 101 |
-
print("🔇 Type 'mute' to disable speech")
|
| 102 |
-
print("🔊 Type 'unmute' to enable speech")
|
| 103 |
-
print("=" * 50)
|
| 104 |
-
|
| 105 |
-
# Test speech engine at startup
|
| 106 |
-
self.speak_text("Text-to-speech chat started.")
|
| 107 |
-
|
| 108 |
-
while True:
|
| 109 |
-
try:
|
| 110 |
-
# Get user input
|
| 111 |
-
user_input = input("\n👤 You: ").strip()
|
| 112 |
-
|
| 113 |
-
if not user_input:
|
| 114 |
-
continue
|
| 115 |
-
|
| 116 |
-
# Check for commands
|
| 117 |
-
if user_input.lower() in ['quit', 'exit', 'q']:
|
| 118 |
-
self.speak_text("Goodbye!")
|
| 119 |
-
print("👋 Goodbye!")
|
| 120 |
-
break
|
| 121 |
-
elif user_input.lower() == 'mute':
|
| 122 |
-
self.speech_enabled = False
|
| 123 |
-
print("🔇 Speech disabled")
|
| 124 |
-
continue
|
| 125 |
-
elif user_input.lower() == 'unmute':
|
| 126 |
-
self.speech_enabled = True
|
| 127 |
-
print("🔊 Speech enabled")
|
| 128 |
-
self.speak_text("Speech enabled.")
|
| 129 |
-
continue
|
| 130 |
-
|
| 131 |
-
# Get AI response, which now speaks paragraphs in real-time
|
| 132 |
-
print("\n🤖 AI: ", end="")
|
| 133 |
-
response = self.get_llm_response(user_input)
|
| 134 |
-
|
| 135 |
-
except KeyboardInterrupt:
|
| 136 |
-
self.speak_text("Goodbye!")
|
| 137 |
-
print("\n👋 Goodbye!")
|
| 138 |
-
break
|
| 139 |
-
except Exception as e:
|
| 140 |
-
print(f"❌ Error: {e}")
|
| 141 |
-
if self.speech_enabled:
|
| 142 |
-
self.speak_text(f"Error: {str(e)}")
|
| 143 |
|
| 144 |
def main(user_input):
|
| 145 |
chat = TextToSpeechChat()
|
| 146 |
response = chat.get_llm_response(user_input)
|
| 147 |
return response
|
| 148 |
|
| 149 |
-
#
|
|
|
|
| 150 |
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
-
|
| 153 |
-
st.title("Simple Streamlit UI")
|
| 154 |
|
| 155 |
-
# Text input
|
| 156 |
user_input = st.text_input("Enter something:")
|
| 157 |
-
|
| 158 |
-
# Button
|
| 159 |
if st.button("Submit"):
|
| 160 |
-
st.write("You entered:",
|
| 161 |
-
|
|
|
|
|
|
| 1 |
import streamlit as st
|
|
|
|
| 2 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from llama_index.llms.groq import Groq
|
| 4 |
+
import streamlit.components.v1 as components
|
| 5 |
+
|
| 6 |
+
# Ensure Streamlit config directory is set
|
| 7 |
+
os.environ["STREAMLIT_CONFIG_DIR"] = "/app/.streamlit"
|
| 8 |
|
| 9 |
class TextToSpeechChat:
|
| 10 |
+
def __init__(self, api_key="your_api_key"):
|
| 11 |
# Initialize the LLM
|
| 12 |
self.llm = Groq(model="llama3-70b-8192", api_key=api_key)
|
| 13 |
+
self.speech_enabled = st.session_state.get("speech_enabled", True)
|
| 14 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
def speak_text(self, text):
|
| 16 |
+
"""Convert text to speech using browser's SpeechSynthesis API"""
|
| 17 |
+
if not text.strip() or not self.speech_enabled:
|
| 18 |
return
|
|
|
|
| 19 |
try:
|
| 20 |
+
safe_text = text.replace('"', '\\"').replace('\n', ' ')
|
| 21 |
+
js_code = f"""
|
| 22 |
+
<script>
|
| 23 |
+
function speak(text) {{
|
| 24 |
+
const utterance = new SpeechSynthesisUtterance(text);
|
| 25 |
+
utterance.rate = 1.0;
|
| 26 |
+
utterance.volume = 0.9;
|
| 27 |
+
const voices = window.speechSynthesis.getVoices();
|
| 28 |
+
if (voices.length > 0) {{
|
| 29 |
+
utterance.voice = voices[0];
|
| 30 |
+
}}
|
| 31 |
+
window.speechSynthesis.speak(utterance);
|
| 32 |
+
}}
|
| 33 |
+
window.speechSynthesis.onvoiceschanged = function() {{
|
| 34 |
+
speak("{safe_text}");
|
| 35 |
+
}};
|
| 36 |
+
window.speechSynthesis.getVoices();
|
| 37 |
+
</script>
|
| 38 |
+
"""
|
| 39 |
+
components.html(js_code, height=0)
|
| 40 |
+
st.write(f"🗣️ Speaking: {text}")
|
| 41 |
except Exception as e:
|
| 42 |
+
st.error(f"❌ Speech error: {e}")
|
| 43 |
+
|
| 44 |
def get_llm_response(self, prompt):
|
| 45 |
"""Get response from LLM and speak paragraphs in real-time if enabled"""
|
| 46 |
try:
|
| 47 |
+
st.write("🤖 Generating response...")
|
| 48 |
response = self.llm.stream_complete(prompt)
|
|
|
|
|
|
|
| 49 |
full_response = ""
|
| 50 |
buffer = ""
|
| 51 |
|
| 52 |
+
response_container = st.empty()
|
| 53 |
for r in response:
|
| 54 |
delta = r.delta
|
| 55 |
full_response += delta
|
| 56 |
buffer += delta
|
| 57 |
+
response_container.write(full_response, unsafe_allow_html=True)
|
| 58 |
|
|
|
|
| 59 |
if self.speech_enabled and "\n\n" in buffer:
|
|
|
|
| 60 |
paragraphs = buffer.split("\n\n")
|
|
|
|
| 61 |
for paragraph in paragraphs[:-1]:
|
| 62 |
if paragraph.strip():
|
| 63 |
self.speak_text(paragraph.strip())
|
|
|
|
| 64 |
buffer = paragraphs[-1]
|
| 65 |
|
|
|
|
| 66 |
if self.speech_enabled and buffer.strip():
|
| 67 |
self.speak_text(buffer.strip())
|
| 68 |
|
|
|
|
| 69 |
return full_response
|
|
|
|
| 70 |
except Exception as e:
|
| 71 |
error_msg = f"❌ Error getting LLM response: {e}"
|
| 72 |
+
st.error(error_msg)
|
| 73 |
if self.speech_enabled:
|
| 74 |
self.speak_text(error_msg)
|
| 75 |
return error_msg
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
def main(user_input):
|
| 78 |
chat = TextToSpeechChat()
|
| 79 |
response = chat.get_llm_response(user_input)
|
| 80 |
return response
|
| 81 |
|
| 82 |
+
# Streamlit UI
|
| 83 |
+
st.title("Simple Streamlit UI")
|
| 84 |
|
| 85 |
+
# Speech toggle
|
| 86 |
+
if "speech_enabled" not in st.session_state:
|
| 87 |
+
st.session_state.speech_enabled = True
|
| 88 |
|
| 89 |
+
st.checkbox("Enable Speech", value=st.session_state.speech_enabled, key="speech_enabled")
|
|
|
|
| 90 |
|
|
|
|
| 91 |
user_input = st.text_input("Enter something:")
|
|
|
|
|
|
|
| 92 |
if st.button("Submit"):
|
| 93 |
+
st.write("You entered:", user_input)
|
| 94 |
+
response = main(user_input)
|
| 95 |
+
st.write("Response:", response)
|