BramLeo commited on
Commit
9cfd8ad
Β·
verified Β·
1 Parent(s): 9b34bdd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -15
app.py CHANGED
@@ -2,6 +2,7 @@ import gradio as gr
2
  import gdown
3
  import pandas as pd
4
  import os
 
5
  import threading
6
  import schedule
7
  import time
@@ -17,7 +18,7 @@ from llama_index.core.node_parser import SentenceSplitter
17
  # Fungsi untuk mengunduh model Llama
18
  def initialize_llama_model():
19
  model_path = hf_hub_download(
20
- repo_id="TheBLoke/zephyr-7b-beta-GGUF",
21
  filename="zephyr-7b-beta.Q4_K_M.gguf",
22
  cache_dir="./models"
23
  )
@@ -32,25 +33,43 @@ def initialize_settings(model_path):
32
 
33
  # Fungsi untuk mengunduh file CSV terbaru dari Google Drive
34
  def download_csv_from_drive():
35
- csv_url = "https://drive.google.com/uc?id=1UIx369_8GlzPiKArMVg8v-IwC6hYTYA0" # Ganti dengan ID file Google Drive kamu
36
  output_csv = "bahandokumen/data.csv"
37
 
38
  if os.path.exists(output_csv):
39
  os.remove(output_csv) # Hapus file lama
40
 
41
  print("πŸ”„ Mengunduh file CSV terbaru...")
42
- gdown.download(csv_url, output_csv, quiet=False)
 
 
 
 
 
 
 
 
43
  return output_csv
44
 
45
- # Fungsi untuk update index (dijalankan 1x sehari)
 
 
 
 
 
 
 
 
 
 
 
46
  def update_index():
47
  print(f"πŸ”„ [{datetime.now()}] Mengupdate index dengan data terbaru...")
48
  csv_file = download_csv_from_drive()
49
-
 
50
  # Baca CSV dengan Pandas
51
  df = pd.read_csv(csv_file)
52
-
53
- # Konversi isi CSV menjadi dokumen teks
54
  documents = [Document(text=" | ".join(map(str, row.values))) for _, row in df.iterrows()]
55
 
56
  # Tambahkan file dokumen lain
@@ -65,16 +84,12 @@ def update_index():
65
  ]).load_data()
66
 
67
  documents.extend(text_documents)
68
-
69
- # Parsing dokumen menjadi nodes
70
  parser = SentenceSplitter(chunk_size=150, chunk_overlap=10)
71
  nodes = parser.get_nodes_from_documents(documents)
72
 
73
- # Gunakan model embedding
74
  embedding = HuggingFaceEmbedding("firqaaa/indo-sentence-bert-base")
75
  Settings.embed_model = embedding
76
 
77
- # Buat index vektor
78
  global index
79
  index = VectorStoreIndex(nodes)
80
  print("βœ… Index berhasil diperbarui!")
@@ -85,7 +100,7 @@ def initialize_chat_engine():
85
 
86
  # Fungsi untuk menghasilkan respons chatbot
87
  def generate_response(message, history):
88
- chat_engine = initialize_chat_engine() # Gunakan index yang sudah diperbarui
89
  response = chat_engine.stream_chat(message)
90
  text = "".join(response.response_gen)
91
  history.append((message, text))
@@ -117,12 +132,12 @@ def main():
117
  initialize_settings(model_path)
118
 
119
  print("πŸ”„ Inisialisasi index pertama kali...")
120
- update_index() # Buat index pertama kali
121
 
122
  print("⏳ Menjalankan scheduler update index (setiap jam 12 malam)...")
123
- start_scheduler() # Jalankan update otomatis di background
124
 
125
- launch_gradio() # Jalankan chatbot
126
 
127
  if __name__ == "__main__":
128
  main()
 
2
  import gdown
3
  import pandas as pd
4
  import os
5
+ import shutil
6
  import threading
7
  import schedule
8
  import time
 
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
  )
 
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_csv = "bahandokumen/data.csv"
38
 
39
  if os.path.exists(output_csv):
40
  os.remove(output_csv) # Hapus file lama
41
 
42
  print("πŸ”„ Mengunduh file CSV terbaru...")
43
+ try:
44
+ gdown.download(csv_url, output_csv, quiet=False)
45
+ if os.path.exists(output_csv):
46
+ print(f"βœ… File berhasil diunduh: {output_csv}")
47
+ else:
48
+ print("❌ Gagal mengunduh file. Cek kembali link Google Drive.")
49
+ except Exception as e:
50
+ print(f"❌ Terjadi kesalahan saat mengunduh file: {e}")
51
+
52
  return output_csv
53
 
54
+ # Fungsi untuk menyimpan file ke Hugging Face Spaces
55
+ def save_to_huggingface():
56
+ src = "bahandokumen/data.csv"
57
+ dst = "/home/user/app/bahandokumen/data.csv" # Jalur sesuai dengan HF Spaces
58
+
59
+ if os.path.exists(src):
60
+ shutil.copy(src, dst)
61
+ print(f"βœ… File {src} berhasil disalin ke {dst}")
62
+ else:
63
+ print("❌ File tidak ditemukan, pastikan berhasil diunduh.")
64
+
65
+ # Fungsi untuk update index chatbot
66
  def update_index():
67
  print(f"πŸ”„ [{datetime.now()}] Mengupdate index dengan data terbaru...")
68
  csv_file = download_csv_from_drive()
69
+ save_to_huggingface()
70
+
71
  # Baca CSV dengan Pandas
72
  df = pd.read_csv(csv_file)
 
 
73
  documents = [Document(text=" | ".join(map(str, row.values))) for _, row in df.iterrows()]
74
 
75
  # Tambahkan file dokumen lain
 
84
  ]).load_data()
85
 
86
  documents.extend(text_documents)
 
 
87
  parser = SentenceSplitter(chunk_size=150, chunk_overlap=10)
88
  nodes = parser.get_nodes_from_documents(documents)
89
 
 
90
  embedding = HuggingFaceEmbedding("firqaaa/indo-sentence-bert-base")
91
  Settings.embed_model = embedding
92
 
 
93
  global index
94
  index = VectorStoreIndex(nodes)
95
  print("βœ… Index berhasil diperbarui!")
 
100
 
101
  # Fungsi untuk menghasilkan respons chatbot
102
  def generate_response(message, history):
103
+ chat_engine = initialize_chat_engine()
104
  response = chat_engine.stream_chat(message)
105
  text = "".join(response.response_gen)
106
  history.append((message, text))
 
132
  initialize_settings(model_path)
133
 
134
  print("πŸ”„ Inisialisasi index pertama kali...")
135
+ update_index()
136
 
137
  print("⏳ Menjalankan scheduler update index (setiap jam 12 malam)...")
138
+ start_scheduler()
139
 
140
+ launch_gradio()
141
 
142
  if __name__ == "__main__":
143
  main()