Spaces:
Sleeping
Sleeping
File size: 5,354 Bytes
eff6ee6 | 1 2 3 4 5 6 7 8 9 10 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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | from pathlib import Path
from dataclasses import dataclass
from typing import List
import re
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
@dataclass
class RetrievedChunk:
text: str
filename: str
score: float
class RAGEngineGPT2:
def __init__(
self,
corpus_dir: str = "corpus/",
chunk_size: int = 450,
chunk_overlap: int = 80,
min_score: float = 0.05
):
self.corpus_dir = Path(corpus_dir)
self.chunk_size = chunk_size
self.chunk_overlap = chunk_overlap
self.min_score = min_score
self.chunks: List[str] = []
self.chunk_sources: List[str] = []
self.vectorizer = TfidfVectorizer(
lowercase=True,
strip_accents="unicode",
ngram_range=(1, 2),
max_features=10000
)
self._load_and_chunk_corpus()
self._index()
def _clean_text(self, text: str) -> str:
text = re.sub(r"\s+", " ", text)
return text.strip()
def _clean_for_prompt(self, text: str) -> str:
text = re.sub(r"\[[A-ZÉÈÊÀÙÎÏÇ _-]+\]", "", text)
text = re.sub(r"\s+", " ", text)
return text.strip()
def _split_into_chunks(self, text: str) -> List[str]:
text = self._clean_text(text)
if len(text) <= self.chunk_size:
return [text]
chunks = []
start = 0
while start < len(text):
end = start + self.chunk_size
chunk = text[start:end].strip()
if chunk:
chunks.append(chunk)
start += self.chunk_size - self.chunk_overlap
return chunks
def _load_and_chunk_corpus(self):
if not self.corpus_dir.exists():
raise FileNotFoundError(f"Dossier corpus introuvable : {self.corpus_dir}")
files = sorted(
list(self.corpus_dir.glob("*.txt")) +
list(self.corpus_dir.glob("*.md"))
)
if not files:
raise ValueError("Aucun fichier .txt ou .md trouvé dans le dossier corpus.")
for file_path in files:
try:
text = file_path.read_text(encoding="utf-8")
chunks = self._split_into_chunks(text)
for chunk in chunks:
self.chunks.append(chunk)
self.chunk_sources.append(file_path.name)
except Exception as e:
print(f"Fichier ignoré : {file_path.name} | Erreur : {e}")
if not self.chunks:
raise ValueError("Aucun passage exploitable trouvé dans le corpus.")
print(f"{len(files)} fichiers chargés.")
print(f"{len(self.chunks)} passages indexés.")
def _index(self):
self.tfidf_matrix = self.vectorizer.fit_transform(self.chunks)
def _apply_domain_boost(self, query: str, scores):
query_lower = query.lower()
for i in range(len(scores)):
filename = self.chunk_sources[i].lower()
if ("médecine" in query_lower or "medecine" in query_lower or "santé" in query_lower) and "ia_medecine" in filename:
scores[i] += 0.08
if ("finance" in query_lower or "banque" in query_lower or "crédit" in query_lower or "credit" in query_lower) and "ia_finance" in filename:
scores[i] += 0.08
if ("recrutement" in query_lower or "rh" in query_lower) and "ia_rh" in filename:
scores[i] += 0.08
if ("éducation" in query_lower or "education" in query_lower or "école" in query_lower or "ecole" in query_lower or "élève" in query_lower or "eleve" in query_lower) and "ia_education" in filename:
scores[i] += 0.08
if ("cybersécurité" in query_lower or "cybersecurite" in query_lower or "cyber" in query_lower) and "ia_cybersecurite" in filename:
scores[i] += 0.08
if ("art" in query_lower or "image" in query_lower or "création" in query_lower or "creation" in query_lower) and "ia_art" in filename:
scores[i] += 0.08
return scores
def search(self, query: str, top_k: int = 1) -> List[RetrievedChunk]:
query = self._clean_text(query)
if not query:
return []
q_vec = self.vectorizer.transform([query])
scores = cosine_similarity(q_vec, self.tfidf_matrix)[0]
scores = self._apply_domain_boost(query, scores)
top_idx = np.argsort(scores)[::-1][:top_k]
results = []
for i in top_idx:
score = float(scores[i])
if score >= self.min_score:
results.append(
RetrievedChunk(
text=self.chunks[i],
filename=self.chunk_sources[i],
score=score
)
)
return results
def build_prompt(self, query: str, top_k: int = 1) -> str:
results = self.search(query, top_k=top_k)
if not results:
return ""
context = "\n\n".join(
[self._clean_for_prompt(result.text) for result in results]
)
return f"""
Contexte :
{context}
Question :
{query}
Réponse en français :
""" |