Vr711 commited on
Commit
bbefddf
·
verified ·
1 Parent(s): 6c77c95

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +292 -0
app.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __import__('pysqlite3')
2
+ import sys
3
+ sys.modules['sqlite3'] = sys.modules.pop('pysqlite3')
4
+
5
+ import streamlit as st
6
+ import os
7
+ import io
8
+ import asyncio
9
+ import json
10
+ import hashlib
11
+ import shutil
12
+ import time
13
+ import requests
14
+ import edge_tts
15
+ from openai import OpenAI
16
+ from langchain_community.document_loaders import PyPDFLoader, Docx2txtLoader, TextLoader
17
+ from langchain_community.vectorstores import Chroma
18
+ from langchain_huggingface import HuggingFaceEmbeddings
19
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
20
+ from streamlit_lottie import st_lottie
21
+
22
+ # --- 1. KONFIGURASI HALAMAN ---
23
+ st.set_page_config(
24
+ page_title="HarshBot - Sobat Digi Galak",
25
+ page_icon="😤",
26
+ layout="wide"
27
+ )
28
+
29
+ # --- 2. CSS CUSTOM (TAMPILAN BERSIH & GALAK) ---
30
+ st.markdown("""
31
+ <style>
32
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap');
33
+
34
+ .stApp { background-color: #ffffff !important; }
35
+ html, body, p, li, h1, h2, h3, h4, span, div, label {
36
+ font-family: 'Inter', sans-serif; color: #333333;
37
+ }
38
+
39
+ /* HIDE HEADER & FOOTER */
40
+ header[data-testid="stHeader"] { visibility: hidden; height: 0%; }
41
+ footer { display:none; }
42
+
43
+ /* CHAT BUBBLES */
44
+ div[data-testid="stChatMessage"] {
45
+ padding: 15px; border-radius: 12px; margin-bottom: 10px; border: none;
46
+ box-shadow: 0 1px 3px rgba(0,0,0,0.05);
47
+ }
48
+
49
+ /* Bubble Asisten (Merah Muda - Kesan Marah) */
50
+ div[data-testid="stChatMessage"][data-testid="assistant"] {
51
+ background-color: #fff5f5;
52
+ border-left: 5px solid #c0392b;
53
+ }
54
+
55
+ /* Bubble User (Biru Muda) */
56
+ div[data-testid="stChatMessage"][data-testid="user"] {
57
+ background-color: #e3f2fd;
58
+ color: #000000;
59
+ }
60
+
61
+ /* INPUT BOX */
62
+ div[data-testid="stBottom"] { background-color: #ffffff !important; border-top: 1px solid #e0e0e0; }
63
+ .stChatInput textarea {
64
+ background-color: #f8f9fa !important; border: 1px solid #e0e0e0 !important; border-radius: 25px !important;
65
+ }
66
+
67
+ /* SIDEBAR */
68
+ section[data-testid="stSidebar"] {
69
+ background-color: #f8f9fa;
70
+ border-right: 1px solid #e0e0e0;
71
+ }
72
+ </style>
73
+ """, unsafe_allow_html=True)
74
+
75
+ # --- 3. FUNGSI UTILITAS (AUDIO & ANIMASI) ---
76
+
77
+ def load_lottieurl(url: str):
78
+ """Load animasi Lottie dari URL"""
79
+ try:
80
+ r = requests.get(url)
81
+ if r.status_code != 200: return None
82
+ return r.json()
83
+ except: return None
84
+
85
+ async def _generate_audio_async(text, voice="id-ID-ArdiNeural"):
86
+ """Generate audio TTS (Async)"""
87
+ communicate = edge_tts.Communicate(text, voice)
88
+ mp3_fp = io.BytesIO()
89
+ async for chunk in communicate.stream():
90
+ if chunk["type"] == "audio":
91
+ mp3_fp.write(chunk["data"])
92
+ mp3_fp.seek(0)
93
+ return mp3_fp
94
+
95
+ def generate_audio_sync(text):
96
+ """Wrapper Sync untuk TTS"""
97
+ try:
98
+ loop = asyncio.get_event_loop()
99
+ except RuntimeError:
100
+ loop = asyncio.new_event_loop()
101
+ asyncio.set_event_loop(loop)
102
+
103
+ if loop.is_running():
104
+ future = asyncio.run_coroutine_threadsafe(_generate_audio_async(text), loop)
105
+ return future.result()
106
+ else:
107
+ return loop.run_until_complete(_generate_audio_async(text))
108
+
109
+ # --- 4. ENGINE: DATABASE & LLM ---
110
+
111
+ api_key = os.environ.get("GROQ_API_KEY") or st.secrets.get("GROQ_API_KEY")
112
+ if not api_key:
113
+ st.error("⚠️ API Key Error: GROQ_API_KEY tidak ditemukan.")
114
+ st.stop()
115
+
116
+ client = OpenAI(api_key=api_key, base_url="https://api.groq.com/openai/v1")
117
+
118
+ # Konfigurasi Path Database
119
+ DB_PATH = "./chroma_db_store"
120
+ METADATA_PATH = "db_metadata.json"
121
+
122
+ def get_files_signature(folder_path="."):
123
+ """Cek apakah ada perubahan file dokumen"""
124
+ file_signatures = []
125
+ for root, dirs, files in os.walk(folder_path):
126
+ for file in files:
127
+ if "chroma_db" in root or file.startswith("."): continue
128
+ if file.lower().endswith(('.pdf', '.docx', '.txt')) and "requirements" not in file:
129
+ full_path = os.path.join(root, file)
130
+ mtime = os.path.getmtime(full_path)
131
+ file_signatures.append(f"{file}_{mtime}")
132
+ return hashlib.md5("".join(sorted(file_signatures)).encode()).hexdigest()
133
+
134
+ @st.cache_resource
135
+ def get_vectorstore():
136
+ """Inisialisasi Database Vektor dengan HuggingFace Embeddings"""
137
+ embedding_function = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
138
+
139
+ current_signature = get_files_signature(".")
140
+ last_signature = ""
141
+
142
+ if os.path.exists(METADATA_PATH):
143
+ with open(METADATA_PATH, "r") as f:
144
+ try: last_signature = json.load(f).get("signature", "")
145
+ except: pass
146
+
147
+ db_exists = os.path.exists(DB_PATH) and len(os.listdir(DB_PATH)) > 0
148
+ is_changed = current_signature != last_signature
149
+
150
+ if db_exists and not is_changed:
151
+ print("✅ Menggunakan Database Lama.")
152
+ return Chroma(persist_directory=DB_PATH, embedding_function=embedding_function)
153
+
154
+ print("🔄 Membangun Ulang Database...")
155
+ if os.path.exists(DB_PATH): shutil.rmtree(DB_PATH, ignore_errors=True)
156
+
157
+ documents = []
158
+ for root, dirs, files in os.walk("."):
159
+ if "chroma_db" in root: continue
160
+ for file in files:
161
+ full_path = os.path.join(root, file)
162
+ try:
163
+ if file.lower().endswith(".pdf"): documents.extend(PyPDFLoader(full_path).load())
164
+ elif file.lower().endswith(".docx"): documents.extend(Docx2txtLoader(full_path).load())
165
+ elif file.lower().endswith(".txt") and "requirements" not in file: documents.extend(TextLoader(full_path, encoding='utf-8').load())
166
+ except: pass
167
+
168
+ if not documents: return None
169
+
170
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
171
+ splits = text_splitter.split_documents(documents)
172
+
173
+ db = Chroma.from_documents(documents=splits, embedding=embedding_function, persist_directory=DB_PATH)
174
+
175
+ with open(METADATA_PATH, "w") as f: json.dump({"signature": current_signature}, f)
176
+ return db
177
+
178
+ # Load Database
179
+ db = get_vectorstore()
180
+
181
+ # --- 5. SIDEBAR: AVATAR & TOMBOL RESET ---
182
+ with st.sidebar:
183
+ st.markdown("### 🤖 Identity")
184
+
185
+ # Animasi Robot (Lottie)
186
+ # Ganti URL ini jika ingin animasi lain
187
+ lottie_url = "https://lottie.host/5b064c5d-4f7f-4c12-9c16-2d3345701c40/3eJ5y2WpQY.json"
188
+ avatar_anim = load_lottieurl(lottie_url)
189
+
190
+ if avatar_anim:
191
+ st_lottie(avatar_anim, height=180, key="avatar_main")
192
+ else:
193
+ st.write("🤖 [Avatar Error]")
194
+
195
+ st.markdown("""
196
+ <div style="background-color: #fff; padding: 10px; border-radius: 8px; border: 1px solid #ddd; margin-top: 10px; text-align: center;">
197
+ <h3 style="margin:0; color: #c0392b;">HarshBot</h3>
198
+ <p style="font-size: 12px; margin:0; color: #555;">Jangan tanya hal bodoh.</p>
199
+ </div>
200
+ """, unsafe_allow_html=True)
201
+
202
+ st.markdown("---")
203
+
204
+ # TOMBOL RESET DATABASE (Permintaan Anda)
205
+ if st.button("🗑️ Hapus & Reset Database", type="primary"):
206
+ with st.spinner("Menghapus ingatan..."):
207
+ try:
208
+ if os.path.exists(DB_PATH):
209
+ shutil.rmtree(DB_PATH)
210
+ if os.path.exists(METADATA_PATH):
211
+ os.remove(METADATA_PATH)
212
+ st.success("Database dihapus!")
213
+ time.sleep(1)
214
+ st.rerun()
215
+ except Exception as e:
216
+ st.error(f"Gagal: {e}")
217
+
218
+ # --- 6. CHAT INTERFACE ---
219
+
220
+ if "messages" not in st.session_state:
221
+ st.session_state.messages = []
222
+
223
+ # Tampilkan History
224
+ for message in st.session_state.messages:
225
+ with st.chat_message(message["role"]):
226
+ st.markdown(message["content"])
227
+ if message["role"] == "assistant" and "audio" in message:
228
+ st.audio(message["audio"], format="audio/mp3")
229
+
230
+ # Input User
231
+ if user_input := st.chat_input("Tulis pertanyaan lo di sini..."):
232
+ st.session_state.messages.append({"role": "user", "content": user_input})
233
+ with st.chat_message("user"):
234
+ st.markdown(user_input)
235
+
236
+ # Cari Konteks (RAG)
237
+ konteks = ""
238
+ if db:
239
+ try:
240
+ docs = db.similarity_search(user_input, k=3)
241
+ konteks = "\n\n".join([d.page_content for d in docs])
242
+ except: pass
243
+
244
+ # Prompt Galak
245
+ system_prompt = f"""You are a very harsh, sarcastic, and nonchalant chatbot.
246
+
247
+ CONTEXT DATA:
248
+ {konteks}
249
+
250
+ INSTRUCTION:
251
+ 1. Act nonchalant and slightly annoyed.
252
+ 2. Use non-formal Indonesian language (bahasa gaul/kasar sopan).
253
+ 3. Provide the answer based on CONTEXT DATA if available, but do it grudgingly.
254
+ 4. If no context matches, mock the user for asking something irrelevant.
255
+ """
256
+
257
+ with st.chat_message("assistant"):
258
+ try:
259
+ # Generate Text
260
+ history_payload = [{"role": m["role"], "content": m["content"]} for m in st.session_state.messages[-5:]]
261
+ messages_final = [{"role": "system", "content": system_prompt}] + history_payload
262
+
263
+ stream = client.chat.completions.create(
264
+ model="llama-3.3-70b-versatile",
265
+ messages=messages_final,
266
+ temperature=0.7,
267
+ stream=True
268
+ )
269
+
270
+ response_placeholder = st.empty()
271
+ full_response = ""
272
+
273
+ for chunk in stream:
274
+ content = chunk.choices[0].delta.content
275
+ if content:
276
+ full_response += content
277
+ response_placeholder.markdown(full_response + "▌")
278
+
279
+ response_placeholder.markdown(full_response)
280
+
281
+ # Generate Audio
282
+ audio_buffer = generate_audio_sync(full_response)
283
+ st.audio(audio_buffer, format="audio/mp3")
284
+
285
+ st.session_state.messages.append({
286
+ "role": "assistant",
287
+ "content": full_response,
288
+ "audio": audio_buffer
289
+ })
290
+
291
+ except Exception as e:
292
+ st.error(f"Error: {e}")