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("""
""", 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("""
HarshBot
Mode: Tanpa Database
"Gak usah pake data, gue udah pinter."
""", 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}")