|
import gradio as gr |
|
from langchain_mistralai.chat_models import ChatMistralAI |
|
from langchain.prompts import ChatPromptTemplate |
|
from langchain_deepseek import ChatDeepSeek |
|
from langchain_google_genai import ChatGoogleGenerativeAI |
|
import os |
|
from pathlib import Path |
|
import json |
|
import faiss |
|
import numpy as np |
|
from langchain.schema import Document |
|
import pickle |
|
import re |
|
import requests |
|
from functools import lru_cache |
|
import torch |
|
from sentence_transformers import SentenceTransformer |
|
from sentence_transformers.cross_encoder import CrossEncoder |
|
import threading |
|
from queue import Queue |
|
import concurrent.futures |
|
from typing import Generator, Tuple, Iterator |
|
import time |
|
|
|
class OptimizedRAGLoader: |
|
def __init__(self, |
|
docs_folder: str = "./docs", |
|
splits_folder: str = "./splits", |
|
index_folder: str = "./index"): |
|
|
|
self.docs_folder = Path(docs_folder) |
|
self.splits_folder = Path(splits_folder) |
|
self.index_folder = Path(index_folder) |
|
|
|
|
|
for folder in [self.splits_folder, self.index_folder]: |
|
folder.mkdir(parents=True, exist_ok=True) |
|
|
|
|
|
self.splits_path = self.splits_folder / "splits.json" |
|
self.index_path = self.index_folder / "faiss.index" |
|
self.documents_path = self.index_folder / "documents.pkl" |
|
|
|
|
|
self.index = None |
|
self.indexed_documents = None |
|
|
|
|
|
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
|
self.encoder = SentenceTransformer("intfloat/multilingual-e5-large") |
|
self.encoder.to(self.device) |
|
self.reranker = model = CrossEncoder("cross-encoder/mmarco-mMiniLMv2-L12-H384-v1",trust_remote_code=True) |
|
|
|
|
|
self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=4) |
|
|
|
|
|
self.response_cache = {} |
|
|
|
@lru_cache(maxsize=1000) |
|
def encode(self, text: str): |
|
"""Cached encoding function""" |
|
with torch.no_grad(): |
|
embeddings = self.encoder.encode( |
|
text, |
|
convert_to_numpy=True, |
|
normalize_embeddings=True |
|
) |
|
return embeddings |
|
|
|
def batch_encode(self, texts: list): |
|
"""Batch encoding for multiple texts""" |
|
with torch.no_grad(): |
|
embeddings = self.encoder.encode( |
|
texts, |
|
batch_size=32, |
|
convert_to_numpy=True, |
|
normalize_embeddings=True, |
|
show_progress_bar=False |
|
) |
|
return embeddings |
|
|
|
def load_and_split_texts(self): |
|
if self._splits_exist(): |
|
return self._load_existing_splits() |
|
|
|
documents = [] |
|
futures = [] |
|
|
|
for file_path in self.docs_folder.glob("*.txt"): |
|
future = self.executor.submit(self._process_file, file_path) |
|
futures.append(future) |
|
|
|
for future in concurrent.futures.as_completed(futures): |
|
documents.extend(future.result()) |
|
|
|
self._save_splits(documents) |
|
return documents |
|
|
|
def _process_file(self, file_path): |
|
with open(file_path, 'r', encoding='utf-8') as file: |
|
text = file.read() |
|
chunks = [s.strip() for s in re.split(r'(?<=[.!?])\s+', text) if s.strip()] |
|
|
|
return [ |
|
Document( |
|
page_content=chunk, |
|
metadata={ |
|
'source': file_path.name, |
|
'chunk_id': i, |
|
'total_chunks': len(chunks) |
|
} |
|
) |
|
for i, chunk in enumerate(chunks) |
|
] |
|
|
|
def load_index(self) -> bool: |
|
""" |
|
Charge l'index FAISS et les documents associés s'ils existent |
|
|
|
Returns: |
|
bool: True si l'index a été chargé, False sinon |
|
""" |
|
if not self._index_exists(): |
|
print("Aucun index trouvé.") |
|
return False |
|
|
|
print("Chargement de l'index existant...") |
|
try: |
|
|
|
self.index = faiss.read_index(str(self.index_path)) |
|
|
|
|
|
with open(self.documents_path, 'rb') as f: |
|
self.indexed_documents = pickle.load(f) |
|
|
|
print(f"Index chargé avec {self.index.ntotal} vecteurs") |
|
return True |
|
|
|
except Exception as e: |
|
print(f"Erreur lors du chargement de l'index: {e}") |
|
return False |
|
|
|
def create_index(self, documents=None): |
|
if documents is None: |
|
documents = self.load_and_split_texts() |
|
|
|
if not documents: |
|
return False |
|
|
|
texts = [doc.page_content for doc in documents] |
|
embeddings = self.batch_encode(texts) |
|
|
|
dimension = embeddings.shape[1] |
|
self.index = faiss.IndexFlatL2(dimension) |
|
|
|
if torch.cuda.is_available(): |
|
|
|
res = faiss.StandardGpuResources() |
|
self.index = faiss.index_cpu_to_gpu(res, 0, self.index) |
|
|
|
self.index.add(np.array(embeddings).astype('float32')) |
|
self.indexed_documents = documents |
|
|
|
|
|
cpu_index = faiss.index_gpu_to_cpu(self.index) if torch.cuda.is_available() else self.index |
|
faiss.write_index(cpu_index, str(self.index_path)) |
|
|
|
with open(self.documents_path, 'wb') as f: |
|
pickle.dump(documents, f) |
|
|
|
return True |
|
|
|
def _index_exists(self) -> bool: |
|
"""Vérifie si l'index et les documents associés existent""" |
|
return self.index_path.exists() and self.documents_path.exists() |
|
|
|
def get_retriever(self, k: int = 10): |
|
if self.index is None: |
|
if not self.load_index(): |
|
if not self.create_index(): |
|
raise ValueError("Unable to load or create index") |
|
|
|
def retriever_function(query: str) -> list: |
|
|
|
cache_key = f"{query}_{k}" |
|
if cache_key in self.response_cache: |
|
return self.response_cache[cache_key] |
|
|
|
query_embedding = self.encode(query) |
|
|
|
distances, indices = self.index.search( |
|
np.array([query_embedding]).astype('float32'), |
|
k |
|
) |
|
|
|
results = [ |
|
self.indexed_documents[idx] |
|
for idx in indices[0] |
|
if idx != -1 |
|
] |
|
|
|
|
|
self.response_cache[cache_key] = results |
|
return results |
|
|
|
return retriever_function |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
from fastapi import FastAPI, Request, HTTPException |
|
from fastapi.responses import StreamingResponse, HTMLResponse |
|
from fastapi.staticfiles import StaticFiles |
|
from langchain_google_genai import ChatGoogleGenerativeAI |
|
import uvicorn |
|
import asyncio |
|
import os |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
rag_loader = None |
|
llm = None |
|
retriever = None |
|
prompt_template = None |
|
initialization_error = None |
|
|
|
|
|
print("--- Starting Application Initialization ---") |
|
try: |
|
|
|
print("Initializing LLM...") |
|
gemini_api_key = os.getenv("GEMINI_KEY") |
|
if not gemini_api_key: |
|
raise ValueError("GEMINI_KEY environment variable not set.") |
|
llm = ChatGoogleGenerativeAI( |
|
model="gemini-1.5-pro", |
|
temperature=0.1, |
|
google_api_key=gemini_api_key, |
|
disable_streaming=True, |
|
) |
|
print("LLM Initialized.") |
|
|
|
|
|
print("Initializing RAG Loader...") |
|
|
|
rag_loader = OptimizedRAGLoader() |
|
print("RAG Loader Initialized. Getting Retriever...") |
|
retriever = rag_loader.get_retriever(k=6) |
|
|
|
|
|
INSUFFICIENT_CONTEXT_FLAG = "CONTEXTE_INSUFFISANT" |
|
|
|
print("Retriever Initialized.") |
|
|
|
|
|
print("Initializing Prompt Template...") |
|
prompt_template = ChatPromptTemplate.from_messages([ |
|
("system", f"Tu es un assistant juridique spécialisé dans le droit marocain. " |
|
f"Évalue si tu peux répondre à la question de l'utilisateur EN UTILISANT UNIQUEMENT les documents suivants. " |
|
f"Si oui, réponds en detail à la question et exploiter toutes les informations du contexte en ajoutant la source de l'information sans extension MD. " |
|
f"repondre aux questions en divisant la reponse selon la source, chaque source a son propre titre et contenu. " |
|
f"enlever les marques de markdown (##) et mettre le titre en gras à la place. " |
|
f"Si non, réponds UNIQUEMENT avec le texte exact '{INSUFFICIENT_CONTEXT_FLAG}' et rien d'autre. "), |
|
("human", "Question: {question}\n\nDocuments Fournis:\n{context}") |
|
]) |
|
print("Prompt Template Initialized.") |
|
|
|
print("--- Application Initialization Successful ---") |
|
|
|
except Exception as e: |
|
print(f"!!!!!!!!!! FATAL INITIALIZATION ERROR !!!!!!!!!!") |
|
print(f"Error during startup: {e}") |
|
import traceback |
|
traceback.print_exc() |
|
initialization_error = str(e) |
|
|
|
|
|
|
|
app = FastAPI() |
|
|
|
|
|
|
|
|
|
async def get_llm_response_stream(question: str): |
|
|
|
if initialization_error: |
|
yield f"data: Erreur critique lors de l'initialisation du serveur: {initialization_error}\n\n" |
|
return |
|
if not retriever or not llm or not prompt_template: |
|
yield f"data: Erreur: Un ou plusieurs composants serveur (LLM, Retriever, Prompt) ne sont pas initialisés.\n\n" |
|
return |
|
|
|
|
|
print(f"API processing question: {question}") |
|
try: |
|
|
|
relevant_docs = retriever(question) |
|
|
|
|
|
formatted_docs = [] |
|
for doc in relevant_docs: |
|
source = doc.metadata.get("source", "Source inconnue") |
|
new_page_content = f"Source: {source}\n\n{doc.page_content}" |
|
|
|
formatted_docs.append(Document(page_content=new_page_content, metadata=doc.metadata)) |
|
|
|
context_str = [doc.page_content for doc in formatted_docs] |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if not relevant_docs: |
|
|
|
yield f"data: لم أتمكن من العثور على معلومات ذات صلة في المستندات.\n\n" |
|
|
|
return |
|
|
|
|
|
prompt = prompt_template.format_messages(context=context_str, question=question) |
|
|
|
full_response = "" |
|
|
|
stream = llm.stream(prompt) |
|
for chunk in stream: |
|
content = chunk.content if hasattr(chunk, 'content') else str(chunk) |
|
if content: |
|
formatted_chunk = content.replace('\n', '\ndata: ') |
|
yield f"data: {formatted_chunk}\n\n" |
|
full_response += content |
|
|
|
yield "event: end\ndata: Stream finished\n\n" |
|
|
|
except Exception as e: |
|
print(f"Error during API LLM generation: {e}") |
|
import traceback |
|
traceback.print_exc() |
|
yield f"data: حدث خطأ أثناء معالجة طلبك: {str(e)}\n\n" |
|
yield "event: error\ndata: Stream error\n\n" |
|
|
|
|
|
|
|
@app.post("/ask") |
|
async def handle_ask(request: Request): |
|
|
|
if initialization_error: |
|
raise HTTPException(status_code=500, detail=f"Erreur d'initialisation serveur: {initialization_error}") |
|
|
|
try: |
|
data = await request.json() |
|
question = data.get("question") |
|
if not question: |
|
raise HTTPException(status_code=400, detail="Question manquante dans la requête JSON") |
|
|
|
|
|
return StreamingResponse(get_llm_response_stream(question), media_type="text/event-stream") |
|
|
|
except Exception as e: |
|
print(f"Error in /ask endpoint: {e}") |
|
raise HTTPException(status_code=500, detail=f"Erreur interne du serveur: {str(e)}") |
|
|
|
|
|
|
|
|
|
app.mount("/", StaticFiles(directory="static", html=True), name="static") |
|
|
|
|
|
if __name__ == "__main__": |
|
uvicorn.run(app, host="0.0.0.0", port=7860) |
|
|