Vdphacker commited on
Commit
483b3b0
·
verified ·
1 Parent(s): 3d2c2c3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -94
app.py CHANGED
@@ -1,55 +1,39 @@
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",
@@ -59,54 +43,9 @@ pipe = pipeline(
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()
 
1
+ # Dans app.py — section de chargement du modèle
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  print("⏳ Chargement du modèle Mistral-7B...")
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
4
  import torch
5
 
 
 
 
 
 
 
 
6
  model_name = "mistralai/Mistral-7B-Instruct-v0.3"
7
  tokenizer = AutoTokenizer.from_pretrained(model_name)
8
+
9
+ # Détecter si GPU disponible
10
+ use_gpu = torch.cuda.is_available()
11
+ print(f"{'✅ GPU détecté.' if use_gpu else '⚠️ Aucun GPU — utilisation du CPU (plus lent).'}")
12
+
13
+ if use_gpu:
14
+ # Charger en 4-bit si GPU
15
+ from transformers import BitsAndBytesConfig
16
+ bnb_config = BitsAndBytesConfig(
17
+ load_in_4bit=True,
18
+ bnb_4bit_quant_type="nf4",
19
+ bnb_4bit_compute_dtype=torch.float16
20
+ )
21
+ model = AutoModelForCausalLM.from_pretrained(
22
+ model_name,
23
+ quantization_config=bnb_config,
24
+ device_map="auto",
25
+ trust_remote_code=True
26
+ )
27
+ device = 0
28
+ else:
29
+ # Charger en FP16/FP32 sur CPU (nécessite ~14 Go de RAM)
30
+ model = AutoModelForCausalLM.from_pretrained(
31
+ model_name,
32
+ torch_dtype=torch.float16, # ou torch.float32 si mémoire insuffisante
33
+ low_cpu_mem_usage=True,
34
+ trust_remote_code=True
35
+ )
36
+ device = -1
37
 
38
  pipe = pipeline(
39
  "text-generation",
 
43
  temperature=0.3,
44
  top_p=0.95,
45
  repetition_penalty=1.2,
46
+ device=device
47
  )
48
 
49
  def llm_generate(prompt: str) -> str:
50
  response = pipe(prompt)
51
+ return response[0]["generated_text"].replace(prompt, "").strip()