File size: 5,427 Bytes
ea1ba01
 
 
 
 
a3a0e96
 
ea1ba01
a3a0e96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea1ba01
40eca06
ea1ba01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25db599
 
27232ee
25db599
 
ea1ba01
 
 
 
 
 
25db599
ea1ba01
 
 
 
 
40eca06
ea1ba01
 
 
 
 
40eca06
ea1ba01
 
 
40eca06
71e79b1
82031c8
71e79b1
 
 
 
a015207
40eca06
ea1ba01
d1c1b9c
 
 
 
 
 
 
40eca06
ea1ba01
 
40eca06
ea1ba01
 
 
 
 
 
 
40eca06
ea1ba01
 
a015207
ea1ba01
40eca06
ea1ba01
 
 
 
 
 
 
 
71e79b1
ea1ba01
25db599
ea1ba01
25db599
 
 
ea1ba01
25db599
ea1ba01
 
 
 
 
25db599
 
 
 
 
 
 
 
a3a0e96
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import streamlit as st
from streamlit_chat import message
from streamlit_mic_recorder import speech_to_text
import base64
import gtts
import os
from dotenv import load_dotenv
from io import BytesIO
import smtplib
from email.message import EmailMessage

load_dotenv()
def send_feedback_email(feedback):
    email_sender = os.getenv("EMAIL_SENDER")
    email_password = os.getenv("EMAIL_PASSWORD")
    email_receiver = os.getenv("EMAIL_RECEIVER")

    msg = EmailMessage()
    msg.set_content(f"Feedback Chatbot:\n\n{feedback}")
    msg["Subject"] = "Feedback Chatbot PNP"
    msg["From"] = email_sender
    msg["To"] = email_receiver

    try:
        with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp:
            smtp.login(email_sender, email_password)
            smtp.send_message(msg)
        return True
    except Exception as e:
        st.error(f"Gagal mengirim feedback: {e}")
        return False

# Inisialisasi state
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'] = ""
    if 'tts_output' not in st.session_state:
        st.session_state['tts_output'] = ""

# Fungsi TTS
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

# Fungsi untuk memanggil chatbot
def conversation_chat(query, chain, history):
    result = chain({"question": query, "chat_history": history})
    history.append((query, result["answer"]))
    return result["answer"]

# Tampilan chat dan logika STT + TTS
def display_chat_history(chain):
    reply_container = st.container()

    # Input teks biasa
    user_input_obj = st.chat_input(
        "Masukkan pertanyaan",
        key="chat_input_field"
    )

    col2, col3 = st.columns([1, 1])

    # Tombol toggle suara
    with col2:
        if st.button("πŸ”Š Text-to-Speech Aktif" if st.session_state['should_speak'] else "πŸ”‡ Text-to-Speech Nonaktif", 
                    key="toggle_tts", 
                    help="Aktifkan/Nonaktifkan Text-to-Speech", 
                    use_container_width=True):
            st.session_state['should_speak'] = not st.session_state['should_speak']
            st.experimental_rerun()

    # Rekaman suara
    with col3:
        stt_text = speech_to_text(
            start_prompt="🎀 Input Suara",
            stop_prompt="πŸ›‘ Stop",
            language='id',
            just_once=True,
            key='stt_input',
            use_container_width=True,
        )

    # Jika hasil STT ada, pakai sebagai input
    if stt_text:
        st.session_state.input_text = stt_text
        st.experimental_rerun()

    # Ambil input dari teks atau STT
    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 = ""

        # Simpan output untuk TTS
        if st.session_state['should_speak'] and output:
            st.session_state['tts_output'] = output
            if 'tts_played' in st.session_state:
                del st.session_state['tts_played']

    # 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")

    # Tampilkan dan mainkan audio TTS jika ada
    if st.session_state.get('tts_output') and not st.session_state.get('tts_played'):
        st.markdown(text_to_speech(st.session_state['tts_output']), unsafe_allow_html=True)
        st.session_state['tts_played'] = True
    elif st.session_state.get('tts_played'):
        st.session_state['tts_output'] = ""
        del st.session_state['tts_played']


    with st.expander("πŸ’¬ Kirim Feedback"):
            with st.form("feedback_form"):
                feedback_text = st.text_area("Masukkan feedback Anda untuk chatbot ini:")
                submitted = st.form_submit_button("Kirim")

                if submitted and feedback_text.strip():
                    success = send_feedback_email(feedback_text)
                    if success:
                        st.success("βœ… Terima kasih! Feedback Anda telah dikirim.")