Spaces:
Runtime error
Runtime error
Download app.py from Vr711/HarshchatbotAPI: direct link, hf CLI and curl.
- Browser
- Download file 6.63 kB
-
https://huggingface.co/spaces/Vr711/HarshchatbotAPI/resolve/main/app.py
- Command line
-
hf download hf://spaces/Vr711/HarshchatbotAPI/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Vr711/HarshchatbotAPI/resolve/main/app.py
6.63 kB
| 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}") |