chouchouvs commited on
Commit
2624013
·
verified ·
1 Parent(s): 33cc09c

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +26 -13
main.py CHANGED
@@ -3,10 +3,13 @@
3
  HF Space - Remote Indexer (No-Qdrant)
4
  Stockage & recherche vectorielle avec 🤗 datasets + FAISS (local), UI Gradio.
5
 
6
- Améliorations:
7
- - Découpage "fail-safe": si aucun chunk, on prend 1 chunk = tout le texte.
8
- - Logs détaillés: taille par fichier, nb chunks par fichier.
9
- - UI: bouton "Indexer depuis textarea" pour tester avec 2 gros textes injectés depuis l'UI.
 
 
 
10
 
11
  ENV:
12
  - EMB_PROVIDER ("hf" | "dummy", défaut "hf")
@@ -278,7 +281,8 @@ async def build_dataset_with_faiss(job: JobState, req: IndexRequest) -> None:
278
  """
279
  Construit un dataset HuggingFace avec colonnes:
280
  - path (str), text (str), chunk (int), start (int), end (int), embedding (float32[])
281
- Ajoute un index FAISS (Inner Product) et persiste sur disque.
 
282
  """
283
  try:
284
  job.stage = "embedding"
@@ -358,24 +362,28 @@ async def build_dataset_with_faiss(job: JobState, req: IndexRequest) -> None:
358
  features=features,
359
  )
360
 
361
- # Index FAISS (Inner Product ≈ cosine après normalisation)
 
 
 
 
 
 
 
362
  job.stage = "indexing"
363
  ds.add_faiss_index(column="embedding", metric_type=faiss.METRIC_INNER_PRODUCT)
364
  job.indexed = ds.num_rows
365
  job.log(f"FAISS index ajouté ({ds.num_rows} points)")
366
-
367
- # Persistance
368
- p = project_paths(req.project_id)
369
- os.makedirs(p["faiss_dir"], exist_ok=True)
370
- ds.save_to_disk(p["ds_dir"])
371
  ds.save_faiss_index("embedding", p["faiss_file"])
372
- save_meta(p["meta_file"], {"dim": vec_dim, "rows": ds.num_rows, "model": HF_EMBED_MODEL, "ts": time.time()})
373
 
 
 
374
  DATASETS[req.project_id] = (ds, vec_dim)
375
 
376
  job.stage = "done"
377
  job.finished_at = time.time()
378
- job.log(f"Dataset sauvegardé dans {p['ds_dir']}, index FAISS → {p['faiss_file']}")
379
  except Exception as e:
380
  job.stage = "failed"
381
  job.errors.append(str(e))
@@ -406,6 +414,10 @@ def create_and_start_job(req: IndexRequest) -> JobState:
406
  # Chargement / Query helpers
407
  # ------------------------------------------------------------------------------
408
  def ensure_loaded(project_id: str) -> Tuple[Dataset, int]:
 
 
 
 
409
  if project_id in DATASETS:
410
  return DATASETS[project_id]
411
  p = project_paths(project_id)
@@ -509,6 +521,7 @@ async def export_hub(project_id: str = Query(..., min_length=1), repo_id: Option
509
  except Exception:
510
  pass
511
 
 
512
  buf = io.BytesIO()
513
  base_dir = p["base"]
514
  zip_name = f"{project_id}_vectors.zip"
 
3
  HF Space - Remote Indexer (No-Qdrant)
4
  Stockage & recherche vectorielle avec 🤗 datasets + FAISS (local), UI Gradio.
5
 
6
+ Améliorations clés de cette version :
7
+ - ✅ Sauvegarde d'abord le dataset SANS index -> save_to_disk()
8
+ - ✅ Puis ajoute FAISS et sauvegarde l'index séparément -> save_faiss_index()
9
+ - ✅ L'index reste chargé en mémoire pour la session courante
10
+ - ✅ Découpage "fail-safe" (au moins 1 chunk si texte non vide)
11
+ - ✅ Logs détaillés par fichier et par étape
12
+ - ✅ UI: bouton "Indexer depuis textarea" pour tester facilement
13
 
14
  ENV:
15
  - EMB_PROVIDER ("hf" | "dummy", défaut "hf")
 
281
  """
282
  Construit un dataset HuggingFace avec colonnes:
283
  - path (str), text (str), chunk (int), start (int), end (int), embedding (float32[])
284
+ Sauvegarde le dataset SANS index (save_to_disk), puis crée un index FAISS
285
+ et l'écrit séparément (save_faiss_index). En mémoire, on garde l'index chargé.
286
  """
287
  try:
288
  job.stage = "embedding"
 
362
  features=features,
363
  )
364
 
365
+ # *** IMPORTANT ***
366
+ # 1) Sauvegarder le dataset SANS index (sinon save_to_disk lève une exception)
367
+ p = project_paths(req.project_id)
368
+ os.makedirs(p["faiss_dir"], exist_ok=True)
369
+ ds.save_to_disk(p["ds_dir"])
370
+ job.log(f"Dataset (sans index) sauvegardé dans {p['ds_dir']}")
371
+
372
+ # 2) Ajouter l'index FAISS en mémoire, puis le sauvegarder séparément
373
  job.stage = "indexing"
374
  ds.add_faiss_index(column="embedding", metric_type=faiss.METRIC_INNER_PRODUCT)
375
  job.indexed = ds.num_rows
376
  job.log(f"FAISS index ajouté ({ds.num_rows} points)")
 
 
 
 
 
377
  ds.save_faiss_index("embedding", p["faiss_file"])
378
+ job.log(f"FAISS écrit sur {p['faiss_file']}")
379
 
380
+ # 3) Métadonnées + cache mémoire (garde l'index attaché pour cette session)
381
+ save_meta(p["meta_file"], {"dim": vec_dim, "rows": ds.num_rows, "model": HF_EMBED_MODEL, "ts": time.time()})
382
  DATASETS[req.project_id] = (ds, vec_dim)
383
 
384
  job.stage = "done"
385
  job.finished_at = time.time()
386
+ job.log(f"OK — dataset+index prêts (projet={req.project_id})")
387
  except Exception as e:
388
  job.stage = "failed"
389
  job.errors.append(str(e))
 
414
  # Chargement / Query helpers
415
  # ------------------------------------------------------------------------------
416
  def ensure_loaded(project_id: str) -> Tuple[Dataset, int]:
417
+ """
418
+ Charge ou recharge le dataset et l'index FAISS depuis disque si nécessaire.
419
+ - Le dataset sur disque n'a pas d'index (par design), on recharge FAISS via .load_faiss_index().
420
+ """
421
  if project_id in DATASETS:
422
  return DATASETS[project_id]
423
  p = project_paths(project_id)
 
521
  except Exception:
522
  pass
523
 
524
+ # Zip du dossier projet
525
  buf = io.BytesIO()
526
  base_dir = p["base"]
527
  zip_name = f"{project_id}_vectors.zip"