File size: 6,629 Bytes
bbefddf
 
 
 
 
25353b1
bbefddf
 
 
 
25353b1
 
98ac043
 
25353b1
bbefddf
98ac043
bbefddf
 
 
 
25353b1
bbefddf
 
 
25353b1
bbefddf
25353b1
 
 
 
 
bbefddf
 
 
25353b1
 
 
 
 
 
 
 
 
 
 
 
 
 
bbefddf
25353b1
 
 
 
 
 
 
 
 
 
 
 
bbefddf
 
 
25353b1
bbefddf
 
25353b1
bbefddf
 
 
 
 
 
 
25353b1
bbefddf
 
 
 
 
 
 
 
 
25353b1
98ac043
bbefddf
25353b1
bbefddf
 
25353b1
bbefddf
25353b1
 
 
 
 
 
 
bbefddf
25353b1
 
 
bbefddf
 
 
25353b1
 
 
 
 
 
 
 
 
 
 
 
bbefddf
25353b1
 
 
98ac043
bbefddf
25353b1
bbefddf
25353b1
 
 
 
bbefddf
 
 
25353b1
bbefddf
 
 
25353b1
 
 
 
bbefddf
25353b1
 
 
 
 
 
 
 
 
 
 
 
 
 
bbefddf
 
25353b1
bbefddf
 
25353b1
 
 
 
bbefddf
 
25353b1
 
bbefddf
 
 
25353b1
bbefddf
25353b1
 
bbefddf
 
 
 
25353b1
 
 
bbefddf
25353b1
 
bbefddf
 
 
25353b1
 
 
 
 
 
bbefddf
 
25353b1
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import streamlit as st
import os
import io
import asyncio
import requests
import nest_asyncio
import edge_tts
from openai import OpenAI
from streamlit_lottie import st_lottie

# --- 1. SETUP WAJIB (Mencegah Error Runtime) ---
# Mengizinkan loop audio berjalan di dalam Streamlit
nest_asyncio.apply()

# --- 2. KONFIGURASI HALAMAN ---
st.set_page_config(
    page_title="HarshBot", 
    page_icon="😤", 
    layout="wide"
)

# --- 3. CSS TAMPILAN (Style Galak) ---
st.markdown("""
    <style>
    @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap');
    
    .stApp { background-color: #ffffff !important; }
    html, body, p, li, h1, h2, h3, h4, span, div, label { 
        font-family: 'Inter', sans-serif; color: #333; 
    }
    
    /* Hilangkan Header & Footer Bawaan */
    header[data-testid="stHeader"] { visibility: hidden; height: 0%; }
    footer { display:none; }
    
    /* Chat Bubbles */
    div[data-testid="stChatMessage"] { 
        padding: 15px; border-radius: 12px; margin-bottom: 10px; border: none;
        box-shadow: 0 1px 3px rgba(0,0,0,0.05);
    }
    /* Bubble Bot: Merah Pudar + Garis Merah Tebal */
    div[data-testid="stChatMessage"][data-testid="assistant"] { 
        background-color: #fff5f5; 
        border-left: 5px solid #c0392b; 
    }
    /* Bubble User: Biru */
    div[data-testid="stChatMessage"][data-testid="user"] { 
        background-color: #e3f2fd; 
    }
    
    /* Input Box */
    .stChatInput textarea {
        background-color: #f8f9fa !important; 
        border: 1px solid #ddd !important;
        border-radius: 25px !important;
    }
    
    /* Sidebar */
    section[data-testid="stSidebar"] {
        background-color: #f8f9fa;
        border-right: 1px solid #e0e0e0;
    }
    </style>
""", unsafe_allow_html=True)

# --- 4. FUNGSI UTAMA (Audio & Animasi) ---

def load_lottieurl(url: str):
    """Download animasi JSON"""
    try:
        r = requests.get(url)
        if r.status_code != 200: return None
        return r.json()
    except: return None

async def _generate_audio_async(text, voice="id-ID-ArdiNeural"):
    """Core function untuk Text-to-Speech"""
    communicate = edge_tts.Communicate(text, voice)
    mp3_fp = io.BytesIO()
    async for chunk in communicate.stream():
        if chunk["type"] == "audio":
            mp3_fp.write(chunk["data"])
    mp3_fp.seek(0)
    return mp3_fp

def generate_audio_sync(text):
    """Wrapper agar bisa jalan di Streamlit"""
    return asyncio.run(_generate_audio_async(text))

# --- 5. SETUP API LLM ---

api_key = os.environ.get("GROQ_API_KEY") or st.secrets.get("GROQ_API_KEY")

if not api_key:
    st.warning("⚠️ API Key Error: Masukkan GROQ_API_KEY di Settings Space Anda.")
    # Stop eksekusi agar tidak error di bawah
    st.stop()

client = OpenAI(api_key=api_key, base_url="https://api.groq.com/openai/v1")

# --- 6. SIDEBAR: IDENTITAS & AVATAR ---
with st.sidebar:
    st.markdown("### 🤖 Status")
    
    # Animasi Robot (Bisa diganti URL-nya)
    lottie_url = "https://lottie.host/5b064c5d-4f7f-4c12-9c16-2d3345701c40/3eJ5y2WpQY.json"
    avatar_anim = load_lottieurl(lottie_url)
    
    if avatar_anim:
        st_lottie(avatar_anim, height=200, key="avatar_main")
    
    st.markdown("""
    <div style="text-align: center; margin-top: 10px; padding: 10px; background: white; border-radius: 10px; border: 1px solid #ddd;">
        <h3 style="color: #c0392b; margin:0;">HarshBot</h3>
        <p style="font-size: 12px; margin:5px 0 0 0; color: #666;">
            Mode: <b>Tanpa Database</b><br>
            <i>"Gak usah pake data, gue udah pinter."</i>
        </p>
    </div>
    """, unsafe_allow_html=True)
    
    # Tombol Clear Chat
    if st.button("🧹 Hapus Chat", type="primary"):
        st.session_state.messages = []
        st.rerun()

# --- 7. LOGIKA CHAT UTAMA ---

if "messages" not in st.session_state:
    st.session_state.messages = []

# Tampilkan History Chat
for message in st.session_state.messages:
    with st.chat_message(message["role"]):
        st.markdown(message["content"])
        # Jika ada audio tersimpan di history, tampilkan playernya
        if message["role"] == "assistant" and "audio" in message: 
            st.audio(message["audio"], format="audio/mp3")

# Input User
if user_input := st.chat_input("Ngomong sini..."):
    
    # 1. Tampilkan User Input
    st.session_state.messages.append({"role": "user", "content": user_input})
    with st.chat_message("user"):
        st.markdown(user_input)

    # 2. Siapkan Prompt Galak (Tanpa Konteks DB)
    system_prompt = """
    You are 'HarshBot'.
    Personality: Extremely nonchalant, harsh, sarcastic, and slightly rude.
    Language: Indonesian colloquial (Bahasa gaul/sehari-hari).
    
    Instructions:
    1. Answer the user's question directly.
    2. Do NOT be helpful in a polite way. Be helpful in an annoyed way.
    3. If the question is simple, mock the user for asking it.
    4. Keep answers relatively short and punchy.
    """

    # 3. Kirim ke AI & Stream Jawaban
    with st.chat_message("assistant"):
        try:
            # Mengambil 5 chat terakhir untuk memori jangka pendek
            history_payload = [{"role": m["role"], "content": m["content"]} for m in st.session_state.messages[-5:]]
            messages_final = [{"role": "system", "content": system_prompt}] + history_payload

            stream = client.chat.completions.create(
                model="llama-3.3-70b-versatile",
                messages=messages_final,
                temperature=0.8, # Lebih kreatif marahnya
                stream=True 
            )
            
            response_container = st.empty()
            full_response = ""
            
            # Efek Mengetik
            for chunk in stream:
                content = chunk.choices[0].delta.content
                if content:
                    full_response += content
                    response_container.markdown(full_response + "▌")
            
            response_container.markdown(full_response)
            
            # 4. Generate Audio (TTS)
            # Kita gunakan nest_asyncio di atas, jadi ini aman sekarang
            audio_buffer = generate_audio_sync(full_response)
            st.audio(audio_buffer, format="audio/mp3")
            
            # 5. Simpan ke Session State
            st.session_state.messages.append({
                "role": "assistant", 
                "content": full_response,
                "audio": audio_buffer
            })

        except Exception as e:
            st.error(f"Waduh error: {e}")