Spaces:
Sleeping
Sleeping
Delete script/rep.py
Browse files- script/rep.py +0 -216
script/rep.py
DELETED
|
@@ -1,216 +0,0 @@
|
|
| 1 |
-
##############################################################################################
|
| 2 |
-
### Script de création de la base de données FAISS des articles
|
| 3 |
-
###
|
| 4 |
-
### Ce script
|
| 5 |
-
### - charge la table articles depuis le dataset HF Loren/articles_database
|
| 6 |
-
### - la traite par batch :
|
| 7 |
-
### - création de chunks de texte
|
| 8 |
-
### - création des embeddings avec le modèle SentenceTransformer "intfloat/e5-small"
|
| 9 |
-
### - ajout des embeddings dans un index FAISS
|
| 10 |
-
### - sauvegarde des métadonnées des chunks dans un fichier parquet
|
| 11 |
-
### - sauvegarde de l'index FAISS dans un fichier faiss_index.bin
|
| 12 |
-
### - upload dans le dataset HF Loren/articles_faiss
|
| 13 |
-
###
|
| 14 |
-
### 👉 L'index Faiss peut alors être utilisé par un space Hugging Face
|
| 15 |
-
##############################################################################################
|
| 16 |
-
|
| 17 |
-
import os
|
| 18 |
-
#import torch
|
| 19 |
-
import duckdb
|
| 20 |
-
from huggingface_hub import hf_hub_download, upload_file
|
| 21 |
-
from huggingface_hub import HfApi, HfFolder, CommitOperationAdd
|
| 22 |
-
#import faiss
|
| 23 |
-
#from sentence_transformers import SentenceTransformer
|
| 24 |
-
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 25 |
-
from functools import partial
|
| 26 |
-
import pyarrow as pa
|
| 27 |
-
import pyarrow.parquet as pq
|
| 28 |
-
from pathlib import Path
|
| 29 |
-
from dotenv import load_dotenv
|
| 30 |
-
|
| 31 |
-
# Fonctions
|
| 32 |
-
# Batch processing function
|
| 33 |
-
def batch_process(list_articles: list, faiss_id_start: int) -> int:
|
| 34 |
-
"""
|
| 35 |
-
Traite un batch d'articles pour générer des embeddings et des métadonnées,
|
| 36 |
-
puis les sauvegarde de manière sécurisée pour garantir la persistance en cas de problème.
|
| 37 |
-
|
| 38 |
-
Étapes réalisées :
|
| 39 |
-
1. Découpage de chaque article en chunks via le splitter.
|
| 40 |
-
2. Création d'un dictionnaire de métadonnées pour chaque chunk contenant :
|
| 41 |
-
- faiss_id : identifiant unique aligné avec l'index FAISS
|
| 42 |
-
- document_id : identifiant de l'article
|
| 43 |
-
- chunk_text : texte du chunk
|
| 44 |
-
3. Calcul des embeddings pour tous les chunks du batch.
|
| 45 |
-
4. Ajout des embeddings au FAISS index existant (append).
|
| 46 |
-
5. Écriture immédiate de l'index FAISS sur disque pour assurer la persistance.
|
| 47 |
-
6. Sauvegarde des métadonnées batch dans un fichier Parquet distinct.
|
| 48 |
-
|
| 49 |
-
Args:
|
| 50 |
-
list_articles (list): Liste de tuples (document_id, document_text) représentant les articles du batch.
|
| 51 |
-
faiss_id_start (int): Identifiant de départ pour le premier chunk du batch,
|
| 52 |
-
utilisé pour aligner FAISS et les métadonnées.
|
| 53 |
-
|
| 54 |
-
Returns:
|
| 55 |
-
int: Identifiant FAISS suivant, à utiliser pour le batch suivant afin de maintenir l'alignement.
|
| 56 |
-
|
| 57 |
-
Notes :
|
| 58 |
-
- Cette fonction est conçue pour être utilisée batch par batch.
|
| 59 |
-
- Les fichiers Parquet et le fichier FAISS sont mis à jour à chaque batch pour éviter toute perte de données.
|
| 60 |
-
"""
|
| 61 |
-
global faiss_index
|
| 62 |
-
|
| 63 |
-
try:
|
| 64 |
-
list_chunks = []
|
| 65 |
-
list_metadata = []
|
| 66 |
-
|
| 67 |
-
for doc_id, doc_content in list_articles:
|
| 68 |
-
chunks = splitter.split_text(doc_content)
|
| 69 |
-
for chunk_text in chunks:
|
| 70 |
-
list_chunks.append(chunk_text)
|
| 71 |
-
list_metadata.append({
|
| 72 |
-
"faiss_id": faiss_id_start,
|
| 73 |
-
"document_id": doc_id,
|
| 74 |
-
"chunk_text": chunk_text
|
| 75 |
-
})
|
| 76 |
-
faiss_id_start += 1
|
| 77 |
-
|
| 78 |
-
# Embeddings
|
| 79 |
-
#if list_chunks:
|
| 80 |
-
# embeddings = model.encode(list_chunks, convert_to_numpy=True, normalize_embeddings=True)
|
| 81 |
-
# faiss_index.add(embeddings)
|
| 82 |
-
# faiss.write_index(faiss_index, FAISS_INDEX_FILE)
|
| 83 |
-
|
| 84 |
-
# Sauvegarde batch métadonnées en Parquet
|
| 85 |
-
if list_metadata:
|
| 86 |
-
table = pa.Table.from_pylist(list_metadata)
|
| 87 |
-
batch_file = PARQUET_DIR / f"metadata_batch_{faiss_id_start}.parquet"
|
| 88 |
-
pq.write_table(table, batch_file)
|
| 89 |
-
|
| 90 |
-
return faiss_id_start
|
| 91 |
-
except Exception as e:
|
| 92 |
-
print(f"ERROR in batch_process function : {e}")
|
| 93 |
-
return None
|
| 94 |
-
##
|
| 95 |
-
|
| 96 |
-
# Initialisations
|
| 97 |
-
global faiss_index
|
| 98 |
-
print("Initialisations ...")
|
| 99 |
-
load_dotenv()
|
| 100 |
-
HF_TOKEN = os.getenv('API_HF_TOKEN')
|
| 101 |
-
REPO_ID = "Loren/articles_database"
|
| 102 |
-
DATA_DIR = Path("../../Data") # dossier parent du script
|
| 103 |
-
CHUNK_SIZE = 250
|
| 104 |
-
CHUNK_OVERLAP = 50
|
| 105 |
-
BATCH_SIZE = 1000
|
| 106 |
-
MODEL_NAME = "intfloat/e5-small"
|
| 107 |
-
FAISS_INDEX_FILE = DATA_DIR / "faiss_index.bin"
|
| 108 |
-
PARQUET_DIR = DATA_DIR / "parquet_metadata"
|
| 109 |
-
|
| 110 |
-
CACHE_DIR = "/tmp"
|
| 111 |
-
os.makedirs(CACHE_DIR, exist_ok=True)
|
| 112 |
-
# Rediriger le cache HF globalement
|
| 113 |
-
os.environ["HF_HOME"] = CACHE_DIR
|
| 114 |
-
os.environ["HF_DATASETS_CACHE"] = CACHE_DIR
|
| 115 |
-
os.environ["TRANSFORMERS_CACHE"] = CACHE_DIR
|
| 116 |
-
|
| 117 |
-
# Téléchargement des fichiers Parquet depuis Hugging Face
|
| 118 |
-
print("Téléchargement des fichiers Parquet depuis Hugging Face ...")
|
| 119 |
-
articles_parquet = hf_hub_download(
|
| 120 |
-
repo_id=REPO_ID,
|
| 121 |
-
filename="articles.parquet",
|
| 122 |
-
repo_type="dataset",
|
| 123 |
-
cache_dir=CACHE_DIR)
|
| 124 |
-
|
| 125 |
-
# Connexion DuckDB en mémoire
|
| 126 |
-
con = duckdb.connect()
|
| 127 |
-
|
| 128 |
-
# Créer des tables DuckDB directement à partir des fichiers Parquet
|
| 129 |
-
print("Création des vues DuckDB à partir des fichiers Parquet ...")
|
| 130 |
-
con.execute(f"CREATE VIEW articles AS SELECT * FROM parquet_scan('{articles_parquet}')")
|
| 131 |
-
|
| 132 |
-
# Creating the plitter for chunking document
|
| 133 |
-
splitter = RecursiveCharacterTextSplitter(
|
| 134 |
-
chunk_size=CHUNK_SIZE,
|
| 135 |
-
chunk_overlap=CHUNK_OVERLAP,
|
| 136 |
-
keep_separator='end',
|
| 137 |
-
separators=["\n\n", "\n", "."]
|
| 138 |
-
)
|
| 139 |
-
|
| 140 |
-
# Creating the Sentence transformer model
|
| 141 |
-
#device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 142 |
-
#print(f"*** Device: {device}")
|
| 143 |
-
#model = SentenceTransformer(MODEL_NAME, device=device)
|
| 144 |
-
#
|
| 145 |
-
## Creating the Faiss index
|
| 146 |
-
#embedding_dim = model.get_sentence_embedding_dimension()
|
| 147 |
-
#faiss_index = faiss.IndexFlatIP(embedding_dim)
|
| 148 |
-
faiss_id_counter = 0 # compteur global pour lier faiss_id et métadonnées
|
| 149 |
-
|
| 150 |
-
# Traitement par batchs
|
| 151 |
-
print("Création des batches et traitement ...")
|
| 152 |
-
cursor = con.execute("""
|
| 153 |
-
SELECT article_id, article_text
|
| 154 |
-
FROM articles
|
| 155 |
-
WHERE (LENGTH(article_text) - LENGTH(REPLACE(article_text, ' ', '')) + 1) >= 100""")
|
| 156 |
-
|
| 157 |
-
# Création d'un itérateur de batches
|
| 158 |
-
fetch_batch = partial(cursor.fetchmany, BATCH_SIZE)
|
| 159 |
-
|
| 160 |
-
for batch_num, batch in enumerate(iter(fetch_batch, []), start=1):
|
| 161 |
-
print("Traitement batch no ", batch_num, " ...")
|
| 162 |
-
faiss_id_counter = batch_process(batch, faiss_id_counter)
|
| 163 |
-
if not faiss_id_counter:
|
| 164 |
-
print("*** Erreur traitement batch no ", batch_num)
|
| 165 |
-
|
| 166 |
-
print("\n✅ Traitement terminé")
|
| 167 |
-
|
| 168 |
-
# Upload des fichiers vers HF
|
| 169 |
-
# Création du dataset HF
|
| 170 |
-
REPO_ID = "Loren/articles_faiss"
|
| 171 |
-
api = HfApi()
|
| 172 |
-
HfFolder.save_token(HF_TOKEN)
|
| 173 |
-
|
| 174 |
-
# Créer repo si besoin
|
| 175 |
-
api.create_repo(repo_id=REPO_ID, repo_type="dataset", exist_ok=True, private=True)
|
| 176 |
-
|
| 177 |
-
# Récupérer la liste de fichiers parquet
|
| 178 |
-
print("Upload des fichiers metadatas dans le dataset hugging face ", REPO_ID, " ...")
|
| 179 |
-
parquet_files = [
|
| 180 |
-
os.path.join(PARQUET_DIR, f)
|
| 181 |
-
for f in os.listdir(PARQUET_DIR)
|
| 182 |
-
if f.endswith(".parquet")
|
| 183 |
-
]
|
| 184 |
-
|
| 185 |
-
# Ajouter tous les fichiers
|
| 186 |
-
operations = [
|
| 187 |
-
CommitOperationAdd(
|
| 188 |
-
path_in_repo=f"data/{os.path.basename(f)}",
|
| 189 |
-
path_or_fileobj=f
|
| 190 |
-
)
|
| 191 |
-
for f in parquet_files
|
| 192 |
-
]
|
| 193 |
-
|
| 194 |
-
api.create_commit(
|
| 195 |
-
repo_id=REPO_ID,
|
| 196 |
-
repo_type="dataset",
|
| 197 |
-
operations=operations,
|
| 198 |
-
commit_message="Upload batch metadata parquet files"
|
| 199 |
-
)
|
| 200 |
-
|
| 201 |
-
print("✅ Upload metadatas terminé !")
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
print("Upload de l'index Faiss dans le dataset hugging face ", REPO_ID, " ...")
|
| 205 |
-
upload_file(
|
| 206 |
-
path_or_fileobj=FAISS_INDEX_FILE,
|
| 207 |
-
path_in_repo=FAISS_INDEX_FILE.name,
|
| 208 |
-
repo_id=REPO_ID,
|
| 209 |
-
repo_type="dataset",
|
| 210 |
-
token=HF_TOKEN
|
| 211 |
-
)
|
| 212 |
-
|
| 213 |
-
print("✅ Upload faiss index terminé")
|
| 214 |
-
|
| 215 |
-
con.close()
|
| 216 |
-
print("✅ Traitement terminé")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|