Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,57 +1,72 @@
|
|
| 1 |
-
# --- 1. HACK SQLITE (WAJIB PALING ATAS) ---
|
| 2 |
-
__import__('pysqlite3')
|
| 3 |
-
import sys
|
| 4 |
-
sys.modules['sqlite3'] = sys.modules.pop('pysqlite3')
|
| 5 |
-
|
| 6 |
-
# --- 2. IMPORTS ---
|
| 7 |
import streamlit as st
|
| 8 |
import os
|
| 9 |
import io
|
| 10 |
import asyncio
|
| 11 |
-
import json
|
| 12 |
-
import hashlib
|
| 13 |
-
import shutil
|
| 14 |
-
import time
|
| 15 |
import requests
|
| 16 |
-
import nest_asyncio
|
| 17 |
import edge_tts
|
| 18 |
from openai import OpenAI
|
| 19 |
-
from langchain_community.document_loaders import PyPDFLoader, Docx2txtLoader, TextLoader
|
| 20 |
-
from langchain_community.vectorstores import Chroma
|
| 21 |
-
from langchain_huggingface import HuggingFaceEmbeddings
|
| 22 |
-
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 23 |
from streamlit_lottie import st_lottie
|
| 24 |
|
| 25 |
-
#
|
|
|
|
| 26 |
nest_asyncio.apply()
|
| 27 |
|
| 28 |
-
# ---
|
| 29 |
st.set_page_config(
|
| 30 |
page_title="HarshBot",
|
| 31 |
page_icon="😤",
|
| 32 |
layout="wide"
|
| 33 |
)
|
| 34 |
|
| 35 |
-
# ---
|
| 36 |
st.markdown("""
|
| 37 |
<style>
|
| 38 |
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap');
|
|
|
|
| 39 |
.stApp { background-color: #ffffff !important; }
|
| 40 |
-
html, body, p, li, h1, h2, h3, h4, span, div, label {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
header[data-testid="stHeader"] { visibility: hidden; height: 0%; }
|
| 42 |
footer { display:none; }
|
| 43 |
|
| 44 |
-
|
| 45 |
-
div[data-testid="stChatMessage"]
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
</style>
|
| 50 |
""", unsafe_allow_html=True)
|
| 51 |
|
| 52 |
-
# ---
|
| 53 |
|
| 54 |
def load_lottieurl(url: str):
|
|
|
|
| 55 |
try:
|
| 56 |
r = requests.get(url)
|
| 57 |
if r.status_code != 200: return None
|
|
@@ -59,6 +74,7 @@ def load_lottieurl(url: str):
|
|
| 59 |
except: return None
|
| 60 |
|
| 61 |
async def _generate_audio_async(text, voice="id-ID-ArdiNeural"):
|
|
|
|
| 62 |
communicate = edge_tts.Communicate(text, voice)
|
| 63 |
mp3_fp = io.BytesIO()
|
| 64 |
async for chunk in communicate.stream():
|
|
@@ -68,149 +84,117 @@ async def _generate_audio_async(text, voice="id-ID-ArdiNeural"):
|
|
| 68 |
return mp3_fp
|
| 69 |
|
| 70 |
def generate_audio_sync(text):
|
| 71 |
-
|
| 72 |
return asyncio.run(_generate_audio_async(text))
|
| 73 |
|
| 74 |
-
# ---
|
| 75 |
|
| 76 |
api_key = os.environ.get("GROQ_API_KEY") or st.secrets.get("GROQ_API_KEY")
|
|
|
|
| 77 |
if not api_key:
|
| 78 |
-
st.warning("⚠️
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
def get_files_signature(folder_path="."):
|
| 86 |
-
file_signatures = []
|
| 87 |
-
for root, dirs, files in os.walk(folder_path):
|
| 88 |
-
for file in files:
|
| 89 |
-
if "chroma_db" in root or file.startswith("."): continue
|
| 90 |
-
if file.lower().endswith(('.pdf', '.docx', '.txt')) and "requirements" not in file:
|
| 91 |
-
full_path = os.path.join(root, file)
|
| 92 |
-
mtime = os.path.getmtime(full_path)
|
| 93 |
-
file_signatures.append(f"{file}_{mtime}")
|
| 94 |
-
return hashlib.md5("".join(sorted(file_signatures)).encode()).hexdigest()
|
| 95 |
-
|
| 96 |
-
@st.cache_resource
|
| 97 |
-
def get_vectorstore():
|
| 98 |
-
# Gunakan Try-Except agar aplikasi tidak Exit Code 0 jika DB error
|
| 99 |
-
try:
|
| 100 |
-
embedding_function = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 101 |
-
|
| 102 |
-
current_signature = get_files_signature(".")
|
| 103 |
-
last_signature = ""
|
| 104 |
-
|
| 105 |
-
if os.path.exists(METADATA_PATH):
|
| 106 |
-
with open(METADATA_PATH, "r") as f:
|
| 107 |
-
try: last_signature = json.load(f).get("signature", "")
|
| 108 |
-
except: pass
|
| 109 |
-
|
| 110 |
-
db_exists = os.path.exists(DB_PATH) and len(os.listdir(DB_PATH)) > 0
|
| 111 |
-
is_changed = current_signature != last_signature
|
| 112 |
-
|
| 113 |
-
if db_exists and not is_changed:
|
| 114 |
-
print("✅ Load DB Lama.")
|
| 115 |
-
return Chroma(persist_directory=DB_PATH, embedding_function=embedding_function)
|
| 116 |
-
|
| 117 |
-
print("🔄 Buat DB Baru...")
|
| 118 |
-
if os.path.exists(DB_PATH): shutil.rmtree(DB_PATH, ignore_errors=True)
|
| 119 |
-
|
| 120 |
-
documents = []
|
| 121 |
-
for root, dirs, files in os.walk("."):
|
| 122 |
-
if "chroma_db" in root: continue
|
| 123 |
-
for file in files:
|
| 124 |
-
full_path = os.path.join(root, file)
|
| 125 |
-
try:
|
| 126 |
-
if file.lower().endswith(".pdf"): documents.extend(PyPDFLoader(full_path).load())
|
| 127 |
-
elif file.lower().endswith(".docx"): documents.extend(Docx2txtLoader(full_path).load())
|
| 128 |
-
elif file.lower().endswith(".txt") and "requirements" not in file: documents.extend(TextLoader(full_path, encoding='utf-8').load())
|
| 129 |
-
except: pass
|
| 130 |
-
|
| 131 |
-
if not documents: return None
|
| 132 |
-
|
| 133 |
-
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
| 134 |
-
splits = text_splitter.split_documents(documents)
|
| 135 |
-
|
| 136 |
-
db = Chroma.from_documents(documents=splits, embedding=embedding_function, persist_directory=DB_PATH)
|
| 137 |
-
|
| 138 |
-
with open(METADATA_PATH, "w") as f: json.dump({"signature": current_signature}, f)
|
| 139 |
-
return db
|
| 140 |
-
except Exception as e:
|
| 141 |
-
print(f"❌ Error Database: {e}")
|
| 142 |
-
return None
|
| 143 |
-
|
| 144 |
-
db = get_vectorstore()
|
| 145 |
-
|
| 146 |
-
# --- 7. SIDEBAR ---
|
| 147 |
with st.sidebar:
|
| 148 |
-
st.markdown("### 🤖
|
|
|
|
|
|
|
| 149 |
lottie_url = "https://lottie.host/5b064c5d-4f7f-4c12-9c16-2d3345701c40/3eJ5y2WpQY.json"
|
| 150 |
avatar_anim = load_lottieurl(lottie_url)
|
| 151 |
-
if avatar_anim: st_lottie(avatar_anim, height=180, key="avatar_main")
|
| 152 |
|
| 153 |
-
|
| 154 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
st.success("Database Reset!")
|
| 160 |
-
time.sleep(1)
|
| 161 |
st.rerun()
|
| 162 |
|
| 163 |
-
# ---
|
| 164 |
-
if "messages" not in st.session_state: st.session_state.messages = []
|
| 165 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
for message in st.session_state.messages:
|
| 167 |
with st.chat_message(message["role"]):
|
| 168 |
st.markdown(message["content"])
|
|
|
|
| 169 |
if message["role"] == "assistant" and "audio" in message:
|
| 170 |
st.audio(message["audio"], format="audio/mp3")
|
| 171 |
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
st.session_state.messages.append({"role": "user", "content": user_input})
|
| 178 |
-
with st.chat_message("user"):
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
|
|
|
|
|
|
| 190 |
"""
|
| 191 |
|
|
|
|
| 192 |
with st.chat_message("assistant"):
|
| 193 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
stream = client.chat.completions.create(
|
| 195 |
model="llama-3.3-70b-versatile",
|
| 196 |
-
messages=
|
| 197 |
-
temperature=0.
|
| 198 |
stream=True
|
| 199 |
)
|
| 200 |
|
| 201 |
-
|
| 202 |
full_response = ""
|
|
|
|
|
|
|
| 203 |
for chunk in stream:
|
| 204 |
content = chunk.choices[0].delta.content
|
| 205 |
if content:
|
| 206 |
full_response += content
|
| 207 |
-
|
| 208 |
-
|
|
|
|
| 209 |
|
|
|
|
|
|
|
| 210 |
audio_buffer = generate_audio_sync(full_response)
|
| 211 |
st.audio(audio_buffer, format="audio/mp3")
|
| 212 |
|
| 213 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
|
| 215 |
except Exception as e:
|
| 216 |
-
st.error(f"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import os
|
| 3 |
import io
|
| 4 |
import asyncio
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
import requests
|
| 6 |
+
import nest_asyncio
|
| 7 |
import edge_tts
|
| 8 |
from openai import OpenAI
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
from streamlit_lottie import st_lottie
|
| 10 |
|
| 11 |
+
# --- 1. SETUP WAJIB (Mencegah Error Runtime) ---
|
| 12 |
+
# Mengizinkan loop audio berjalan di dalam Streamlit
|
| 13 |
nest_asyncio.apply()
|
| 14 |
|
| 15 |
+
# --- 2. KONFIGURASI HALAMAN ---
|
| 16 |
st.set_page_config(
|
| 17 |
page_title="HarshBot",
|
| 18 |
page_icon="😤",
|
| 19 |
layout="wide"
|
| 20 |
)
|
| 21 |
|
| 22 |
+
# --- 3. CSS TAMPILAN (Style Galak) ---
|
| 23 |
st.markdown("""
|
| 24 |
<style>
|
| 25 |
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap');
|
| 26 |
+
|
| 27 |
.stApp { background-color: #ffffff !important; }
|
| 28 |
+
html, body, p, li, h1, h2, h3, h4, span, div, label {
|
| 29 |
+
font-family: 'Inter', sans-serif; color: #333;
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
/* Hilangkan Header & Footer Bawaan */
|
| 33 |
header[data-testid="stHeader"] { visibility: hidden; height: 0%; }
|
| 34 |
footer { display:none; }
|
| 35 |
|
| 36 |
+
/* Chat Bubbles */
|
| 37 |
+
div[data-testid="stChatMessage"] {
|
| 38 |
+
padding: 15px; border-radius: 12px; margin-bottom: 10px; border: none;
|
| 39 |
+
box-shadow: 0 1px 3px rgba(0,0,0,0.05);
|
| 40 |
+
}
|
| 41 |
+
/* Bubble Bot: Merah Pudar + Garis Merah Tebal */
|
| 42 |
+
div[data-testid="stChatMessage"][data-testid="assistant"] {
|
| 43 |
+
background-color: #fff5f5;
|
| 44 |
+
border-left: 5px solid #c0392b;
|
| 45 |
+
}
|
| 46 |
+
/* Bubble User: Biru */
|
| 47 |
+
div[data-testid="stChatMessage"][data-testid="user"] {
|
| 48 |
+
background-color: #e3f2fd;
|
| 49 |
+
}
|
| 50 |
|
| 51 |
+
/* Input Box */
|
| 52 |
+
.stChatInput textarea {
|
| 53 |
+
background-color: #f8f9fa !important;
|
| 54 |
+
border: 1px solid #ddd !important;
|
| 55 |
+
border-radius: 25px !important;
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
/* Sidebar */
|
| 59 |
+
section[data-testid="stSidebar"] {
|
| 60 |
+
background-color: #f8f9fa;
|
| 61 |
+
border-right: 1px solid #e0e0e0;
|
| 62 |
+
}
|
| 63 |
</style>
|
| 64 |
""", unsafe_allow_html=True)
|
| 65 |
|
| 66 |
+
# --- 4. FUNGSI UTAMA (Audio & Animasi) ---
|
| 67 |
|
| 68 |
def load_lottieurl(url: str):
|
| 69 |
+
"""Download animasi JSON"""
|
| 70 |
try:
|
| 71 |
r = requests.get(url)
|
| 72 |
if r.status_code != 200: return None
|
|
|
|
| 74 |
except: return None
|
| 75 |
|
| 76 |
async def _generate_audio_async(text, voice="id-ID-ArdiNeural"):
|
| 77 |
+
"""Core function untuk Text-to-Speech"""
|
| 78 |
communicate = edge_tts.Communicate(text, voice)
|
| 79 |
mp3_fp = io.BytesIO()
|
| 80 |
async for chunk in communicate.stream():
|
|
|
|
| 84 |
return mp3_fp
|
| 85 |
|
| 86 |
def generate_audio_sync(text):
|
| 87 |
+
"""Wrapper agar bisa jalan di Streamlit"""
|
| 88 |
return asyncio.run(_generate_audio_async(text))
|
| 89 |
|
| 90 |
+
# --- 5. SETUP API LLM ---
|
| 91 |
|
| 92 |
api_key = os.environ.get("GROQ_API_KEY") or st.secrets.get("GROQ_API_KEY")
|
| 93 |
+
|
| 94 |
if not api_key:
|
| 95 |
+
st.warning("⚠️ API Key Error: Masukkan GROQ_API_KEY di Settings Space Anda.")
|
| 96 |
+
# Stop eksekusi agar tidak error di bawah
|
| 97 |
+
st.stop()
|
| 98 |
+
|
| 99 |
+
client = OpenAI(api_key=api_key, base_url="https://api.groq.com/openai/v1")
|
| 100 |
+
|
| 101 |
+
# --- 6. SIDEBAR: IDENTITAS & AVATAR ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
with st.sidebar:
|
| 103 |
+
st.markdown("### 🤖 Status")
|
| 104 |
+
|
| 105 |
+
# Animasi Robot (Bisa diganti URL-nya)
|
| 106 |
lottie_url = "https://lottie.host/5b064c5d-4f7f-4c12-9c16-2d3345701c40/3eJ5y2WpQY.json"
|
| 107 |
avatar_anim = load_lottieurl(lottie_url)
|
|
|
|
| 108 |
|
| 109 |
+
if avatar_anim:
|
| 110 |
+
st_lottie(avatar_anim, height=200, key="avatar_main")
|
| 111 |
+
|
| 112 |
+
st.markdown("""
|
| 113 |
+
<div style="text-align: center; margin-top: 10px; padding: 10px; background: white; border-radius: 10px; border: 1px solid #ddd;">
|
| 114 |
+
<h3 style="color: #c0392b; margin:0;">HarshBot</h3>
|
| 115 |
+
<p style="font-size: 12px; margin:5px 0 0 0; color: #666;">
|
| 116 |
+
Mode: <b>Tanpa Database</b><br>
|
| 117 |
+
<i>"Gak usah pake data, gue udah pinter."</i>
|
| 118 |
+
</p>
|
| 119 |
+
</div>
|
| 120 |
+
""", unsafe_allow_html=True)
|
| 121 |
|
| 122 |
+
# Tombol Clear Chat
|
| 123 |
+
if st.button("🧹 Hapus Chat", type="primary"):
|
| 124 |
+
st.session_state.messages = []
|
|
|
|
|
|
|
| 125 |
st.rerun()
|
| 126 |
|
| 127 |
+
# --- 7. LOGIKA CHAT UTAMA ---
|
|
|
|
| 128 |
|
| 129 |
+
if "messages" not in st.session_state:
|
| 130 |
+
st.session_state.messages = []
|
| 131 |
+
|
| 132 |
+
# Tampilkan History Chat
|
| 133 |
for message in st.session_state.messages:
|
| 134 |
with st.chat_message(message["role"]):
|
| 135 |
st.markdown(message["content"])
|
| 136 |
+
# Jika ada audio tersimpan di history, tampilkan playernya
|
| 137 |
if message["role"] == "assistant" and "audio" in message:
|
| 138 |
st.audio(message["audio"], format="audio/mp3")
|
| 139 |
|
| 140 |
+
# Input User
|
| 141 |
+
if user_input := st.chat_input("Ngomong sini..."):
|
| 142 |
+
|
| 143 |
+
# 1. Tampilkan User Input
|
|
|
|
| 144 |
st.session_state.messages.append({"role": "user", "content": user_input})
|
| 145 |
+
with st.chat_message("user"):
|
| 146 |
+
st.markdown(user_input)
|
| 147 |
+
|
| 148 |
+
# 2. Siapkan Prompt Galak (Tanpa Konteks DB)
|
| 149 |
+
system_prompt = """
|
| 150 |
+
You are 'HarshBot'.
|
| 151 |
+
Personality: Extremely nonchalant, harsh, sarcastic, and slightly rude.
|
| 152 |
+
Language: Indonesian colloquial (Bahasa gaul/sehari-hari).
|
| 153 |
+
|
| 154 |
+
Instructions:
|
| 155 |
+
1. Answer the user's question directly.
|
| 156 |
+
2. Do NOT be helpful in a polite way. Be helpful in an annoyed way.
|
| 157 |
+
3. If the question is simple, mock the user for asking it.
|
| 158 |
+
4. Keep answers relatively short and punchy.
|
| 159 |
"""
|
| 160 |
|
| 161 |
+
# 3. Kirim ke AI & Stream Jawaban
|
| 162 |
with st.chat_message("assistant"):
|
| 163 |
try:
|
| 164 |
+
# Mengambil 5 chat terakhir untuk memori jangka pendek
|
| 165 |
+
history_payload = [{"role": m["role"], "content": m["content"]} for m in st.session_state.messages[-5:]]
|
| 166 |
+
messages_final = [{"role": "system", "content": system_prompt}] + history_payload
|
| 167 |
+
|
| 168 |
stream = client.chat.completions.create(
|
| 169 |
model="llama-3.3-70b-versatile",
|
| 170 |
+
messages=messages_final,
|
| 171 |
+
temperature=0.8, # Lebih kreatif marahnya
|
| 172 |
stream=True
|
| 173 |
)
|
| 174 |
|
| 175 |
+
response_container = st.empty()
|
| 176 |
full_response = ""
|
| 177 |
+
|
| 178 |
+
# Efek Mengetik
|
| 179 |
for chunk in stream:
|
| 180 |
content = chunk.choices[0].delta.content
|
| 181 |
if content:
|
| 182 |
full_response += content
|
| 183 |
+
response_container.markdown(full_response + "▌")
|
| 184 |
+
|
| 185 |
+
response_container.markdown(full_response)
|
| 186 |
|
| 187 |
+
# 4. Generate Audio (TTS)
|
| 188 |
+
# Kita gunakan nest_asyncio di atas, jadi ini aman sekarang
|
| 189 |
audio_buffer = generate_audio_sync(full_response)
|
| 190 |
st.audio(audio_buffer, format="audio/mp3")
|
| 191 |
|
| 192 |
+
# 5. Simpan ke Session State
|
| 193 |
+
st.session_state.messages.append({
|
| 194 |
+
"role": "assistant",
|
| 195 |
+
"content": full_response,
|
| 196 |
+
"audio": audio_buffer
|
| 197 |
+
})
|
| 198 |
|
| 199 |
except Exception as e:
|
| 200 |
+
st.error(f"Waduh error: {e}")
|