pnp-chatbot-v1 / app /chat.py
FauziIsyrinApridal
Initial commit without binary files
ea1ba01
raw
history blame
3.7 kB
import streamlit as st
from streamlit_chat import message
from streamlit_mic_recorder import speech_to_text
import base64
import gtts
from io import BytesIO
def initialize_session_state():
if 'history' not in st.session_state:
st.session_state['history'] = []
if 'generated' not in st.session_state:
st.session_state['generated'] = ["Halo! Saya bisa membantu anda menjawab pertanyaan seputar Politeknik Negeri Padang!"]
if 'past' not in st.session_state:
st.session_state['past'] = ["Hai! πŸ‘‹"]
if 'data_len' not in st.session_state:
st.session_state['data_len'] = 0
if 'vector_store' not in st.session_state:
st.session_state['vector_store'] = None
if 'should_speak' not in st.session_state:
st.session_state['should_speak'] = True
if 'input_text' not in st.session_state:
st.session_state['input_text'] = ""
def text_to_speech(text):
tts = gtts.gTTS(text, lang="id")
audio_bytes = BytesIO()
tts.write_to_fp(audio_bytes)
audio_bytes.seek(0)
audio_base64 = base64.b64encode(audio_bytes.read()).decode()
audio_player = f"""
<audio autoplay>
<source src="data:audio/mp3;base64,{audio_base64}" type="audio/mp3">
</audio>
"""
return audio_player
def conversation_chat(query, chain, history):
result = chain({"question": query, "chat_history": history})
history.append((query, result["answer"]))
return result["answer"]
def display_chat_history(chain):
reply_container = st.container()
# Chat input section (at the bottom, always)
col1, col2, col3 = st.columns([7, 1, 1])
with col2:
# Toggle Text-to-Speech (TTS) using an icon instead of visible checkbox
should_speak = st.session_state.get('should_speak', True)
# Handle manual icon toggle (using button instead of checkbox)
icon_label = "πŸ”Š" if should_speak else "πŸ”‡"
if st.button(icon_label, key="toggle_tts", help="Aktifkan/Nonaktifkan Text-to-Speech", use_container_width=True):
st.session_state['should_speak'] = not should_speak
with col3:
# Mic input
stt_text = speech_to_text(
start_prompt="🎀",
stop_prompt="πŸ›‘ Stop",
language='id',
just_once=True,
key='stt_input',
use_container_width=True,
)
with col1:
# Use chat_input so it's pinned and integrated better
user_input_obj = st.chat_input(
"Masukkan pertanyaan atau Tekan tombol mic untuk berbicara!",
key="chat_input_field"
)
# Jika ada hasil dari STT, masukkan ke input dan rerun
if stt_text:
st.session_state.input_text = stt_text
st.rerun()
user_input = user_input_obj or st.session_state.get("input_text", "")
if user_input:
with st.spinner('Sedang membuat jawaban...'):
output = conversation_chat(user_input, chain, st.session_state['history'])
st.session_state['past'].append(user_input)
st.session_state['generated'].append(output)
st.session_state.input_text = "" # Kosongkan input setelah kirim
if st.session_state['should_speak'] and output:
st.markdown(text_to_speech(output), unsafe_allow_html=True)
# Tampilkan riwayat chat
if st.session_state['generated']:
with reply_container:
for i in range(len(st.session_state['generated'])):
message(st.session_state["past"][i], is_user=True, key=str(i) + '_user', avatar_style="no-avatar")
message(st.session_state["generated"][i], key=str(i), avatar_style="no-avatar")