Update ingest.py
Browse files
ingest.py
CHANGED
|
@@ -1,39 +1,63 @@
|
|
| 1 |
-
# ingest.py
|
| 2 |
-
import json
|
| 3 |
-
import os
|
| 4 |
-
import time
|
| 5 |
-
|
| 6 |
-
from
|
| 7 |
-
|
| 8 |
-
from
|
| 9 |
-
|
| 10 |
-
def
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ingest.py
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import time
|
| 5 |
+
import requests
|
| 6 |
+
from bs4 import BeautifulSoup
|
| 7 |
+
import chromadb
|
| 8 |
+
from chromadb.utils import embedding_functions
|
| 9 |
+
|
| 10 |
+
def simple_extract_text(url: str) -> str:
|
| 11 |
+
"""Extrait le texte propre d'une page web."""
|
| 12 |
+
try:
|
| 13 |
+
headers = {'User-Agent': 'CyberWise Assistant (educational bot)'}
|
| 14 |
+
response = requests.get(url, headers=headers, timeout=15)
|
| 15 |
+
response.raise_for_status()
|
| 16 |
+
soup = BeautifulSoup(response.content, 'html.parser')
|
| 17 |
+
for script in soup(["script", "style", "nav", "footer", "header", "noscript"]):
|
| 18 |
+
script.decompose()
|
| 19 |
+
text = soup.get_text(separator=' ', strip=True)
|
| 20 |
+
return ' '.join(text.split())
|
| 21 |
+
except Exception as e:
|
| 22 |
+
print(f" ❌ Échec extraction {url}: {e}")
|
| 23 |
+
return ""
|
| 24 |
+
|
| 25 |
+
def run_ingest(persist_directory="./chroma_db"):
|
| 26 |
+
if os.path.exists(persist_directory):
|
| 27 |
+
print("✅ Base vectorielle déjà présente.")
|
| 28 |
+
return
|
| 29 |
+
|
| 30 |
+
print("🔍 Indexation des sources de confiance...")
|
| 31 |
+
with open("trusted_sources.json", "r", encoding="utf-8") as f:
|
| 32 |
+
sources = json.load(f)
|
| 33 |
+
|
| 34 |
+
embedding_function = embedding_functions.SentenceTransformerEmbeddingFunction(
|
| 35 |
+
model_name="all-MiniLM-L6-v2"
|
| 36 |
+
)
|
| 37 |
+
client = chromadb.PersistentClient(path=persist_directory)
|
| 38 |
+
collection = client.get_or_create_collection(
|
| 39 |
+
name="cyberwise",
|
| 40 |
+
embedding_function=embedding_function
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
documents = []
|
| 44 |
+
metadatas = []
|
| 45 |
+
ids = []
|
| 46 |
+
|
| 47 |
+
for i, src in enumerate(sources):
|
| 48 |
+
print(f" → {src['url']}")
|
| 49 |
+
text = simple_extract_text(src['url'])
|
| 50 |
+
if text and len(text) > 100:
|
| 51 |
+
# Découper en chunks de 500 caractères
|
| 52 |
+
chunks = [text[j:j+500] for j in range(0, len(text), 500)]
|
| 53 |
+
for k, chunk in enumerate(chunks):
|
| 54 |
+
documents.append(chunk)
|
| 55 |
+
metadatas.append({"source": src['url']})
|
| 56 |
+
ids.append(f"doc_{i}_{k}")
|
| 57 |
+
time.sleep(1)
|
| 58 |
+
|
| 59 |
+
if documents:
|
| 60 |
+
collection.add(documents=documents, metadatas=metadatas, ids=ids)
|
| 61 |
+
print(f"✅ {len(documents)} extraits indexés dans 'chroma_db'.")
|
| 62 |
+
else:
|
| 63 |
+
raise RuntimeError("Aucun texte valide n’a été extrait des sources.")
|