BramLeo commited on
Commit
01f654d
Β·
verified Β·
1 Parent(s): 2e89b04

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -78
app.py CHANGED
@@ -1,87 +1,43 @@
1
  import gradio as gr
2
- import gdown
3
  import pandas as pd
4
  import os
5
- import shutil
6
  import threading
7
  import schedule
8
  import time
9
  from datetime import datetime
10
- from llama_cpp import Llama
11
  from llama_index.core import SimpleDirectoryReader, VectorStoreIndex, Settings, Document
12
- from llama_index.core.llms import ChatMessage
13
- from llama_index.llms.llama_cpp import LlamaCPP
14
  from llama_index.embeddings.huggingface import HuggingFaceEmbedding
15
  from huggingface_hub import hf_hub_download
16
- from llama_index.core.node_parser import SentenceSplitter
17
-
18
- # Fungsi untuk mengunduh model Llama
19
- def initialize_llama_model():
20
- model_path = hf_hub_download(
21
- repo_id="TheBloke/zephyr-7b-beta-GGUF",
22
- filename="zephyr-7b-beta.Q4_K_M.gguf",
23
- cache_dir="./models"
24
- )
25
- return model_path
26
-
27
- # Fungsi untuk mengatur konfigurasi Settings
28
- def initialize_settings(model_path):
29
- Settings.llm = LlamaCPP(
30
- model_path=model_path,
31
- temperature=0.7,
32
- )
33
-
34
- # Fungsi untuk mengunduh file CSV terbaru dari Google Drive
35
- def download_csv_from_drive():
36
- csv_url = "https://drive.google.com/uc?id=1UIx369_8GlzPiKArMVg8v-IwC6hYTYA0" # Ganti dengan ID file terbaru
37
- output_folder = "bahandokumen"
38
- output_csv = os.path.join(output_folder, "data.csv") # Path lengkap ke dalam folder
39
-
40
- # Pastikan folder bahandokumen/ ada
41
- os.makedirs(output_folder, exist_ok=True)
42
 
43
- # Hapus file lama jika ada
44
- if os.path.exists(output_csv):
45
- os.remove(output_csv)
 
46
 
47
- print("πŸ”„ Mengunduh file CSV terbaru...")
 
48
  try:
49
- gdown.download(csv_url, output_csv, quiet=False)
50
- if os.path.exists(output_csv):
51
- print(f"βœ… File berhasil diunduh: {output_csv}")
52
- else:
53
- print("❌ Gagal mengunduh file. Cek kembali link Google Drive.")
54
  except Exception as e:
55
- print(f"❌ Terjadi kesalahan saat mengunduh file: {e}")
56
-
57
- return output_csv
58
 
59
- # Fungsi untuk menyimpan file ke jalur yang sesuai di Hugging Face Spaces
60
- def save_to_huggingface():
61
- src = "bahandokumen/data.csv"
62
- dst = "/home/user/app/bahandokumen/data.csv" # Jalur sesuai dengan HF Spaces
63
-
64
- # Pastikan file ada sebelum menyalin
65
- if os.path.exists(src):
66
- if os.path.abspath(src) != os.path.abspath(dst): # Cek apakah lokasi berbeda
67
- shutil.copy(src, dst)
68
- print(f"βœ… File {src} berhasil disalin ke {dst}")
69
- else:
70
- print("⚠️ File sudah berada di lokasi yang sama, tidak perlu disalin.")
71
- else:
72
- print("❌ File tidak ditemukan, pastikan berhasil diunduh.")
73
-
74
- # Fungsi untuk update index chatbot
75
  def update_index():
76
  print(f"πŸ”„ [{datetime.now()}] Mengupdate index dengan data terbaru...")
77
- csv_file = download_csv_from_drive()
78
- save_to_huggingface()
 
 
 
79
 
80
- # Baca CSV dengan Pandas
81
- df = pd.read_csv(csv_file)
82
  documents = [Document(text=" | ".join(map(str, row.values))) for _, row in df.iterrows()]
83
 
84
- # Tambahkan file dokumen lain
85
  text_documents = SimpleDirectoryReader(input_files=[
86
  "bahandokumen/K3.txt",
87
  "bahandokumen/bonus.txt",
@@ -103,42 +59,39 @@ def update_index():
103
  index = VectorStoreIndex(nodes)
104
  print("βœ… Index berhasil diperbarui!")
105
 
106
- # Inisialisasi Mesin Chat
107
  def initialize_chat_engine():
108
  return index.as_chat_engine(chat_mode="condense_plus_context", similarity_top_k=3)
109
 
110
- # Fungsi untuk menghasilkan respons chatbot
111
  def generate_response(message, history):
112
  chat_engine = initialize_chat_engine()
113
  response = chat_engine.stream_chat(message)
114
- text = "".join(response.response_gen)
115
- history.append((message, text))
116
  return history
117
 
118
- # Scheduler untuk update otomatis setiap jam 12 malam
119
  def schedule_update():
120
  schedule.every().day.at("00:00").do(update_index)
121
  while True:
122
  schedule.run_pending()
123
- time.sleep(60) # Cek setiap 1 menit
124
 
125
- # Fungsi untuk menjalankan scheduler di thread terpisah
126
  def start_scheduler():
127
  thread = threading.Thread(target=schedule_update, daemon=True)
128
  thread.start()
129
 
130
- # Inisialisasi Komponen Gradio untuk UI
131
  def launch_gradio():
132
  with gr.Blocks() as demo:
133
- clear_btn = gr.Button("Clear")
134
- chat_interface = gr.ChatInterface(lambda message, history: generate_response(message, history))
135
  demo.launch()
136
 
137
- # Fungsi Utama untuk Menjalankan Aplikasi
138
  def main():
139
  global index # Agar index bisa diperbarui secara global
140
- model_path = initialize_llama_model()
141
- initialize_settings(model_path)
142
 
143
  print("πŸ”„ Inisialisasi index pertama kali...")
144
  update_index()
@@ -149,4 +102,4 @@ def main():
149
  launch_gradio()
150
 
151
  if __name__ == "__main__":
152
- main()
 
1
  import gradio as gr
 
2
  import pandas as pd
3
  import os
 
4
  import threading
5
  import schedule
6
  import time
7
  from datetime import datetime
 
8
  from llama_index.core import SimpleDirectoryReader, VectorStoreIndex, Settings, Document
9
+ from llama_index.core.node_parser import SentenceSplitter
 
10
  from llama_index.embeddings.huggingface import HuggingFaceEmbedding
11
  from huggingface_hub import hf_hub_download
12
+ from llama_index.llms.llama_cpp import LlamaCPP
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ # Fungsi untuk membaca Google Sheets sebagai DataFrame
15
+ def fetch_google_sheets_data():
16
+ sheet_id = "1740C15sMgOowI5wv5Q-kmYQUXMJUEyRSrFXRwIMc4Z0" # Ganti dengan ID Google Sheets Anda
17
+ sheet_name = "datatarget" # Ganti dengan nama sheet
18
 
19
+ url = f"https://docs.google.com/spreadsheets/d/1740C15sMgOowI5wv5Q-kmYQUXMJUEyRSrFXRwIMc4Z0/edit?gid=1097907532#gid=1097907532"
20
+
21
  try:
22
+ df = pd.read_csv(url)
23
+ print("βœ… Data berhasil diambil dari Google Sheets!")
24
+ return df
 
 
25
  except Exception as e:
26
+ print(f"❌ Gagal mengambil data: {e}")
27
+ return None
 
28
 
29
+ # Fungsi untuk update index chatbot dengan data terbaru dari Google Sheets
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  def update_index():
31
  print(f"πŸ”„ [{datetime.now()}] Mengupdate index dengan data terbaru...")
32
+
33
+ df = fetch_google_sheets_data()
34
+ if df is None:
35
+ print("⚠️ Tidak bisa memperbarui index karena gagal membaca Google Sheets.")
36
+ return
37
 
 
 
38
  documents = [Document(text=" | ".join(map(str, row.values))) for _, row in df.iterrows()]
39
 
40
+ # Tambahkan dokumen tambahan dari teks lokal
41
  text_documents = SimpleDirectoryReader(input_files=[
42
  "bahandokumen/K3.txt",
43
  "bahandokumen/bonus.txt",
 
59
  index = VectorStoreIndex(nodes)
60
  print("βœ… Index berhasil diperbarui!")
61
 
62
+ # Inisialisasi Chatbot
63
  def initialize_chat_engine():
64
  return index.as_chat_engine(chat_mode="condense_plus_context", similarity_top_k=3)
65
 
66
+ # Fungsi untuk mendapatkan respons chatbot
67
  def generate_response(message, history):
68
  chat_engine = initialize_chat_engine()
69
  response = chat_engine.stream_chat(message)
70
+ text = "".join(response.response_gen)
71
+ history.append((message, text))
72
  return history
73
 
74
+ # Scheduler untuk update otomatis
75
  def schedule_update():
76
  schedule.every().day.at("00:00").do(update_index)
77
  while True:
78
  schedule.run_pending()
79
+ time.sleep(60)
80
 
81
+ # Menjalankan scheduler di thread terpisah
82
  def start_scheduler():
83
  thread = threading.Thread(target=schedule_update, daemon=True)
84
  thread.start()
85
 
86
+ # Inisialisasi Gradio
87
  def launch_gradio():
88
  with gr.Blocks() as demo:
89
+ gr.ChatInterface(lambda message, history: generate_response(message, history))
 
90
  demo.launch()
91
 
92
+ # Fungsi utama
93
  def main():
94
  global index # Agar index bisa diperbarui secara global
 
 
95
 
96
  print("πŸ”„ Inisialisasi index pertama kali...")
97
  update_index()
 
102
  launch_gradio()
103
 
104
  if __name__ == "__main__":
105
+ main()