Update index.py
This commit is contained in:
parent
50042f6655
commit
3dc85bd99b
26
index.py
26
index.py
@ -9,9 +9,8 @@ Indexation incrémentale des fiches avec BGE‑M3 (FlagEmbedding) + FAISS
|
||||
• Les embeddings sont ajoutés à l'index existant sans toucher aux anciens.
|
||||
• Écrit/Met à jour : corpus.idx (vecteurs) + corpus.meta.json (métadonnées)
|
||||
|
||||
Temps gagné : pour 1 fiche ajoutée, seules ses quelques dizaines de passages
|
||||
sont ré-encodés, pas les ~6 000 déjà en place ➜ ré‑indexation en quelques
|
||||
secondes au lieu de minutes.
|
||||
➡ Robustesse améliorée : le script détecte tous les formats de retour possibles
|
||||
de `BGEM3FlagModel.encode` (ndarray ou dict avec clef `embedding`, etc.).
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
@ -37,7 +36,7 @@ BATCH = 128 # plus grand batch : encode plus
|
||||
|
||||
def split(text: str, chunk_size: int = CHUNK, overlap: int = OVERLAP):
|
||||
"""Découpe un texte en morceaux de chunk_size mots avec overlap mots."""
|
||||
sentences = re.split(r"(?<=[\.\!\?])\s+", text)
|
||||
sentences = re.split(r"(?<=[\.!?])\s+", text)
|
||||
chunks, buf = [], []
|
||||
for s in sentences:
|
||||
buf.append(s)
|
||||
@ -53,7 +52,6 @@ def gather_files(root: Path):
|
||||
for pattern in EXTENSIONS:
|
||||
yield from root.rglob(pattern)
|
||||
|
||||
|
||||
# --- Chargement éventuel de l'index existant -------------------------------
|
||||
|
||||
def load_existing():
|
||||
@ -64,7 +62,6 @@ def load_existing():
|
||||
meta = json.load(open(META_FILE, encoding="utf-8"))
|
||||
return index, meta, len(meta)
|
||||
|
||||
|
||||
# --- Pipeline principal -----------------------------------------------------
|
||||
|
||||
def main():
|
||||
@ -99,8 +96,20 @@ def main():
|
||||
|
||||
model = BGEM3FlagModel(MODEL_NAME, device="cpu")
|
||||
emb_out = model.encode(new_docs, batch_size=BATCH)
|
||||
# FlagEmbedding renvoie soit un ndarray, soit un dict {"embedding": …}
|
||||
emb = emb_out["embedding"] if isinstance(emb_out, dict) else emb_out
|
||||
|
||||
# --- Gestion robuste du format de sortie --------------------------------
|
||||
if isinstance(emb_out, np.ndarray):
|
||||
emb = emb_out
|
||||
elif isinstance(emb_out, dict):
|
||||
for key in ("embedding", "embeddings", "sentence_embeds", "sentence_embedding"):
|
||||
if key in emb_out:
|
||||
emb = np.asarray(emb_out[key])
|
||||
break
|
||||
else:
|
||||
emb = np.asarray(next(iter(emb_out.values())))
|
||||
else: # liste de tableaux ?
|
||||
emb = np.asarray(emb_out)
|
||||
|
||||
emb = emb.astype("float32")
|
||||
emb /= np.linalg.norm(emb, axis=1, keepdims=True) + 1e-12
|
||||
|
||||
@ -118,7 +127,6 @@ def main():
|
||||
f"+{len(new_docs)}). Dernière maj : {datetime.now().isoformat(timespec='seconds')}"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
t0 = time.time()
|
||||
main()
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user