Harshchatbot / app.py
Vr711's picture
Update app.py
2d1d1bd verified
Raw History Blame Contribute Delete
10.1 kB
__import__('pysqlite3')
import sys
sys.modules['sqlite3'] = sys.modules.pop('pysqlite3')
import streamlit as st
import os
import io
import asyncio
import json
import hashlib
import shutil
import time
import requests
import edge_tts
from openai import OpenAI
from langchain_community.document_loaders import PyPDFLoader, Docx2txtLoader, TextLoader
from langchain_community.vectorstores import Chroma
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter
from streamlit_lottie import st_lottie
# --- 1. KONFIGURASI HALAMAN ---
st.set_page_config(
page_title="HarshBot - Sobat Digi Galak",
page_icon="๐Ÿ˜ค",
layout="wide"
)
# --- 2. CSS CUSTOM (TAMPILAN BERSIH & 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: #333333;
}
/* HIDE HEADER & FOOTER */
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 Asisten (Merah Muda - Kesan Marah) */
div[data-testid="stChatMessage"][data-testid="assistant"] {
background-color: #fff5f5;
border-left: 5px solid #c0392b;
}
/* Bubble User (Biru Muda) */
div[data-testid="stChatMessage"][data-testid="user"] {
background-color: #e3f2fd;
color: #000000;
}
/* INPUT BOX */
div[data-testid="stBottom"] { background-color: #ffffff !important; border-top: 1px solid #e0e0e0; }
.stChatInput textarea {
background-color: #f8f9fa !important; border: 1px solid #e0e0e0 !important; border-radius: 25px !important;
}
/* SIDEBAR */
section[data-testid="stSidebar"] {
background-color: #f8f9fa;
border-right: 1px solid #e0e0e0;
}
</style>
""", unsafe_allow_html=True)
# --- 3. FUNGSI UTILITAS (AUDIO & ANIMASI) ---
def load_lottieurl(url: str):
"""Load animasi Lottie dari URL"""
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"):
"""Generate audio TTS (Async)"""
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 Sync untuk TTS"""
try:
loop = asyncio.get_event_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
if loop.is_running():
future = asyncio.run_coroutine_threadsafe(_generate_audio_async(text), loop)
return future.result()
else:
return loop.run_until_complete(_generate_audio_async(text))
# --- 4. ENGINE: DATABASE & LLM ---
api_key = os.environ.get("GROQ_API_KEY") or st.secrets.get("GROQ_API_KEY")
if not api_key:
st.error("โš ๏ธ API Key Error: GROQ_API_KEY tidak ditemukan.")
st.stop()
client = OpenAI(api_key=api_key, base_url="https://api.groq.com/openai/v1")
# Konfigurasi Path Database
DB_PATH = "./chroma_db_store"
METADATA_PATH = "db_metadata.json"
def get_files_signature(folder_path="."):
"""Cek apakah ada perubahan file dokumen"""
file_signatures = []
for root, dirs, files in os.walk(folder_path):
for file in files:
if "chroma_db" in root or file.startswith("."): continue
if file.lower().endswith(('.pdf', '.docx', '.txt')) and "requirements" not in file:
full_path = os.path.join(root, file)
mtime = os.path.getmtime(full_path)
file_signatures.append(f"{file}_{mtime}")
return hashlib.md5("".join(sorted(file_signatures)).encode()).hexdigest()
@st.cache_resource
def get_vectorstore():
"""Inisialisasi Database Vektor dengan HuggingFace Embeddings"""
embedding_function = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
current_signature = get_files_signature(".")
last_signature = ""
if os.path.exists(METADATA_PATH):
with open(METADATA_PATH, "r") as f:
try: last_signature = json.load(f).get("signature", "")
except: pass
db_exists = os.path.exists(DB_PATH) and len(os.listdir(DB_PATH)) > 0
is_changed = current_signature != last_signature
if db_exists and not is_changed:
print("โœ… Menggunakan Database Lama.")
return Chroma(persist_directory=DB_PATH, embedding_function=embedding_function)
print("๐Ÿ”„ Membangun Ulang Database...")
if os.path.exists(DB_PATH): shutil.rmtree(DB_PATH, ignore_errors=True)
documents = []
for root, dirs, files in os.walk("."):
if "chroma_db" in root: continue
for file in files:
full_path = os.path.join(root, file)
try:
if file.lower().endswith(".pdf"): documents.extend(PyPDFLoader(full_path).load())
elif file.lower().endswith(".docx"): documents.extend(Docx2txtLoader(full_path).load())
elif file.lower().endswith(".txt") and "requirements" not in file: documents.extend(TextLoader(full_path, encoding='utf-8').load())
except: pass
if not documents: return None
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
splits = text_splitter.split_documents(documents)
db = Chroma.from_documents(documents=splits, embedding=embedding_function, persist_directory=DB_PATH)
with open(METADATA_PATH, "w") as f: json.dump({"signature": current_signature}, f)
return db
# Load Database
db = get_vectorstore()
# --- 5. SIDEBAR: AVATAR & TOMBOL RESET ---
with st.sidebar:
st.markdown("### ๐Ÿค– Identity")
# Animasi Robot (Lottie)
# Ganti URL ini jika ingin animasi lain
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=180, key="avatar_main")
else:
st.write("๐Ÿค– [Avatar Error]")
st.markdown("""
<div style="background-color: #fff; padding: 10px; border-radius: 8px; border: 1px solid #ddd; margin-top: 10px; text-align: center;">
<h3 style="margin:0; color: #c0392b;">HarshBot</h3>
<p style="font-size: 12px; margin:0; color: #555;">Jangan tanya hal bodoh.</p>
</div>
""", unsafe_allow_html=True)
st.markdown("---")
# TOMBOL RESET DATABASE (Permintaan Anda)
if st.button("๐Ÿ—‘๏ธ Hapus & Reset Database", type="primary"):
with st.spinner("Menghapus ingatan..."):
try:
if os.path.exists(DB_PATH):
shutil.rmtree(DB_PATH)
if os.path.exists(METADATA_PATH):
os.remove(METADATA_PATH)
st.success("Database dihapus!")
time.sleep(1)
st.rerun()
except Exception as e:
st.error(f"Gagal: {e}")
# --- 6. CHAT INTERFACE ---
if "messages" not in st.session_state:
st.session_state.messages = []
# Tampilkan History
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
if message["role"] == "assistant" and "audio" in message:
st.audio(message["audio"], format="audio/mp3")
# Input User
if user_input := st.chat_input("Tulis pertanyaan lo di sini..."):
st.session_state.messages.append({"role": "user", "content": user_input})
with st.chat_message("user"):
st.markdown(user_input)
# Cari Konteks (RAG)
konteks = ""
if db:
try:
docs = db.similarity_search(user_input, k=3)
konteks = "\n\n".join([d.page_content for d in docs])
except: pass
# Prompt Galak
system_prompt = f"""You are a very harsh, sarcastic, and nonchalant chatbot.
CONTEXT DATA:
{konteks}
INSTRUCTION:
1. Act nonchalant and slightly annoyed.
2. Use non-formal Indonesian language (bahasa gaul/kasar sopan).
3. Provide the answer based on CONTEXT DATA if available, but do it grudgingly.
4. If no context matches, mock the user for asking something irrelevant.
"""
with st.chat_message("assistant"):
try:
# Generate Text
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.7,
stream=True
)
response_placeholder = st.empty()
full_response = ""
for chunk in stream:
content = chunk.choices[0].delta.content
if content:
full_response += content
response_placeholder.markdown(full_response + "โ–Œ")
response_placeholder.markdown(full_response)
# Generate Audio
audio_buffer = generate_audio_sync(full_response)
st.audio(audio_buffer, format="audio/mp3")
st.session_state.messages.append({
"role": "assistant",
"content": full_response,
"audio": audio_buffer
})
except Exception as e:
st.error(f"Error: {e}")