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)))