Files
aethas-free/main.py
T
2026-08-16 23:26:07 +02:00

342 lines
22 KiB
Python

import os
import uuid
import time
import re
from dotenv import load_dotenv
from fasthtml.common import *
from starlette.responses import FileResponse
# Import propre depuis le dossier modules
from modules.database import load_history, save_history, nettoyer_vieilles_discussions, HISTORY_FILE
from modules.scraper import rechercher_sur_google, extraire_contenu_urls
from modules.ai_engine import local_client, interroger_gemini_cascade, appeler_groq_api
from modules.router import nettoyer_decision_router
from modules.ui_components import render_user_msg, render_ai_msg, render_sidebar
load_dotenv()
nettoyer_vieilles_discussions()
svg_favicon = "%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Cstyle%3E@keyframes pulse { 0% { opacity: 1; stroke-width: 5; } 50% { opacity: 0.5; stroke-width: 7; } 100% { opacity: 1; stroke-width: 5; } } .neon { animation: pulse 2s infinite; transform-origin: 50px 50px; transform: rotate(45deg); }%3C/style%3E%3Crect width='100' height='100' fill='%23121212'/%3E%3Cg class='neon'%3E%3Crect x='25' y='25' width='50' height='50' fill='none' stroke='%2300e5ff'/%3E%3Cpath d='M25 50 L75 50 M50 25 L50 75' stroke='%23b300ff'/%3E%3Ccircle cx='50' cy='50' r='8' fill='%23e0e0e0'/%3E%3C/g%3E%3C/svg%3E"
theme_hdrs = (
Script(src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"),
Script(src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"),
Script(src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"),
Script(src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"),
Link(rel="stylesheet", href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css"),
Link(rel="icon", type="image/svg+xml", href=f"data:image/svg+xml;utf8,{svg_favicon}"),
Style("""
:root { --bg-dark: #121212; --bg-panel: #1e1e24; --accent-blue: #00e5ff; --accent-purple: #b300ff; --text-main: #e0e0e0; }
body { background-color: var(--bg-dark); color: var(--text-main); font-family: 'Segoe UI', Tahoma, sans-serif; margin: 0; display: flex; height: 100vh; overflow: hidden; box-sizing: border-box; }
.sidebar { width: 280px; background-color: #0a0a0c; border-right: 1px solid #333; padding: 20px; display: flex; flex-direction: column; height: 100vh; box-sizing: border-box; }
.sidebar-top { flex-shrink: 0; }
.sidebar-history { flex: 1; overflow-y: auto; margin-top: 15px; margin-bottom: 15px; }
.sidebar-footer { flex-shrink: 0; border-top: 1px solid #333; padding-top: 15px; text-align: center; }
.nav-buttons { display: flex; flex-direction: column; gap: 10px; margin-bottom: 20px; }
.new-chat-btn { display:block; text-align:center; text-decoration:none; background: transparent; border: 1px solid var(--accent-blue); color: var(--accent-blue); padding: 10px; border-radius: 5px; cursor: pointer; font-weight: bold; transition: 0.2s; }
.new-chat-btn:hover { background: rgba(0, 229, 255, 0.1); }
.export-btn { background: #2a2a35; border: 1px solid #444; color: white; padding: 10px; border-radius: 5px; cursor: pointer; transition: 0.2s; font-size: 1em; text-align:center; text-decoration:none; display:block;}
.export-btn:hover { background: #444; }
.history-item { display: flex; justify-content: space-between; align-items: center; padding: 10px; border-bottom: 1px solid #222; font-size: 0.9em; transition: 0.2s; }
.history-item:hover { background: #1a1a20; }
.history-link { flex: 1; text-decoration: none; color: inherit; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: block; padding-right: 10px; }
.history-btn { background: none; border: none; color: #888; cursor: pointer; padding: 2px 5px; font-size: 1.1em; }
.history-btn:hover { color: var(--accent-blue); }
.main-content { flex: 1; display: flex; flex-direction: column; height: 100vh; position: relative; box-sizing: border-box; }
.chat-container { flex: 1; padding: 20px; max-width: 1000px; margin: 0 auto; width: 100%; overflow-y: auto; display: flex; flex-direction: column; gap: 20px; padding-bottom: 140px; box-sizing: border-box; }
.user-bubble { background-color: #2a2a35; padding: 15px 20px; border-radius: 15px 15px 0 15px; align-self: flex-end; max-width: 80%; border: 1px solid #444; margin-left: auto; word-break: break-word; overflow-wrap: break-word; }
.ai-bubble { background-color: var(--bg-panel); padding: 15px 20px; border-radius: 15px 15px 15px 0; align-self: flex-start; max-width: 90%; width: 100%; border: 1px solid #333; word-break: break-word; overflow-wrap: break-word; }
.msg-actions { display: flex; gap: 10px; margin-top: 15px; border-top: 1px dashed #333; padding-top: 10px; justify-content: flex-end; flex-wrap: wrap; }
.msg-action-btn { background: transparent; border: 1px solid #444; color: #888; border-radius: 15px; padding: 5px 12px; cursor: pointer; font-size: 0.85em; transition: 0.2s; }
.msg-action-btn:hover { background: #2a2a35; color: var(--accent-blue); border-color: var(--accent-blue); }
.code-header { background: #16161a; padding: 8px 15px; display: flex; justify-content: space-between; align-items: center; border-radius: 8px 8px 0 0; font-family: monospace; font-size: 0.85em; border: 1px solid #333; border-bottom: none; }
.code-actions-group { display: flex; gap: 8px; }
.code-header button { background: #2a2a35; border: 1px solid #444; color: #e0e0e0; cursor: pointer; padding: 4px 10px; border-radius: 5px; font-size: 0.85em; transition: 0.2s; }
.code-header button:hover { background: var(--accent-blue); color: black; border-color: var(--accent-blue); }
.markdown-rendered pre { margin-top: 0; border-radius: 0 0 8px 8px; border: 1px solid #333; padding: 15px; overflow-x: auto; background-color: #0d0d0f !important; }
.input-area { position: absolute; bottom: 0; width: 100%; padding: 20px; background: linear-gradient(0deg, #121212 85%, transparent); display: flex; justify-content: center; box-sizing: border-box; }
.input-container-box { width: 100%; max-width: 900px; background: #1e1e24; border-radius: 24px; border: 1px solid #444; padding: 10px 15px; box-sizing: border-box; display: flex; flex-direction: column; gap: 8px; }
#file-preview-list { display: flex; flex-wrap: wrap; gap: 6px; max-height: 80px; overflow-y: auto; padding-bottom: 5px; }
.file-pill { background: #2a2a35; border: 1px solid #555; color: var(--accent-blue); padding: 5px 12px; border-radius: 12px; font-size: 0.8em; display: flex; align-items: center; gap: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.2); }
.input-row { display: flex; align-items: flex-end; gap: 10px; width: 100%; }
.input-field { background: transparent; border: none; color: white; resize: none; flex: 1; font-size: 1em; height: 36px; max-height: 140px; overflow-y: hidden; padding: 8px; font-family: inherit; box-sizing: border-box; line-height: 20px; }
.input-field:focus { outline: none; }
.file-btn { background: #2a2a35; border: 1px solid #444; color: var(--accent-blue); width: 36px !important; height: 36px !important; border-radius: 50%; display: flex; align-items: center; justify-content: center; cursor: pointer; font-size: 1.3em; text-decoration: none; flex-shrink: 0; }
.btn-submit { background: linear-gradient(135deg, var(--accent-blue), var(--accent-purple)); color: white; border: none; width: 36px !important; height: 36px !important; border-radius: 50%; display: flex; align-items: center; justify-content: center; cursor: pointer; font-size: 1.1em; flex-shrink: 0; }
.htmx-indicator { display: none; }
.htmx-request .htmx-indicator { display: flex; }
.tech-loader-container { display: flex; align-items: center; gap: 15px; color: var(--accent-blue); font-style: italic; background: var(--bg-panel); padding: 15px 20px; border-radius: 15px 15px 15px 0; border: 1px dashed var(--accent-blue); width: fit-content; margin-bottom: 20px; font-size: 0.9em; }
.tech-spinner { width: 20px; height: 20px; border: 3px solid rgba(0, 229, 255, 0.2); border-top-color: var(--accent-blue); border-radius: 50%; animation: spin 1s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
"""),
Script("""
function renderMarkdown() {
try {
document.querySelectorAll('.markdown-raw').forEach(el => {
if (el.dataset.rendered) return;
let container = el.nextElementSibling;
container.innerHTML = (typeof marked !== 'undefined') ? marked.parse(el.textContent) : el.textContent;
el.dataset.rendered = "true";
el.classList.remove('markdown-raw');
container.querySelectorAll('pre').forEach(pre => {
try {
let code = pre.querySelector('code');
if (code && !pre.previousElementSibling?.classList.contains('code-header')) {
let rawLang = code.className.replace('language-', '') || 'snippet';
let header = document.createElement('div');
header.className = 'code-header';
header.innerHTML = `
<span style="color:#00e5ff; font-weight:bold;">${rawLang.toUpperCase()}</span>
<div class="code-actions-group">
<button onclick="copyCodeBlock(this)">📋 Copier</button>
<button onclick="downloadCodeZip(this, '${rawLang}')">📦 ZIP</button>
</div>`;
pre.parentNode.insertBefore(header, pre);
if (typeof hljs !== 'undefined') hljs.highlightElement(code);
}
} catch(err) { console.warn("Erreur entête code", err); }
});
});
let chat = document.getElementById('chat-history');
if (chat) chat.scrollTop = chat.scrollHeight;
} catch(e) { console.error("Erreur markdown", e); }
}
function autoResize(textarea) {
if (!textarea) return;
textarea.style.height = '36px';
let scrollH = textarea.scrollHeight;
if (scrollH > 100) {
textarea.style.height = '100px';
textarea.style.overflowY = 'auto';
} else {
textarea.style.height = scrollH + 'px';
textarea.style.overflowY = 'hidden';
}
}
document.addEventListener('DOMContentLoaded', () => {
const ta = document.getElementById('prompt-input');
const dropZone = document.querySelector('.input-container-box');
const fileInput = document.getElementById('file-upload');
if (ta) {
ta.addEventListener('input', () => autoResize(ta));
ta.addEventListener('paste', (e) => {
let items = (e.clipboardData || e.originalEvent.clipboardData).items;
let dt = new DataTransfer();
if (fileInput && fileInput.files) {
for (let f of fileInput.files) dt.items.add(f);
}
let hasFiles = false;
for (let i = 0; i < items.length; i++) {
if (items[i].kind === 'file') {
let blob = items[i].getAsFile();
if (blob) { dt.items.add(blob); hasFiles = true; }
}
}
if (hasFiles) {
e.preventDefault();
fileInput.files = dt.files;
handleFileSelection(fileInput);
} else {
setTimeout(() => autoResize(ta), 20);
}
});
}
if (dropZone && fileInput) {
['dragenter', 'dragover'].forEach(eName => dropZone.addEventListener(eName, e => { e.preventDefault(); dropZone.style.borderColor = 'var(--accent-blue)'; }));
['dragleave', 'drop'].forEach(eName => dropZone.addEventListener(eName, e => { e.preventDefault(); dropZone.style.borderColor = '#444'; }));
dropZone.addEventListener('drop', (e) => {
e.preventDefault();
let dt = new DataTransfer();
if (fileInput.files) { for (let f of fileInput.files) dt.items.add(f); }
for (let f of e.dataTransfer.files) { dt.items.add(f); }
fileInput.files = dt.files;
handleFileSelection(fileInput);
});
}
});
function copyCodeBlock(btn) {
let pre = btn.closest('.code-header').nextElementSibling;
navigator.clipboard.writeText(pre.querySelector('code').innerText);
btn.innerText = "✅ Copié !";
setTimeout(() => btn.innerText = "📋 Copier", 2000);
}
function downloadCodeZip(btn, lang) {
let pre = btn.closest('.code-header').nextElementSibling;
let code = pre.querySelector('code').innerText;
let ext = lang === 'python' ? 'py' : (lang === 'javascript' ? 'js' : (lang === 'html' ? 'html' : 'txt'));
let fileName = 'aethas_snippet.' + ext;
if (typeof JSZip !== 'undefined') {
let zip = new JSZip();
zip.file(fileName, code);
zip.generateAsync({type: "blob"}).then(function(content) {
let link = document.createElement('a');
link.href = URL.createObjectURL(content);
link.download = "aethas_code_snippet.zip";
link.click();
});
} else {
let blob = new Blob([code], {type: 'text/plain;charset=utf-8'});
let link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = fileName;
link.click();
}
}
function handleFileSelection(input) {
let previewList = document.getElementById('file-preview-list');
previewList.innerHTML = '';
if (input.files) {
for (let i = 0; i < input.files.length; i++) {
let file = input.files[i];
let pill = document.createElement('div');
pill.className = 'file-pill';
pill.innerHTML = `📎 ${file.name} <span style="cursor:pointer; color:#ff5555; margin-left:4px;" onclick="removeFile(${i})">✕</span>`;
previewList.appendChild(pill);
}
}
}
function removeFile(index) {
let fileInput = document.getElementById('file-upload');
let dt = new DataTransfer();
let { files } = fileInput;
for (let i = 0; i < files.length; i++) {
if (i !== index) dt.items.add(files[i]);
}
fileInput.files = dt.files;
handleFileSelection(fileInput);
}
function downloadResponsePDF(btn) {
let content = btn.closest('.ai-bubble').querySelector('.markdown-rendered');
html2pdf().set({ margin: 10, filename: 'Aethas38_Reponse.pdf', html2canvas: { scale: 2 }, jsPDF: { unit: 'mm', format: 'a4' } }).from(content).save();
}
function downloadResponseTXT(btn) {
let text = btn.closest('.ai-bubble').querySelector('.markdown-rendered').innerText;
let blob = new Blob([text], {type: 'text/plain;charset=utf-8'});
let link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.download = 'Aethas38_Reponse.txt'; link.click();
}
function downloadResponseDOC(btn) {
let html = btn.closest('.ai-bubble').querySelector('.markdown-rendered').innerHTML;
let blob = new Blob(['\\ufeff' + html], { type: 'application/msword' });
let link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.download = 'Aethas38_Reponse.doc'; link.click();
}
function downloadResponseJSON(btn) {
let text = btn.closest('.ai-bubble').querySelector('.markdown-rendered').innerText;
let blob = new Blob([JSON.stringify({content: text}, null, 2)], {type: 'application/json;charset=utf-8'});
let link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.download = 'Aethas38_Reponse.json'; link.click();
}
function shareWhatsApp(btn) {
let text = btn.closest('.ai-bubble').querySelector('.markdown-rendered').innerText;
window.open('https://api.whatsapp.com/send?text=' + encodeURIComponent(text), '_blank');
}
function shareEmail(btn) {
let text = btn.closest('.ai-bubble').querySelector('.markdown-rendered').innerText;
window.open('mailto:?subject=Aethas38&body=' + encodeURIComponent(text), '_self');
}
""")
)
app, rt = fast_app(hdrs=theme_hdrs, secret_key="super_secret_aethas")
@rt('/')
def get(session):
if 'current_chat_id' not in session or not session['current_chat_id']:
session['current_chat_id'] = str(uuid.uuid4())
chat_id = session['current_chat_id']
history = load_history()
msgs = [render_user_msg(m['content']) if m['role']=='user' else render_ai_msg(m['content'], m.get('intention',''), m.get('fournisseur',''), m.get('modele',''), m.get('couleur','#333')) for m in history.get(chat_id, {}).get('messages', [])]
if msgs: msgs.append(Script("setTimeout(renderMarkdown, 150);"))
return Title("Aethas38 - Core"), Body(
Div(
Div(
Div(H2("AETHAS 38", style="color:#00e5ff; margin:0; text-align:center;"), P("Tech Core", style="font-size:0.7em; color:#888; text-align:center;"), margin_bottom="20px"),
Div(A("+ Nouvelle discussion", href="/new_chat", cls="new-chat-btn"), A("💾 Exporter JSON", href="/export_json", target="_blank", cls="export-btn"), cls="nav-buttons"),
cls="sidebar-top"
),
render_sidebar(),
Div(P("👤 Admin (Xavier)", style="color: #aaa; margin: 0; font-size: 0.9em;"), cls="sidebar-footer"),
cls="sidebar"
),
Div(
Div(*msgs, id="chat-history", cls="chat-container"),
Div(Div(Div(cls="tech-spinner"), Span("Aethas Core analyse la requête..."), cls="tech-loader-container"), id="global-loader", cls="htmx-indicator", style="max-width: 1000px; margin: 0 auto; width: 100%; padding: 0 20px; box-sizing: border-box; padding-bottom: 120px;"),
Div(
Form(
Input(type="hidden", name="chat_id", value=chat_id),
Div(
Div(id="file-preview-list"),
Div(
Label("+", _for="file-upload", cls="file-btn"),
Input(type="file", name="files", id="file-upload", multiple=True, style="display:none;", onchange="handleFileSelection(this)"),
Textarea(name="prompt", id="prompt-input", placeholder="Requête, lien ou glissez vos fichiers ici...", cls="input-field", rows="1", oninput="autoResize(this)"),
Button("↑", type="submit", cls="btn-submit"),
cls="input-row"
),
cls="input-container-box"
),
hx_post="/chat", hx_target="#chat-history", hx_swap="beforeend", hx_indicator="#global-loader",
hx_on__after_request="this.reset(); document.getElementById('file-preview-list').innerHTML=''; document.getElementById('prompt-input').style.height='36px';",
enctype="multipart/form-data", style="width: 100%; display: flex; justify-content: center;"
),
cls="input-area"
),
cls="main-content"
)
)
@rt('/chat')
async def post(request, session: dict):
try:
form = await request.form()
prompt = form.get("prompt", "")
chat_id = form.get("chat_id", str(uuid.uuid4()))
files = form.getlist("files")
session['current_chat_id'] = chat_id
history = load_history()
sec_prompt = f"""Analyse et route cette demande. Si recherche web nécessaire ("va sur", "site", "historique", "version", "cherche", etc.) -> choisis "gemini". Si code/technique -> "groq". Sinon -> "local".
Renvoie STRICTEMENT un JSON : {{"intention": "...", "fournisseur": "gemini|groq|local"}}
Requête : {prompt}"""
router_res = local_client.chat.completions.create(model="qwen2.5:3b", messages=[{"role": "system", "content": "JSON uniquement."}, {"role": "user", "content": sec_prompt}], temperature=0.1)
decision = nettoyer_decision_router(router_res.choices[0].message.content)
intention, fournisseur = decision.get('intention', 'Analyse'), decision.get('fournisseur', 'gemini').lower()
urls = re.findall(r'https?://[^\s]+', prompt)
mots_cles = ["cherche", "recherche", "sur internet", "sur le web", "sur le net", "va sur", "trouve", "site", "donne", "historique", "version"]
if any(m in prompt.lower() for m in mots_cles):
urls.extend(rechercher_sur_google(prompt))
web_text = extraire_contenu_urls(list(set(urls))) if urls else ""
file_summary = []
file_names = []
for f in files[:10]:
if f && f.filename: # Wait, Python uses `and` instead of `&&`