Matis Codjia commited on
Commit
3a00bdd
·
1 Parent(s): 6290fdd

Persist data

Browse files
Files changed (2) hide show
  1. app.py +48 -16
  2. cache_manager.py +1 -1
app.py CHANGED
@@ -19,7 +19,7 @@ from deepseek_caller import DeepSeekCaller
19
  from stats_logger import StatsLogger
20
  from config import DISTANCE_THRESHOLD
21
  from utils import load_css
22
- from huggingface_hub import login
23
  import os
24
 
25
  # ==========================================
@@ -32,6 +32,13 @@ st.set_page_config(
32
  initial_sidebar_state="expanded"
33
  )
34
 
 
 
 
 
 
 
 
35
  # ==========================================
36
  # CUSTOM CSS
37
  # ==========================================
@@ -130,24 +137,49 @@ def load_dataset_from_source(source: str, path: str):
130
  data.append(json.loads(line))
131
  return data
132
 
133
- def initialize_chromadb(force_reindex=False):
134
- db_path = Path("streamlit_rag_viewer/chroma_db_storage")
135
- db_path.mkdir(parents=True, exist_ok=True)
136
-
137
- client = chromadb.PersistentClient(path=str(db_path))
138
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
  try:
140
- if force_reindex:
141
- try: client.delete_collection("feedbacks")
142
- except: pass
143
- collection = client.create_collection(name="feedbacks", metadata={"hnsw:space": "cosine"})
144
- else:
145
- collection = client.get_collection(name="feedbacks")
146
- except:
147
- collection = client.create_collection(name="feedbacks", metadata={"hnsw:space": "cosine"})
148
 
149
  return client, collection
150
-
151
  # ==========================================
152
  # MAIN APP
153
  # ==========================================
 
19
  from stats_logger import StatsLogger
20
  from config import DISTANCE_THRESHOLD
21
  from utils import load_css
22
+ from huggingface_hub import login, snapshot_download
23
  import os
24
 
25
  # ==========================================
 
32
  initial_sidebar_state="expanded"
33
  )
34
 
35
+ DATASET_ID = "matis35/chroma-rag-storage"
36
+ REPO_FOLDER = "chroma_db_storage" # Le nom du dossier DANS le repo HF
37
+
38
+ # Le dossier local où Streamlit va stocker la DB
39
+ # On se met un niveau au-dessus pour que snapshot_download recrée le dossier "chroma_db_storage" dedans
40
+ LOCAL_CACHE_DIR = Path("./chroma_cache")
41
+
42
  # ==========================================
43
  # CUSTOM CSS
44
  # ==========================================
 
137
  data.append(json.loads(line))
138
  return data
139
 
140
+ # @st.cache_resource # <--- Décommenter si tu es sous Streamlit pour ne le faire qu'une fois !
141
+ def initialize_chromadb():
142
+ """
143
+ Mode Static RAG : Télécharge la DB depuis Hugging Face et se connecte en lecture seule.
144
+ """
145
+
146
+ # 1. CHEMIN CIBLE
147
+ # Le chemin final sera : ./chroma_cache/chroma_db_storage
148
+ final_db_path = LOCAL_CACHE_DIR / REPO_FOLDER
149
+
150
+ # 2. TÉLÉCHARGEMENT (Si pas déjà présent)
151
+ if not final_db_path.exists():
152
+ print(f"📥 Téléchargement de la base depuis {DATASET_ID}...")
153
+ try:
154
+ snapshot_download(
155
+ repo_id=DATASET_ID,
156
+ repo_type="dataset",
157
+ local_dir=LOCAL_CACHE_DIR, # On télécharge DANS le cache
158
+ allow_patterns=[f"{REPO_FOLDER}/*"], # On ne prend que le dossier DB
159
+ local_dir_use_symlinks=False,
160
+ # token=os.environ.get("HF_TOKEN") # Nécessaire si le dataset est PRIVÉ
161
+ )
162
+ print("Téléchargement terminé.")
163
+ except Exception as e:
164
+ print(f"❌ Erreur de téléchargement : {e}")
165
+ # Fallback : Si on est en local et que le dossier existe déjà ailleurs, on pourrait pointer dessus
166
+ raise e
167
+
168
+ # 3. CONNEXION CHROMA
169
+ # On pointe vers le dossier contenant le fichier sqlite3
170
+ client = chromadb.PersistentClient(path=str(final_db_path))
171
+
172
+ # 4. RÉCUPÉRATION DE LA COLLECTION
173
+ # Attention : On ne fait plus de "create_collection" ni de "delete".
174
+ # On récupère juste ce qui existe.
175
  try:
176
+ collection = client.get_collection(name="feedbacks")
177
+ print(f"📊 Collection chargée. {collection.count()} documents disponibles.")
178
+ except Exception as e:
179
+ print(f" Erreur : La collection 'feedbacks' n'existe pas dans la base téléchargée.")
180
+ raise e
 
 
 
181
 
182
  return client, collection
 
183
  # ==========================================
184
  # MAIN APP
185
  # ==========================================
cache_manager.py CHANGED
@@ -18,7 +18,7 @@ class CacheManager:
18
  """
19
  self.collection = chroma_collection
20
  self.encoder_fn = encoder_fn
21
- self.threshold = threshold if threshold is not None else SIMILARITY_THRESHOLD
22
 
23
  def calculate_confidence(self, distances: List[float]) -> float:
24
  """
 
18
  """
19
  self.collection = chroma_collection
20
  self.encoder_fn = encoder_fn
21
+ self.threshold = threshold if threshold is not None else DISTANCE_THRESHOLD
22
 
23
  def calculate_confidence(self, distances: List[float]) -> float:
24
  """