File size: 5,125 Bytes
0e0677c | 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 | import os
import gradio as gr
import requests
import json
from urllib.robotparser import RobotFileParser
from urllib.parse import urlparse
from bs4 import BeautifulSoup
import time
import subprocess
# ==== Démarrer Ollama ====
def start_ollama():
try:
requests.get("http://localhost:11434/api/tags", timeout=2)
except:
subprocess.Popen(["ollama", "serve"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
time.sleep(10)
# ==== Respect robots.txt ====
def can_fetch(url: str) -> bool:
try:
parsed = urlparse(url)
robots_url = f"{parsed.scheme}://{parsed.netloc}/robots.txt"
rp = RobotFileParser()
rp.set_url(robots_url)
rp.read()
return rp.can_fetch("*", url)
except:
return True
# ==== Scraper ====
def scrape_page(url: str) -> str:
if not can_fetch(url):
return ""
try:
headers = {"User-Agent": "CyberAssistant/1.0"}
resp = requests.get(url, headers=headers, timeout=10)
soup = BeautifulSoup(resp.text, "html.parser")
for tag in soup(["script", "style", "nav", "footer", "header", "aside"]):
tag.decompose()
return soup.get_text(separator=" ", strip=True)[:1500]
except:
return ""
# ==== Charger traductions ====
def load_lang_data():
langs = {}
for lang in ["fr", "mos", "dyu"]:
path = f"lang/{lang}.json"
if os.path.exists(path):
with open(path, "r", encoding="utf-8") as f:
langs[lang] = json.load(f)
else:
langs[lang] = {}
return langs
LANG_DATA = load_lang_data()
# ==== Interroger Phi-3 ====
def ask_phi3(prompt: str) -> str:
try:
response = requests.post(
"http://localhost:11434/api/generate",
json={
"model": "phi3",
"prompt": prompt,
"stream": False,
"options": {"temperature": 0.1}
},
timeout=120
)
return response.json().get("response", "Désolé, je n'ai pas pu générer une réponse.")
except Exception as e:
return "Erreur interne. Veuillez réessayer."
# ==== Sites ====
SITES = [
"https://www.ssi.gouv.fr/guide/mot-de-passe/",
"https://www.cert.ssi.gouv.fr/guide/certfr-guide-logs/",
"https://owasp.org/www-project-top-ten/",
"https://attack.mitre.org"
]
# ==== Fonction principale ====
def repondre(question: str, langue: str = "fr"):
question = question.strip()
if not question:
return "Veuillez poser une question."
start_ollama()
# 🔹 CAS 1 : Langue locale (moore/dioula)
if langue in ["mos", "dyu"]:
# Inverser le dictionnaire pour chercher la question
inv_map = {v: k for k, v in LANG_DATA[langue].items() if k.startswith("quest_")}
key = inv_map.get(question)
if key:
resp_key = "reponse_" + key.split("_", 1)[1]
if resp_key in LANG_DATA[langue]:
return LANG_DATA[langue][resp_key]
# Sinon, pas de réponse fiable → demander français
return (
"Désolé, je ne comprends pas encore toutes les questions en "
+ ("moore" if langue == "mos" else "dioula") +
". Veuillez poser votre question en français pour une réponse technique fiable."
)
# 🔹 CAS 2 : Français → recherche + IA
context_parts = []
for url in SITES:
if can_fetch(url):
content = scrape_page(url)
if content:
context_parts.append(f"Source: {url}\n{content}")
context = "\n\n".join(context_parts) if context_parts else "Aucune source officielle accessible."
prompt = f"""
Tu es un expert en cybersécurité. Réponds en français, de façon claire, concise et technique.
Utilise UNIQUEMENT les informations ci-dessous. Si le sujet n’est pas lié à la cybersécurité ou à l’analyse de logs, dis :
"Je suis un assistant spécialisé en cybersécurité. Veuillez poser une question sur ce thème."
Sources :
{context}
Question : {question}
Réponse :
"""
return ask_phi3(prompt)
# ==== Interface ====
demo = gr.Interface(
fn=repondre,
inputs=[
gr.Textbox(label="Posez votre question (ex. : 'Comment sécuriser un mot de passe ?')"),
gr.Dropdown(
choices=[
("Français", "fr"),
("Moore (Mossi)", "mos"),
("Dioula (Jula)", "dyu")
],
value="fr",
label="Langue"
)
],
outputs=gr.Textbox(label="Réponse"),
title="🛡️ Assistant Cybersécurité – Répond à (presque) TOUTE question",
description="En moore/dioula : réponses prédéfinies. En français : recherche web + IA en temps réel."
)
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860))) |