Update app.py
Browse files
app.py
CHANGED
|
@@ -1,112 +1,112 @@
|
|
| 1 |
-
# app.py
|
| 2 |
-
import
|
| 3 |
-
import
|
| 4 |
-
import
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
# Auto-indexation
|
| 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 |
-
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
import os
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import chromadb
|
| 5 |
+
from chromadb.utils import embedding_functions
|
| 6 |
+
|
| 7 |
+
# Auto-indexation si base absente
|
| 8 |
+
DB_PATH = "./chroma_db"
|
| 9 |
+
if not os.path.exists(DB_PATH):
|
| 10 |
+
print("🔍 Base de connaissances absente. Indexation en cours…")
|
| 11 |
+
from ingest import run_ingest
|
| 12 |
+
run_ingest(DB_PATH)
|
| 13 |
+
print("✅ Indexation terminée.")
|
| 14 |
+
|
| 15 |
+
# Charger la base vectorielle
|
| 16 |
+
client = chromadb.PersistentClient(path=DB_PATH)
|
| 17 |
+
embedding_function = embedding_functions.SentenceTransformerEmbeddingFunction(
|
| 18 |
+
model_name="all-MiniLM-L6-v2"
|
| 19 |
+
)
|
| 20 |
+
collection = client.get_collection(name="cyberwise", embedding_function=embedding_function)
|
| 21 |
+
|
| 22 |
+
# Fonction de récupération
|
| 23 |
+
def retrieve_context(query: str, k=3):
|
| 24 |
+
results = collection.query(query_texts=[query], n_results=k)
|
| 25 |
+
if not results['documents'][0]:
|
| 26 |
+
return "", []
|
| 27 |
+
docs = results['documents'][0]
|
| 28 |
+
metas = results['metadatas'][0]
|
| 29 |
+
sources = list(set(m['source'] for m in metas))
|
| 30 |
+
context = "\n\n".join(docs)
|
| 31 |
+
return context, sources
|
| 32 |
+
|
| 33 |
+
# Charger le LLM (Mistral-7B en 4-bit)
|
| 34 |
+
print("⏳ Chargement du modèle Mistral-7B...")
|
| 35 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline, BitsAndBytesConfig
|
| 36 |
+
import torch
|
| 37 |
+
|
| 38 |
+
use_gpu = torch.cuda.is_available()
|
| 39 |
+
bnb_config = BitsAndBytesConfig(
|
| 40 |
+
load_in_4bit=True,
|
| 41 |
+
bnb_4bit_quant_type="nf4",
|
| 42 |
+
bnb_4bit_compute_dtype=torch.float16 if use_gpu else torch.float32
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
model_name = "mistralai/Mistral-7B-Instruct-v0.3"
|
| 46 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 47 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 48 |
+
model_name,
|
| 49 |
+
quantization_config=bnb_config,
|
| 50 |
+
device_map="auto" if use_gpu else "cpu",
|
| 51 |
+
trust_remote_code=True
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
pipe = pipeline(
|
| 55 |
+
"text-generation",
|
| 56 |
+
model=model,
|
| 57 |
+
tokenizer=tokenizer,
|
| 58 |
+
max_new_tokens=512,
|
| 59 |
+
temperature=0.3,
|
| 60 |
+
top_p=0.95,
|
| 61 |
+
repetition_penalty=1.2,
|
| 62 |
+
device=0 if use_gpu else -1
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
def llm_generate(prompt: str) -> str:
|
| 66 |
+
response = pipe(prompt)
|
| 67 |
+
return response[0]["generated_text"].replace(prompt, "").strip()
|
| 68 |
+
|
| 69 |
+
# Chaîne RAG
|
| 70 |
+
def rag_chain(question: str):
|
| 71 |
+
context, sources = retrieve_context(question)
|
| 72 |
+
if not context.strip():
|
| 73 |
+
return "Je ne dispose pas d'informations fiables sur ce sujet dans mes sources officielles.", []
|
| 74 |
+
|
| 75 |
+
prompt = f"""
|
| 76 |
+
Tu es CyberWise, un assistant expert en cybersécurité, vie numérique responsable et analyse de logs.
|
| 77 |
+
Utilise UNIQUEMENT les informations ci-dessous pour répondre.
|
| 78 |
+
Si le sujet n'est pas couvert, dis exactement :
|
| 79 |
+
"Je ne dispose pas d'informations fiables sur ce sujet dans mes sources officielles."
|
| 80 |
+
|
| 81 |
+
Contexte :
|
| 82 |
+
{context}
|
| 83 |
+
|
| 84 |
+
Question : {question}
|
| 85 |
+
|
| 86 |
+
Réponse (claire, pédagogique, en français si la question est en français) :
|
| 87 |
+
""".strip()
|
| 88 |
+
|
| 89 |
+
response = llm_generate(prompt)
|
| 90 |
+
return response, sources
|
| 91 |
+
|
| 92 |
+
# Interface Gradio
|
| 93 |
+
def predict(message, history):
|
| 94 |
+
response, sources = rag_chain(message)
|
| 95 |
+
if sources:
|
| 96 |
+
source_links = "\n\n**Sources officielles :**\n" + "\n".join([f"- [{s}]({s})" for s in sources])
|
| 97 |
+
response += source_links
|
| 98 |
+
return response
|
| 99 |
+
|
| 100 |
+
print("🚀 Démarrage de l'interface Gradio...")
|
| 101 |
+
demo = gr.ChatInterface(
|
| 102 |
+
fn=predict,
|
| 103 |
+
title="🔍 CyberWise Assistant",
|
| 104 |
+
description="Assistant IA spécialisé en cybersécurité. Réponses basées sur ANSSI, CNIL, OWASP, CISA.",
|
| 105 |
+
examples=[
|
| 106 |
+
"Comment reconnaître un mail de phishing ?",
|
| 107 |
+
"Qu'est-ce que la double authentification ?",
|
| 108 |
+
"Est-il dangereux de réutiliser un mot de passe ?"
|
| 109 |
+
],
|
| 110 |
+
theme="soft"
|
| 111 |
+
)
|
| 112 |
+
demo.launch()
|