Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fd82d77709 | ||
|
|
189a2e4bf6 | ||
|
|
e322435bd8 | ||
|
|
efbecada77 | ||
|
|
4a9a0d8ec6 | ||
|
|
b554c983a6 | ||
|
|
007e723e4e | ||
|
|
95125df3b2 | ||
|
|
36f205a56e | ||
|
|
2eb3acceea | ||
|
|
4d5046e8d0 | ||
|
|
ba2f37cf59 | ||
|
|
4805228f28 | ||
|
|
6e4aee1984 | ||
|
|
b6765a9bc8 | ||
|
|
efdda0ed00 | ||
|
|
8a32c16ff4 | ||
|
|
4ce11d0bfe | ||
|
|
b3d92558fc | ||
|
|
ec37ac06fe | ||
|
|
6f7e3efd6e | ||
|
|
f794937fd8 | ||
|
|
4b80ff404f | ||
|
|
9288e849af | ||
|
|
00a92de1c4 | ||
|
|
43be6b5be6 |
No files matched your search
@@ -5,56 +5,78 @@ Ce projet est un laboratoire d'intelligence artificielle personnel. Il agit comm
|
|||||||
L'interface visuelle est inspirée de l'ergonomie de Gemini, avec le logo stylisé A38 (cerveau en réseau neuronal néon) comme charte graphique centrale.
|
L'interface visuelle est inspirée de l'ergonomie de Gemini, avec le logo stylisé A38 (cerveau en réseau neuronal néon) comme charte graphique centrale.
|
||||||
|
|
||||||
## 🏗️ Stack Technique & Architecture
|
## 🏗️ Stack Technique & Architecture
|
||||||
- **Backend :** FastAPI (Python) modulaire (une fonction = un module).
|
|
||||||
- **Frontend :** Vue.js + Tailwind CSS (Responsive / Mobile-first).
|
* **Backend :** FastAPI (Python) modulaire asynchrone (httpx, asyncio)[cite: 2].
|
||||||
- **Base de Données :** PostgreSQL (gestion des utilisateurs, historiques, suivi financier).
|
* **Frontend :** Vue.js + Tailwind CSS (Responsive / Mobile-first)[cite: 2].
|
||||||
- **Traitement Documentaire :** LibreOffice Headless (génération/conversion Excel, Word, PDF).
|
* **Base de Données :** PostgreSQL (gestion des utilisateurs, rôles hiérarchiques Super-Admin/Admin/User, historiques, suivi financier)[cite: 2].
|
||||||
- **Déploiement :** Docker, géré via Dockge et Gitea, sécurisé sur grappe RAID.
|
* **Traitement Documentaire :** LibreOffice Headless (génération/conversion Excel, Word, PDF)[cite: 2].
|
||||||
|
* **Déploiement :** Docker, géré via Dockge et Gitea, sécurisé sur grappe RAID[cite: 2].
|
||||||
|
|
||||||
## 📌 Règles de Versioning (SemVer)
|
## 📌 Règles de Versioning (SemVer)
|
||||||
Le développement suit un versioning strict (format `vX.Y.Z`) synchronisé avec les tags Gitea et GitHub, affiché dynamiquement sur l'interface :
|
|
||||||
- **Majeur (X) :** Changement profond d'architecture ou refonte globale.
|
Le développement suit un versioning strict (format `vX.Y.Z`) synchronisé avec les tags Gitea et GitHub, affiché dynamiquement sur l'interface[cite: 2]:
|
||||||
- **Mineur (Y) :** Validation et ajout d'une nouvelle fonctionnalité de la roadmap.
|
|
||||||
- **Patch (Z) :** Corrections de bugs, correctifs de sécurité ou ajustements visuels mineurs.
|
* **Majeur (X) :** Changement profond d'architecture ou refonte globale[cite: 2].
|
||||||
|
* **Mineur (Y) :** Validation et ajout d'une nouvelle fonctionnalité de la roadmap[cite: 2].
|
||||||
|
* **Patch (Z) :** Corrections de bugs, correctifs de sécurité ou ajustements visuels mineurs[cite: 2].
|
||||||
|
|
||||||
|
## 📦 Récupération des Paquets Docker (Tags)
|
||||||
|
|
||||||
|
Les images Docker sont construites automatiquement par les pipelines CI/CD lors de la création d'un tag[cite: 2].
|
||||||
|
|
||||||
|
* **Sur Gitea :** Depuis la page principale de votre dépôt, naviguez dans l'onglet **Packages** (ou Paquets). Vous y trouverez le registre de conteneurs avec toutes les versions taguées (`v0.16.1`, `latest`, etc.)[cite: 2].
|
||||||
|
* **Sur GitHub :** Depuis la page principale du dépôt, regardez dans la colonne de droite la section **Packages**. Cliquez dessus pour accéder au GitHub Container Registry (`ghcr.io/votre-utilisateur/aethas38-multi-ia`) et visualiser la liste des tags disponibles à tirer via Docker/Dockge[cite: 2].
|
||||||
|
|
||||||
## 🚀 ROADMAP & CAHIER DES CHARGES
|
## 🚀 ROADMAP & CAHIER DES CHARGES
|
||||||
|
|
||||||
### Sécurité & Infrastructure
|
### Sécurité & Infrastructure
|
||||||
- [x] Installation stricte via Dockge et Gitea (création automatique des dossiers inclus).
|
|
||||||
- [x] Sécurisation de la totalité du projet (fichiers, BDD PostgreSQL) sur le stockage RAID.
|
* [x] Installation stricte via Dockge et Gitea (création automatique des dossiers inclus)[cite: 2].
|
||||||
- [x] Mots de passe cryptés (bcrypt), protection anti-brute force.
|
* [x] Sécurisation de la totalité du projet (fichiers, BDD PostgreSQL) sur le stockage RAID[cite: 2].
|
||||||
- [x] Authentification 2FA obligatoire (Keepassium, Authenticator, etc.).
|
* [x] Mots de passe cryptés (bcrypt), protection anti-brute force[cite: 2].
|
||||||
- [x] Déconnexion automatique (timer invisible / session JWT) après 60 minutes d'inactivité.
|
* [x] Authentification 2FA obligatoire (Keepassium, Authenticator, etc.)[cite: 2].
|
||||||
- [x] Configuration de GitHub Actions / Gitea Actions pour la création automatique des paquets Docker (Tags SemVer + latest).
|
* [x] Déconnexion automatique (timer invisible / session JWT) après 60 minutes d'inactivité[cite: 2].
|
||||||
- [x] Horodatage UTC en base de données pour immunité au changement d'heure français (Prévention crash 2FA).
|
* [x] Configuration de GitHub Actions / Gitea Actions pour la création automatique des paquets Docker (Tags SemVer + latest)[cite: 2].
|
||||||
- [ ] Procédure de réinitialisation/modification du mot de passe (Admin et Utilisateurs).
|
* [x] Horodatage UTC en base de données pour immunité au changement d'heure français (Prévention crash 2FA)[cite: 2].
|
||||||
|
* [x] Rotation automatique des logs système : génération d'un fichier log par jour avec purge stricte des fichiers de plus de 7 jours[cite: 2].
|
||||||
|
* [x] Procédure de modification sécurisée du mot de passe (Utilisateurs et Admins)[cite: 2].
|
||||||
|
|
||||||
### Administration & Gestion des Utilisateurs
|
### Administration & Gestion des Utilisateurs
|
||||||
- [x] Assistant de première installation (création du compte admin complet).
|
|
||||||
- [ ] Refonte du setup initial (Super Admin) : Obligation de configurer le serveur mail (aide opérateurs FR/Gmail) et proposition de saisie des clés API.
|
* [x] Assistant de première installation : l'initiateur du projet se voit attribuer automatiquement le rôle exclusif de **Super-Admin** (un seul par projet)[cite: 2].
|
||||||
- [ ] Intégration de la roue crantée (Paramètres) en bas de la barre latérale.
|
* [x] Refonte du setup initial (Super Admin) : configuration du serveur mail (opérateurs FR/Gmail) et paramétrage complet des clés fournisseurs IA[cite: 2].
|
||||||
- [ ] Page de configuration Utilisateur : changement d'email (avec validation via lien envoyé) et de mot de passe.
|
* [x] Intégration de la roue crantée (Paramètres) en bas de la barre latérale[cite: 2].
|
||||||
- [ ] Page de configuration Admin : ajout/modification de fournisseurs, clés API, et serveur mail en permanence.
|
* [x] Page de configuration par niveau (Super-Admin, Admin, Utilisateur)[cite: 2].
|
||||||
- [ ] Hiérarchie des rôles : Un Admin peut proposer l'élévation d'un User en Admin (formulaire soumis à la validation exclusive du Super Admin).
|
* [x] Upload et personnalisation dynamique d'avatar utilisateur[cite: 2].
|
||||||
- [ ] Export de l'activité Admin : Fichier Excel avec KPI, graphiques "camembert", et suivi financier par utilisateur.
|
* [ ] Hiérarchie des rôles : Un Admin peut proposer l'élévation d'un User en Admin (formulaire soumis à la validation exclusive du Super Admin)[cite: 2].
|
||||||
- [ ] Suivi financier en temps réel et vérification du budget API.
|
* [ ] Export de l'activité Admin : Fichier Excel avec KPI, graphiques "camembert", et suivi financier par utilisateur[cite: 2].
|
||||||
- [ ] Envoi de rapport d'activité automatisé chaque jeudi à 04h00.
|
* [x] Suivi financier en temps réel et vérification du budget API (mis à jour après chaque requête et affiché de manière non invasive sous le nom)[cite: 2].
|
||||||
|
* [ ] Envoi de rapport d'activité automatisé chaque jeudi à 04h00[cite: 2].
|
||||||
|
|
||||||
### Expérience Utilisateur (UI/UX)
|
### Expérience Utilisateur (UI/UX)
|
||||||
- [x] Thème moderne (Gemini-like) et 100% compatible smartphones.
|
|
||||||
- [x] Refonte de la gestion des projets : séparation Épinglés (en haut) / Non Épinglés (Récents).
|
* [x] Thème moderne (Gemini-like) et 100% compatible smartphones[cite: 2].
|
||||||
- [x] Arrêt de la création automatique de nouveau projet à l'ouverture.
|
* [x] Refonte de la gestion des projets : séparation Épinglés (en haut) / Non Épinglés (Récents)[cite: 2].
|
||||||
- [x] Intégration permanente du logo AETHAS38 en local (Setup / Login / Dashboard).
|
* [x] Arrêt de la création automatique de nouveau projet à l'ouverture[cite: 2].
|
||||||
- [ ] Indicateur visuel (Loader/Animation) signalant que l'IA AETHAS38 "réfléchit" ou travaille.
|
* [x] Intégration permanente du logo AETHAS38 en local (Setup / Login / Dashboard)[cite: 2].
|
||||||
- [ ] Fonctionnalité de renommage manuel des discussions/projets.
|
* [x] Indicateur visuel (Loader/Animation) signalant que l'IA AETHAS38 "réfléchit" ou travaille[cite: 2].
|
||||||
|
* [x] Fonctionnalité de renommage manuel des discussions/projets[cite: 2].
|
||||||
|
* [ ] Affichage natif et fluide des images directement dans le flux de la discussion[cite: 2].
|
||||||
|
* [ ] Système de partage des réponses sur les réseaux et messageries externes (Facebook, WhatsApp, etc.)[cite: 2].
|
||||||
|
|
||||||
### Moteur IA, Modèles & Fonctionnalités
|
### Moteur IA, Modèles & Fonctionnalités
|
||||||
- [ ] Pipeline multi-agents : 1 Rédacteur de prompt, jusqu'à 5 Travailleurs, 1 Concaténeur final.
|
|
||||||
- [ ] Extraction automatisée des modèles disponibles chez les fournisseurs (sauvegarde txt horodatée ex: "07/10/2026 à 10h00").
|
* [x] Cœur asynchrone pour la parallélisation des appels API (module `orchestrator.py`)[cite: 2].
|
||||||
- [ ] Tâche planifiée (CRON) pour la mise à jour des modèles toutes les 12h (le timer se reset si mise à jour manuelle).
|
* [x] Pipeline multi-agents complet avec sélection dynamique par requête :
|
||||||
- [ ] Classement, filtrage (Gratuit/Payant) et catégorisation des modèles (Texte, Code, Image, Audio, Vidéo).
|
* Sélection de 1 à 5 travailleurs IA en parallèle[cite: 2].
|
||||||
- [ ] Upload manuel du fichier d'extraction des modèles avec intégration dans l'interface filtrable.
|
* Si un seul travailleur est sélectionné, bypass automatique du prompteur et du concaténeur[cite: 2].
|
||||||
- [ ] Traduction automatisée des descriptions des modèles via Ollama (local) ou Gemini.
|
* Si > 1 travailleur, activation de la chaîne complète (1 Prompteur ➔ N Travailleurs ➔ 1 Concaténeur)[cite: 2].
|
||||||
- [ ] Interface d'aide à la décision pour le choix des modèles selon la tâche souhaitée.
|
* [x] Extraction universelle multi-fournisseurs (OpenRouter, Groq, DeepSeek, Mistral, Gemini, Cloudflare) avec timeout porté à 90 secondes[cite: 2].
|
||||||
- [ ] Mécanisme de fallback / termes génériques pour les appels API (protection contre le dépassement des quotas Gemini).
|
* [x] Tâche planifiée (CRON) pour la mise à jour des modèles toutes les 12h (00h00 et 12h00)[cite: 2].
|
||||||
- [ ] Téléchargement des requêtes, réponses et fichiers générés (Excel, PDF, TXT, Images).
|
* [x] Page spécifique dédiée aux modèles permettant l'export, l'import manuel d'un fichier d'extraction JSON, ainsi que le filtrage par prix, domaine et mots-clés[cite: 2].
|
||||||
|
* [x] Extraction unitaire des retours IA et téléchargement global d'une conversation (formats TXT et JSON)[cite: 2].
|
||||||
|
* [x] Détection et téléchargement ciblé de pièces jointes ou blocs spécifiques (Code brut, scripts, fichiers de données) générés par l'IA en respectant le nommage exact demandé[cite: 2].
|
||||||
|
* [x] Classement, filtrage (Gratuit/Payant) et catégorisation des modèles (Texte, Code, Vision, Audio)[cite: 2].
|
||||||
|
* [ ] Traduction automatisée des descriptions des modèles via Ollama (local) ou Gemini[cite: 2].
|
||||||
|
* [ ] Interface d'aide à la décision pour le choix des modèles selon la tâche souhaitée[cite: 2].
|
||||||
|
* [ ] Mécanisme de fallback / termes génériques pour les appels API (protection contre le dépassement des quotas)[cite: 2].
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
# 📚 WIKI AETHAS38 - Configuration des Fournisseurs IA
|
||||||
|
|
||||||
|
Ce document détaille la procédure pour obtenir les clés API avec les droits complets (Inférence + Accès financier) nécessaires au fonctionnement de l'Orchestrateur AETHAS38.
|
||||||
|
|
||||||
|
## 1. OpenRouter (Prioritaire)
|
||||||
|
OpenRouter agit comme un agrégateur. C'est le fournisseur recommandé car il permet d'accéder à presque tous les modèles (y compris Gemini, Claude, Llama) avec un seul portefeuille prépayé.
|
||||||
|
* **Obtenir la clé API :** Allez sur [OpenRouter Keys](https://openrouter.ai/keys). Créez une clé standard sans limite de crédit pour permettre à AETHAS38 de requêter les modèles.
|
||||||
|
* **Accès Financier (Management Key) :** Pour que AETHAS38 lise votre solde en temps réel, vous devez générer une clé spécifique d'administration (Management Key) sur la même page, ou accorder les droits `read_balance` à votre clé API principale selon les dernières mises à jour de leur interface.
|
||||||
|
|
||||||
|
## 2. Google Gemini Studio
|
||||||
|
* **Obtenir la clé API :** Rendez-vous sur [Google AI Studio](https://aistudio.google.com/app/apikey).
|
||||||
|
* **Levée des quotas :** Par défaut, la clé est gratuite mais soumise à des limites strictes (ex: 15 requêtes/minute) qui bloqueront le travail en parallèle d'AETHAS38. Pour un accès total, liez votre projet AI Studio à un compte de facturation Google Cloud Platform (GCP).
|
||||||
|
|
||||||
|
## 3. DeepSeek & Groq
|
||||||
|
* **DeepSeek :** [DeepSeek Platform](https://platform.deepseek.com/api_keys). Facturation à l'usage (Token). Il faut provisionner le compte par carte bancaire (Top-up).
|
||||||
|
* **Groq :** [Groq Console](https://console.groq.com/keys). Actuellement en phase gratuite avec quotas de requêtes très élevés, idéal pour les travailleurs de base de l'orchestrateur.
|
||||||
|
|
||||||
|
## 4. Cloudflare Workers AI & HuggingFace
|
||||||
|
* **Cloudflare :** [Cloudflare Dash](https://dash.cloudflare.com/profile/api-tokens). Créez un token personnalisé avec la permission `Workers AI : Read/Write`. L'ID de compte (Account ID) est visible dans la barre latérale droite de l'aperçu de la zone.
|
||||||
|
* **HuggingFace :** [HF Settings](https://huggingface.co/settings/tokens). Générez un token *Fine-Grained* et cochez les permissions liées à l'`Inference API` pour permettre l'exécution des modèles serverless.
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
from openai import OpenAI
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from .models import SystemSettings
|
||||||
|
|
||||||
|
def get_ai_response(messages: list, settings: SystemSettings) -> str:
|
||||||
|
"""Route la conversation vers le premier fournisseur IA disponible, priorité à Gemini Direct."""
|
||||||
|
if not settings:
|
||||||
|
raise HTTPException(status_code=500, detail="Configuration système introuvable.")
|
||||||
|
|
||||||
|
formatted_messages = [{"role": msg.role, "content": msg.content} for msg in messages]
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 1. Priorité absolue : Test Gemini direct
|
||||||
|
if settings.gemini_api_key:
|
||||||
|
client = OpenAI(
|
||||||
|
base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
|
||||||
|
api_key=settings.gemini_api_key
|
||||||
|
)
|
||||||
|
# Correction : Utilisation exacte du modèle 3.5 Flash-Lite
|
||||||
|
model = "gemini-3.5-flash-lite"
|
||||||
|
response = client.chat.completions.create(model=model, messages=formatted_messages)
|
||||||
|
|
||||||
|
# 2. Test OpenRouter (Fallback)
|
||||||
|
elif settings.openrouter_api_key:
|
||||||
|
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=settings.openrouter_api_key)
|
||||||
|
model = "google/gemini-3.5-flash-lite"
|
||||||
|
response = client.chat.completions.create(
|
||||||
|
model=model,
|
||||||
|
messages=formatted_messages,
|
||||||
|
extra_headers={"HTTP-Referer": "https://aethas38.duckdns.org", "X-Title": "AETHAS38"}
|
||||||
|
)
|
||||||
|
|
||||||
|
# 3. Test DeepSeek
|
||||||
|
elif settings.deepseek_api_key:
|
||||||
|
client = OpenAI(base_url="https://api.deepseek.com/v1", api_key=settings.deepseek_api_key)
|
||||||
|
model = "deepseek-chat"
|
||||||
|
response = client.chat.completions.create(model=model, messages=formatted_messages)
|
||||||
|
|
||||||
|
# 4. Test Groq
|
||||||
|
elif settings.groq_api_key:
|
||||||
|
client = OpenAI(base_url="https://api.groq.com/openai/v1", api_key=settings.groq_api_key)
|
||||||
|
model = "llama3-8b-8192"
|
||||||
|
response = client.chat.completions.create(model=model, messages=formatted_messages)
|
||||||
|
|
||||||
|
else:
|
||||||
|
raise HTTPException(status_code=400, detail="Aucune clé API IA n'est configurée.")
|
||||||
|
|
||||||
|
return response.choices[0].message.content
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Erreur API IA : {str(e)}")
|
||||||
|
raise HTTPException(status_code=502, detail=f"Détail du fournisseur : {str(e)}")
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import logging
|
||||||
|
from logging.handlers import TimedRotatingFileHandler
|
||||||
|
import os
|
||||||
|
|
||||||
|
# Création du dossier logs à la racine du projet
|
||||||
|
log_dir = os.path.join(os.getcwd(), "logs")
|
||||||
|
os.makedirs(log_dir, exist_ok=True)
|
||||||
|
|
||||||
|
# Configuration du logger
|
||||||
|
system_logger = logging.getLogger("AETHAS38_Logger")
|
||||||
|
system_logger.setLevel(logging.INFO)
|
||||||
|
|
||||||
|
# Rotation tous les jours à minuit, conservation sur 7 jours
|
||||||
|
handler = TimedRotatingFileHandler(
|
||||||
|
filename=os.path.join(log_dir, "aethas38_system.log"),
|
||||||
|
when="midnight",
|
||||||
|
interval=1,
|
||||||
|
backupCount=7,
|
||||||
|
encoding="utf-8"
|
||||||
|
)
|
||||||
|
|
||||||
|
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%d/%m/%Y %H:%M:%S')
|
||||||
|
handler.setFormatter(formatter)
|
||||||
|
system_logger.addHandler(handler)
|
||||||
+128
-185
@@ -1,239 +1,182 @@
|
|||||||
from fastapi import FastAPI, Depends, HTTPException, status, Request, Response
|
from fastapi import FastAPI, Depends, HTTPException, status, Request, Response, UploadFile, File
|
||||||
from fastapi.responses import RedirectResponse, FileResponse
|
from fastapi.responses import RedirectResponse, FileResponse
|
||||||
from fastapi.staticfiles import StaticFiles
|
from fastapi.staticfiles import StaticFiles
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
from typing import List
|
from typing import List
|
||||||
import os
|
import os, json, asyncio, shutil
|
||||||
|
from datetime import datetime
|
||||||
|
import pytz
|
||||||
|
|
||||||
# Importation de nos modules locaux
|
from .database import engine, Base, get_db, SessionLocal
|
||||||
from .database import engine, Base, get_db
|
|
||||||
from .models import User, Project, Message
|
|
||||||
from .auth import get_password_hash, generate_totp_secret, get_totp_uri, verify_password, verify_totp, create_access_token, verify_token
|
from .auth import get_password_hash, generate_totp_secret, get_totp_uri, verify_password, verify_totp, create_access_token, verify_token
|
||||||
from .schemas import AdminCreate, LoginRequest, ProjectCreate, ProjectResponse, ProjectRename, MessageCreate, MessageResponse
|
from .schemas import AdminCreate, LoginRequest, ProjectCreate, ProjectResponse, ProjectRename, MessageCreate, MessageResponse, PasswordChange
|
||||||
from .models import User, Project, Message, SystemSettings
|
from .models import User, Project, Message, SystemSettings, AIModel, FinancialLog
|
||||||
|
from .orchestrator import run_orchestrator, sync_providers_models, sync_finances
|
||||||
|
|
||||||
# Création des tables dans la base de données
|
|
||||||
Base.metadata.create_all(bind=engine)
|
Base.metadata.create_all(bind=engine)
|
||||||
|
app = FastAPI(title="AETHAS38")
|
||||||
|
|
||||||
app = FastAPI(title="AETHAS38 - Orchestrateur Multi-IA")
|
|
||||||
|
|
||||||
# Configuration des fichiers statiques (images, css locaux, etc.)
|
|
||||||
assets_path = os.path.join(os.getcwd(), "frontend", "assets")
|
assets_path = os.path.join(os.getcwd(), "frontend", "assets")
|
||||||
os.makedirs(assets_path, exist_ok=True) # Crée le dossier s'il n'existe pas
|
avatars_path = os.path.join(assets_path, "avatars")
|
||||||
app.mount("/static", StaticFiles(directory=assets_path), name="static")
|
os.makedirs(assets_path, exist_ok=True)
|
||||||
|
os.makedirs(avatars_path, exist_ok=True)
|
||||||
|
app.mount("/assets", StaticFiles(directory=assets_path), name="assets")
|
||||||
|
|
||||||
def is_setup_required(db: Session) -> bool:
|
async def scheduler_task():
|
||||||
"""Vérifie si la base de données contient au moins un administrateur."""
|
tz = pytz.timezone('Europe/Paris')
|
||||||
admin = db.query(User).filter(User.is_admin == True).first()
|
while True:
|
||||||
return admin is None
|
now = datetime.now(tz)
|
||||||
|
if (now.hour == 0 or now.hour == 12) and now.minute == 0:
|
||||||
|
db = SessionLocal()
|
||||||
|
settings = db.query(SystemSettings).first()
|
||||||
|
if settings:
|
||||||
|
try: await sync_providers_models(db, settings, "Automatique")
|
||||||
|
except: pass
|
||||||
|
db.close()
|
||||||
|
await asyncio.sleep(60)
|
||||||
|
await asyncio.sleep(30)
|
||||||
|
|
||||||
|
@app.on_event("startup")
|
||||||
|
async def startup_event(): asyncio.create_task(scheduler_task())
|
||||||
|
|
||||||
|
def is_setup_required(db: Session) -> bool: return db.query(User).filter(User.is_superadmin == True).first() is None
|
||||||
|
|
||||||
|
def get_current_user(request: Request, db: Session = Depends(get_db)):
|
||||||
|
token = request.cookies.get("session_token")
|
||||||
|
if not token: raise HTTPException(status_code=401, detail="Non authentifié")
|
||||||
|
payload = verify_token(token)
|
||||||
|
if not payload: raise HTTPException(status_code=401, detail="Session expirée")
|
||||||
|
user = db.query(User).filter(User.username == payload.get("sub")).first()
|
||||||
|
if not user: raise HTTPException(status_code=401, detail="Utilisateur introuvable")
|
||||||
|
return user
|
||||||
|
|
||||||
@app.get("/")
|
@app.get("/")
|
||||||
def read_root(db: Session = Depends(get_db)):
|
def read_root(db: Session = Depends(get_db)): return RedirectResponse(url="/setup") if is_setup_required(db) else RedirectResponse(url="/login")
|
||||||
if is_setup_required(db):
|
|
||||||
return RedirectResponse(url="/setup")
|
|
||||||
return RedirectResponse(url="/login")
|
|
||||||
|
|
||||||
@app.get("/setup")
|
@app.get("/setup")
|
||||||
def setup_page(db: Session = Depends(get_db)):
|
def setup_page(db: Session = Depends(get_db)): return RedirectResponse(url="/login") if not is_setup_required(db) else FileResponse(os.path.join(os.getcwd(), "frontend", "index.html"))
|
||||||
"""Affiche l'interface d'installation Vue.js."""
|
|
||||||
if not is_setup_required(db):
|
|
||||||
return RedirectResponse(url="/login")
|
|
||||||
|
|
||||||
frontend_path = os.path.join(os.getcwd(), "frontend", "index.html")
|
|
||||||
if not os.path.exists(frontend_path):
|
|
||||||
raise HTTPException(status_code=404, detail="Interface introuvable.")
|
|
||||||
|
|
||||||
return FileResponse(frontend_path)
|
|
||||||
|
|
||||||
@app.get("/login")
|
@app.get("/login")
|
||||||
def login_page(db: Session = Depends(get_db)):
|
def login_page(db: Session = Depends(get_db)): return RedirectResponse(url="/setup") if is_setup_required(db) else FileResponse(os.path.join(os.getcwd(), "frontend", "login.html"))
|
||||||
"""Affiche la page de connexion sécurisée."""
|
|
||||||
if is_setup_required(db):
|
|
||||||
return RedirectResponse(url="/setup")
|
|
||||||
|
|
||||||
frontend_path = os.path.join(os.getcwd(), "frontend", "login.html")
|
|
||||||
if not os.path.exists(frontend_path):
|
|
||||||
raise HTTPException(status_code=404, detail="Interface de connexion introuvable.")
|
|
||||||
|
|
||||||
return FileResponse(frontend_path)
|
|
||||||
|
|
||||||
@app.post("/api/setup")
|
@app.post("/api/setup")
|
||||||
def create_admin(admin_data: AdminCreate, db: Session = Depends(get_db)):
|
def create_admin(admin_data: AdminCreate, db: Session = Depends(get_db)):
|
||||||
"""Reçoit les données du frontend, crée l'admin, sauvegarde la configuration et retourne le QR Code 2FA."""
|
if not is_setup_required(db): raise HTTPException(status_code=403, detail="Déjà installé.")
|
||||||
if not is_setup_required(db):
|
new_admin = User(email=admin_data.email, username=admin_data.username, hashed_password=get_password_hash(admin_data.password), totp_secret=generate_totp_secret(), is_admin=True, is_superadmin=True)
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_403_FORBIDDEN,
|
|
||||||
detail="L'installation a déjà été effectuée."
|
|
||||||
)
|
|
||||||
|
|
||||||
# Création du Super Admin
|
|
||||||
hashed_pw = get_password_hash(admin_data.password)
|
|
||||||
totp_secret = generate_totp_secret()
|
|
||||||
new_admin = User(
|
|
||||||
email=admin_data.email,
|
|
||||||
username=admin_data.username,
|
|
||||||
hashed_password=hashed_pw,
|
|
||||||
totp_secret=totp_secret,
|
|
||||||
is_admin=True
|
|
||||||
)
|
|
||||||
db.add(new_admin)
|
db.add(new_admin)
|
||||||
|
new_settings = SystemSettings(smtp_host=admin_data.smtp_host, smtp_port=admin_data.smtp_port, smtp_user=admin_data.smtp_user, smtp_password=admin_data.smtp_password, openrouter_api_key=admin_data.openrouter_api_key, openrouter_management_key=admin_data.openrouter_management_key, groq_api_key=admin_data.groq_api_key, gemini_api_key=admin_data.gemini_api_key, deepseek_api_key=admin_data.deepseek_api_key, mistral_api_key=admin_data.mistral_api_key, cloudflare_account_id=admin_data.cloudflare_account_id, cloudflare_api_token=admin_data.cloudflare_api_token, huggingface_api_key=admin_data.huggingface_api_key)
|
||||||
# Sauvegarde des paramètres système
|
|
||||||
new_settings = SystemSettings(
|
|
||||||
smtp_host=admin_data.smtp_host,
|
|
||||||
smtp_port=admin_data.smtp_port,
|
|
||||||
smtp_user=admin_data.smtp_user,
|
|
||||||
smtp_password=admin_data.smtp_password,
|
|
||||||
gemini_api_key=admin_data.gemini_api_key,
|
|
||||||
openrouter_api_key=admin_data.openrouter_api_key
|
|
||||||
)
|
|
||||||
db.add(new_settings)
|
db.add(new_settings)
|
||||||
|
|
||||||
db.commit()
|
db.commit()
|
||||||
db.refresh(new_admin)
|
db.refresh(new_admin)
|
||||||
|
return {"message": "Succès", "totp_secret": new_admin.totp_secret, "totp_uri": get_totp_uri(new_admin.totp_secret, new_admin.username)}
|
||||||
totp_uri = get_totp_uri(totp_secret, new_admin.username)
|
|
||||||
return {
|
|
||||||
"message": "Configuration terminée avec succès.",
|
|
||||||
"totp_secret": totp_secret,
|
|
||||||
"totp_uri": totp_uri
|
|
||||||
}
|
|
||||||
|
|
||||||
@app.post("/api/login")
|
@app.post("/api/login")
|
||||||
def login(login_data: LoginRequest, response: Response, db: Session = Depends(get_db)):
|
def login(login_data: LoginRequest, response: Response, db: Session = Depends(get_db)):
|
||||||
"""Vérifie les identifiants et crée une session de 60 minutes."""
|
|
||||||
user = db.query(User).filter(User.username == login_data.username).first()
|
user = db.query(User).filter(User.username == login_data.username).first()
|
||||||
|
if not user or not verify_password(login_data.password, user.hashed_password): raise HTTPException(status_code=401, detail="Identifiants incorrects.")
|
||||||
# Vérification de l'utilisateur et du mot de passe
|
if not verify_totp(user.totp_secret, login_data.totp_code): raise HTTPException(status_code=401, detail="2FA invalide.")
|
||||||
if not user or not verify_password(login_data.password, user.hashed_password):
|
response.set_cookie(key="session_token", value=create_access_token(data={"sub": user.username}), httponly=True, max_age=3600, samesite="lax")
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
||||||
detail="Nom d'utilisateur ou mot de passe incorrect."
|
|
||||||
)
|
|
||||||
|
|
||||||
# Vérification du code 2FA
|
|
||||||
if not verify_totp(user.totp_secret, login_data.totp_code):
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
||||||
detail="Code 2FA invalide."
|
|
||||||
)
|
|
||||||
|
|
||||||
# Création du jeton de session
|
|
||||||
access_token = create_access_token(data={"sub": user.username})
|
|
||||||
|
|
||||||
# Injection du jeton dans un cookie sécurisé (invisible pour le JavaScript côté client)
|
|
||||||
response.set_cookie(
|
|
||||||
key="session_token",
|
|
||||||
value=access_token,
|
|
||||||
httponly=True,
|
|
||||||
max_age=3600, # 3600 secondes = 60 minutes
|
|
||||||
samesite="lax"
|
|
||||||
)
|
|
||||||
|
|
||||||
return {"message": "Connexion réussie"}
|
return {"message": "Connexion réussie"}
|
||||||
|
|
||||||
@app.get("/dashboard")
|
@app.get("/dashboard")
|
||||||
def dashboard(request: Request):
|
def dashboard(request: Request):
|
||||||
"""Route protégée : affiche l'interface principale si le cookie est valide."""
|
|
||||||
token = request.cookies.get("session_token")
|
token = request.cookies.get("session_token")
|
||||||
if not token:
|
if not token or not verify_token(token): return RedirectResponse(url="/login")
|
||||||
return RedirectResponse(url="/login")
|
return FileResponse(os.path.join(os.getcwd(), "frontend", "dashboard.html"))
|
||||||
|
|
||||||
payload = verify_token(token)
|
@app.get("/api/users/me")
|
||||||
if not payload:
|
def get_me(current_user: User = Depends(get_current_user)):
|
||||||
return RedirectResponse(url="/login")
|
return {"username": current_user.username, "is_admin": current_user.is_admin, "is_superadmin": current_user.is_superadmin, "avatar_path": current_user.avatar_path}
|
||||||
|
|
||||||
frontend_path = os.path.join(os.getcwd(), "frontend", "dashboard.html")
|
@app.put("/api/users/me/password")
|
||||||
if not os.path.exists(frontend_path):
|
def change_password(passwords: PasswordChange, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
||||||
raise HTTPException(status_code=404, detail="Interface du tableau de bord introuvable.")
|
if not verify_password(passwords.old_password, current_user.hashed_password): raise HTTPException(status_code=400, detail="L'ancien mot de passe est incorrect.")
|
||||||
|
if len(passwords.new_password) < 8: raise HTTPException(status_code=400, detail="8 caractères minimum.")
|
||||||
|
current_user.hashed_password = get_password_hash(passwords.new_password)
|
||||||
|
db.commit()
|
||||||
|
return {"message": "Mot de passe mis à jour."}
|
||||||
|
|
||||||
return FileResponse(frontend_path)
|
@app.post("/api/users/me/avatar")
|
||||||
|
async def upload_avatar(file: UploadFile = File(...), db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
||||||
# --- GESTION DES PROJETS ---
|
file_location = os.path.join(avatars_path, f"user_{current_user.id}.jpg")
|
||||||
|
with open(file_location, "wb") as buffer: shutil.copyfileobj(file.file, buffer)
|
||||||
def get_current_user(request: Request, db: Session = Depends(get_db)):
|
current_user.avatar_path = f"/assets/avatars/user_{current_user.id}.jpg?v={int(datetime.now().timestamp())}"
|
||||||
"""Extrait l'utilisateur actuel à partir du cookie de session JWT."""
|
db.commit()
|
||||||
token = request.cookies.get("session_token")
|
return {"message": "Avatar mis à jour", "avatar_path": current_user.avatar_path}
|
||||||
if not token:
|
|
||||||
raise HTTPException(status_code=401, detail="Non authentifié")
|
|
||||||
|
|
||||||
payload = verify_token(token)
|
|
||||||
if not payload:
|
|
||||||
raise HTTPException(status_code=401, detail="Session expirée")
|
|
||||||
|
|
||||||
user = db.query(User).filter(User.username == payload.get("sub")).first()
|
|
||||||
if not user:
|
|
||||||
raise HTTPException(status_code=401, detail="Utilisateur introuvable")
|
|
||||||
return user
|
|
||||||
|
|
||||||
@app.get("/api/projects", response_model=List[ProjectResponse])
|
@app.get("/api/projects", response_model=List[ProjectResponse])
|
||||||
def get_projects(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
def get_projects(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): return db.query(Project).filter(Project.user_id == current_user.id).order_by(Project.created_at.desc()).all()
|
||||||
"""Récupère tous les projets de l'utilisateur connecté."""
|
|
||||||
return db.query(Project).filter(Project.user_id == current_user.id).order_by(Project.created_at.desc()).all()
|
|
||||||
|
|
||||||
@app.post("/api/projects", response_model=ProjectResponse)
|
@app.post("/api/projects", response_model=ProjectResponse)
|
||||||
def create_project(project: ProjectCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
def create_project(project: ProjectCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
||||||
"""Crée un nouveau projet pour l'utilisateur connecté."""
|
p = Project(title=project.title, user_id=current_user.id); db.add(p); db.commit(); db.refresh(p); return p
|
||||||
new_project = Project(title=project.title, user_id=current_user.id)
|
|
||||||
db.add(new_project)
|
|
||||||
db.commit()
|
|
||||||
db.refresh(new_project)
|
|
||||||
return new_project
|
|
||||||
|
|
||||||
@app.put("/api/projects/{project_id}/rename", response_model=ProjectResponse)
|
@app.put("/api/projects/{project_id}/rename", response_model=ProjectResponse)
|
||||||
def rename_project(project_id: int, project_data: ProjectRename, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
def rename_project(project_id: int, project_data: ProjectRename, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
||||||
"""Renomme un projet existant."""
|
p = db.query(Project).filter(Project.id == project_id, Project.user_id == current_user.id).first()
|
||||||
project = db.query(Project).filter(Project.id == project_id, Project.user_id == current_user.id).first()
|
if not p: raise HTTPException(status_code=404)
|
||||||
if not project:
|
p.title = project_data.title; db.commit(); db.refresh(p); return p
|
||||||
raise HTTPException(status_code=404, detail="Projet introuvable")
|
|
||||||
|
|
||||||
project.title = project_data.title
|
|
||||||
db.commit()
|
|
||||||
db.refresh(project)
|
|
||||||
return project
|
|
||||||
|
|
||||||
@app.put("/api/projects/{project_id}/pin", response_model=ProjectResponse)
|
@app.put("/api/projects/{project_id}/pin", response_model=ProjectResponse)
|
||||||
def toggle_pin_project(project_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
def toggle_pin_project(project_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
||||||
"""Bascule le statut épinglé (is_pinned) d'un projet."""
|
p = db.query(Project).filter(Project.id == project_id, Project.user_id == current_user.id).first()
|
||||||
project = db.query(Project).filter(Project.id == project_id, Project.user_id == current_user.id).first()
|
if not p: raise HTTPException(status_code=404)
|
||||||
if not project:
|
p.is_pinned = not p.is_pinned; db.commit(); db.refresh(p); return p
|
||||||
raise HTTPException(status_code=404, detail="Projet introuvable")
|
|
||||||
|
|
||||||
project.is_pinned = not project.is_pinned
|
|
||||||
db.commit()
|
|
||||||
db.refresh(project)
|
|
||||||
return project
|
|
||||||
|
|
||||||
@app.delete("/api/projects/{project_id}")
|
@app.delete("/api/projects/{project_id}")
|
||||||
def delete_project(project_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
def delete_project(project_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
||||||
"""Supprime définitivement un projet et tous ses messages associés."""
|
p = db.query(Project).filter(Project.id == project_id, Project.user_id == current_user.id).first()
|
||||||
project = db.query(Project).filter(Project.id == project_id, Project.user_id == current_user.id).first()
|
if not p: raise HTTPException(status_code=404)
|
||||||
if not project:
|
db.delete(p); db.commit(); return {"message": "Supprimé"}
|
||||||
raise HTTPException(status_code=404, detail="Projet introuvable")
|
|
||||||
|
|
||||||
db.delete(project)
|
@app.get("/api/projects/{project_id}/export")
|
||||||
db.commit()
|
def export_project(project_id: int, format: str = "txt", db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
||||||
return {"message": "Projet supprimé"}
|
p = db.query(Project).filter(Project.id == project_id, Project.user_id == current_user.id).first()
|
||||||
|
messages = db.query(Message).filter(Message.project_id == project_id).order_by(Message.created_at.asc()).all()
|
||||||
# --- GESTION DES MESSAGES ---
|
if format == "json":
|
||||||
|
data = [{"role": m.role, "content": m.content, "date": m.created_at.isoformat()} for m in messages]
|
||||||
|
return Response(content=json.dumps(data, indent=2), media_type="application/json", headers={"Content-Disposition": f"attachment; filename=export_{project_id}.json"})
|
||||||
|
text = f"--- HISTORIQUE : {p.title} ---\n\n"
|
||||||
|
for m in messages: text += f"[{m.created_at.strftime('%Y-%m-%d %H:%M:%S')}] {'VOUS' if m.role == 'user' else 'AETHAS38'}:\n{m.content}\n\n{'-'*50}\n\n"
|
||||||
|
return Response(content=text, media_type="text/plain;charset=utf-8", headers={"Content-Disposition": f"attachment; filename=export_{project_id}.txt"})
|
||||||
|
|
||||||
@app.get("/api/projects/{project_id}/messages", response_model=List[MessageResponse])
|
@app.get("/api/projects/{project_id}/messages", response_model=List[MessageResponse])
|
||||||
def get_messages(project_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
def get_messages(project_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): return db.query(Message).filter(Message.project_id == project_id).order_by(Message.created_at.asc()).all()
|
||||||
"""Récupère tous les messages d'un projet spécifique."""
|
|
||||||
project = db.query(Project).filter(Project.id == project_id, Project.user_id == current_user.id).first()
|
@app.post("/api/projects/{project_id}/messages", response_model=List[MessageResponse])
|
||||||
if not project:
|
async def create_message(project_id: int, message: MessageCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
||||||
raise HTTPException(status_code=404, detail="Projet introuvable")
|
db.add(Message(role=message.role, content=message.content, project_id=project_id)); db.commit()
|
||||||
|
history = db.query(Message).filter(Message.project_id == project_id).order_by(Message.created_at.asc()).all()
|
||||||
|
settings = db.query(SystemSettings).first()
|
||||||
|
conf = message.config.dict() if message.config else {"workers": ["gemini-3.5-flash-lite"]}
|
||||||
|
|
||||||
|
ai_resp = await run_orchestrator(db, history, settings, conf) # Transmission de DB
|
||||||
|
|
||||||
|
db.add(Message(role="assistant", content=ai_resp, project_id=project_id)); db.commit()
|
||||||
return db.query(Message).filter(Message.project_id == project_id).order_by(Message.created_at.asc()).all()
|
return db.query(Message).filter(Message.project_id == project_id).order_by(Message.created_at.asc()).all()
|
||||||
|
|
||||||
@app.post("/api/projects/{project_id}/messages", response_model=MessageResponse)
|
# --- ROUTES MODÈLES & FINANCES ---
|
||||||
def create_message(project_id: int, message: MessageCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
@app.get("/api/models/info")
|
||||||
"""Ajoute un message à un projet."""
|
def get_models_info(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
||||||
project = db.query(Project).filter(Project.id == project_id, Project.user_id == current_user.id).first()
|
settings = db.query(SystemSettings).first()
|
||||||
if not project:
|
return {
|
||||||
raise HTTPException(status_code=404, detail="Projet introuvable")
|
"last_sync_date": settings.last_sync_date.isoformat() if settings and settings.last_sync_date else None,
|
||||||
|
"last_sync_type": settings.last_sync_type if settings else None,
|
||||||
|
"models": db.query(AIModel).order_by(AIModel.name.asc()).all(),
|
||||||
|
"finances": db.query(FinancialLog).all()
|
||||||
|
}
|
||||||
|
|
||||||
new_message = Message(role=message.role, content=message.content, project_id=project_id)
|
@app.get("/api/finances")
|
||||||
db.add(new_message)
|
def get_finances(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
||||||
db.commit()
|
return db.query(FinancialLog).all()
|
||||||
db.refresh(new_message)
|
|
||||||
return new_message
|
@app.post("/api/models/sync")
|
||||||
|
async def trigger_model_sync(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
||||||
|
if not current_user.is_admin: raise HTTPException(status_code=403, detail="Accès admin requis.")
|
||||||
|
settings = db.query(SystemSettings).first()
|
||||||
|
return await sync_providers_models(db, settings, "Manuelle")
|
||||||
|
|
||||||
|
@app.get("/api/models/export")
|
||||||
|
def export_models(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
|
||||||
|
if not current_user.is_admin: raise HTTPException(status_code=403, detail="Accès admin requis.")
|
||||||
|
models = db.query(AIModel).all()
|
||||||
|
data = [{"provider": m.provider, "model_id": m.model_id, "name": m.name, "description_fr": m.description_fr, "domain": m.domain, "is_free": m.is_free, "context_length": m.context_length, "pricing_prompt": m.pricing_prompt, "pricing_completion": m.pricing_completion} for m in models]
|
||||||
|
return Response(content=json.dumps(data), media_type="application/json", headers={"Content-Disposition": "attachment; filename=aethas38_models.json"})
|
||||||
+45
-26
@@ -1,57 +1,76 @@
|
|||||||
from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey, Text
|
from sqlalchemy import Column, Integer, String, Boolean, ForeignKey, DateTime, Float
|
||||||
from sqlalchemy.orm import relationship
|
from sqlalchemy.orm import relationship
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from .database import Base
|
from .database import Base
|
||||||
|
|
||||||
class User(Base):
|
class User(Base):
|
||||||
__tablename__ = "users"
|
__tablename__ = "users"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
email = Column(String, unique=True, index=True, nullable=False)
|
email = Column(String, unique=True, index=True)
|
||||||
username = Column(String, unique=True, index=True, nullable=False)
|
username = Column(String, unique=True, index=True)
|
||||||
hashed_password = Column(String, nullable=False)
|
hashed_password = Column(String)
|
||||||
totp_secret = Column(String, nullable=False)
|
totp_secret = Column(String)
|
||||||
is_admin = Column(Boolean, default=False)
|
is_admin = Column(Boolean, default=False)
|
||||||
|
is_superadmin = Column(Boolean, default=False)
|
||||||
# Relation : Un utilisateur peut avoir plusieurs projets
|
avatar_path = Column(String, nullable=True)
|
||||||
projects = relationship("Project", back_populates="owner", cascade="all, delete-orphan")
|
projects = relationship("Project", back_populates="owner")
|
||||||
|
|
||||||
|
|
||||||
class Project(Base):
|
class Project(Base):
|
||||||
__tablename__ = "projects"
|
__tablename__ = "projects"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
title = Column(String, nullable=False)
|
title = Column(String, index=True)
|
||||||
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
||||||
is_pinned = Column(Boolean, default=False)
|
is_pinned = Column(Boolean, default=False)
|
||||||
user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
user_id = Column(Integer, ForeignKey("users.id"))
|
||||||
|
|
||||||
# Relations
|
|
||||||
owner = relationship("User", back_populates="projects")
|
owner = relationship("User", back_populates="projects")
|
||||||
messages = relationship("Message", back_populates="project", cascade="all, delete-orphan")
|
messages = relationship("Message", back_populates="project", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
|
||||||
class Message(Base):
|
class Message(Base):
|
||||||
__tablename__ = "messages"
|
__tablename__ = "messages"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
role = Column(String, nullable=False) # Ex: 'user', 'assistant', 'worker_1', 'system'
|
role = Column(String)
|
||||||
content = Column(Text, nullable=False)
|
content = Column(String)
|
||||||
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
||||||
project_id = Column(Integer, ForeignKey("projects.id"), nullable=False)
|
project_id = Column(Integer, ForeignKey("projects.id"))
|
||||||
|
|
||||||
# Relation
|
|
||||||
project = relationship("Project", back_populates="messages")
|
project = relationship("Project", back_populates="messages")
|
||||||
|
|
||||||
class SystemSettings(Base):
|
class SystemSettings(Base):
|
||||||
__tablename__ = "system_settings"
|
__tablename__ = "system_settings"
|
||||||
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
# Serveur Mail (Obligatoire)
|
|
||||||
smtp_host = Column(String, nullable=False)
|
smtp_host = Column(String, nullable=False)
|
||||||
smtp_port = Column(Integer, nullable=False)
|
smtp_port = Column(Integer, nullable=False)
|
||||||
smtp_user = Column(String, nullable=False)
|
smtp_user = Column(String, nullable=False)
|
||||||
smtp_password = Column(String, nullable=False)
|
smtp_password = Column(String, nullable=False)
|
||||||
# Clés API (Optionnelles)
|
|
||||||
gemini_api_key = Column(String, nullable=True)
|
|
||||||
openrouter_api_key = Column(String, nullable=True)
|
openrouter_api_key = Column(String, nullable=True)
|
||||||
|
openrouter_management_key = Column(String, nullable=True)
|
||||||
|
groq_api_key = Column(String, nullable=True)
|
||||||
|
gemini_api_key = Column(String, nullable=True)
|
||||||
|
deepseek_api_key = Column(String, nullable=True)
|
||||||
|
mistral_api_key = Column(String, nullable=True)
|
||||||
|
cloudflare_account_id = Column(String, nullable=True)
|
||||||
|
cloudflare_api_token = Column(String, nullable=True)
|
||||||
|
huggingface_api_key = Column(String, nullable=True)
|
||||||
|
last_sync_date = Column(DateTime, nullable=True)
|
||||||
|
last_sync_type = Column(String, nullable=True)
|
||||||
|
|
||||||
|
class AIModel(Base):
|
||||||
|
__tablename__ = "ai_models"
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
provider = Column(String, index=True)
|
||||||
|
model_id = Column(String, unique=True, index=True)
|
||||||
|
name = Column(String)
|
||||||
|
description_fr = Column(String, nullable=True)
|
||||||
|
domain = Column(String, default="Texte")
|
||||||
|
is_free = Column(Boolean, default=False)
|
||||||
|
context_length = Column(Integer)
|
||||||
|
pricing_prompt = Column(Float)
|
||||||
|
pricing_completion = Column(Float)
|
||||||
|
last_updated = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
||||||
|
|
||||||
|
class FinancialLog(Base):
|
||||||
|
__tablename__ = "financial_logs"
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
provider = Column(String, unique=True, index=True)
|
||||||
|
balance = Column(Float, default=0.0)
|
||||||
|
total_usage = Column(Float, default=0.0)
|
||||||
|
checked_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
|
||||||
@@ -0,0 +1,244 @@
|
|||||||
|
import asyncio
|
||||||
|
import httpx
|
||||||
|
from openai import AsyncOpenAI
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from sqlalchemy.exc import IntegrityError
|
||||||
|
from .models import SystemSettings, AIModel, FinancialLog
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
def determine_domain(model_id: str) -> str:
|
||||||
|
mid = model_id.lower()
|
||||||
|
if "vision" in mid or "vl" in mid or "omni" in mid: return "Vision & Texte"
|
||||||
|
if "coder" in mid or "code" in mid or "math" in mid: return "Code & Logique"
|
||||||
|
if "audio" in mid or "whisper" in mid: return "Audio"
|
||||||
|
return "Texte Polyvalent"
|
||||||
|
|
||||||
|
async def sync_finances(db: Session, settings: SystemSettings):
|
||||||
|
"""Interroge les fournisseurs pour récupérer le solde financier exact."""
|
||||||
|
async with httpx.AsyncClient(timeout=30.0) as client:
|
||||||
|
# OpenRouter
|
||||||
|
if settings.openrouter_management_key or settings.openrouter_api_key:
|
||||||
|
try:
|
||||||
|
key = settings.openrouter_management_key or settings.openrouter_api_key
|
||||||
|
cred_resp = await client.get("https://openrouter.ai/api/v1/credits", headers={"Authorization": f"Bearer {key}"})
|
||||||
|
balance = 0.0
|
||||||
|
usage = 0.0
|
||||||
|
if cred_resp.status_code == 200 and cred_resp.json().get("data"):
|
||||||
|
c_data = cred_resp.json().get("data", {})
|
||||||
|
balance = float(c_data.get("total_credits") or 0.0) - float(c_data.get("total_usage") or 0.0)
|
||||||
|
usage = float(c_data.get("total_usage") or 0.0)
|
||||||
|
else:
|
||||||
|
key_resp = await client.get("https://openrouter.ai/api/v1/auth/key", headers={"Authorization": f"Bearer {key}"})
|
||||||
|
if key_resp.status_code == 200:
|
||||||
|
data = key_resp.json().get("data", {})
|
||||||
|
limit = data.get("limit")
|
||||||
|
usage = float(data.get("usage") or 0.0)
|
||||||
|
balance = (float(limit) - usage) if limit is not None else -usage
|
||||||
|
update_finance_db(db, "OpenRouter", balance, usage)
|
||||||
|
except Exception as e: print(f"Erreur Finance OR: {e}")
|
||||||
|
|
||||||
|
# Groq
|
||||||
|
if settings.groq_api_key: update_finance_db(db, "Groq", 999.0, 0.0)
|
||||||
|
|
||||||
|
# DeepSeek
|
||||||
|
if settings.deepseek_api_key:
|
||||||
|
try:
|
||||||
|
resp = await client.get("https://api.deepseek.com/user/balance", headers={"Authorization": f"Bearer {settings.deepseek_api_key}"})
|
||||||
|
if resp.status_code == 200:
|
||||||
|
infos = resp.json().get("balance_infos", [{}])[0]
|
||||||
|
update_finance_db(db, "DeepSeek", float(infos.get("total_balance", 0)), 0.0)
|
||||||
|
except Exception: pass
|
||||||
|
|
||||||
|
# Mistral AI
|
||||||
|
if settings.mistral_api_key: update_finance_db(db, "Mistral", 0.0, 0.0)
|
||||||
|
|
||||||
|
# Gemini
|
||||||
|
if settings.gemini_api_key: update_finance_db(db, "Gemini", 0.0, 0.0)
|
||||||
|
|
||||||
|
try: db.commit()
|
||||||
|
except: db.rollback()
|
||||||
|
|
||||||
|
def update_finance_db(db, provider, balance, usage):
|
||||||
|
try:
|
||||||
|
log = db.query(FinancialLog).filter(FinancialLog.provider == provider).first()
|
||||||
|
if log:
|
||||||
|
log.balance = balance; log.total_usage = usage; log.checked_at = datetime.now(timezone.utc)
|
||||||
|
else:
|
||||||
|
db.add(FinancialLog(provider=provider, balance=balance, total_usage=usage))
|
||||||
|
except Exception as e: print(f"Finance DB Error: {e}")
|
||||||
|
|
||||||
|
async def sync_providers_models(db: Session, settings: SystemSettings, sync_type: str = "Automatique"):
|
||||||
|
added = 0
|
||||||
|
# On stocke les modèles en mémoire avant de les envoyer en base pour éviter les doublons
|
||||||
|
models_to_process = {}
|
||||||
|
|
||||||
|
async with httpx.AsyncClient(timeout=90.0) as client:
|
||||||
|
# 1. OpenRouter
|
||||||
|
if settings.openrouter_api_key:
|
||||||
|
try:
|
||||||
|
resp = await client.get("https://openrouter.ai/api/v1/models")
|
||||||
|
if resp.status_code == 200:
|
||||||
|
for item in resp.json().get("data", []):
|
||||||
|
try:
|
||||||
|
m_id = item.get("id")
|
||||||
|
if not m_id: continue
|
||||||
|
pricing = item.get("pricing") or {}
|
||||||
|
try: pp = float(pricing.get("prompt") or 0.0) * 1000000
|
||||||
|
except: pp = 0.0
|
||||||
|
try: pc = float(pricing.get("completion") or 0.0) * 1000000
|
||||||
|
except: pc = 0.0
|
||||||
|
is_free = (pp == 0.0 and pc == 0.0)
|
||||||
|
desc = item.get("description", "Modèle OpenRouter.")[:200] + "..."
|
||||||
|
models_to_process[m_id] = {"provider": "openrouter", "name": item.get("name", "Inconnu"), "desc": desc, "domain": determine_domain(m_id), "is_free": is_free, "ctx": item.get("context_length", 0), "pp": pp, "pc": pc}
|
||||||
|
except: pass
|
||||||
|
except Exception as e: print(f"Erreur OR Models: {e}")
|
||||||
|
|
||||||
|
# 2. Groq
|
||||||
|
if settings.groq_api_key:
|
||||||
|
try:
|
||||||
|
resp = await client.get("https://api.groq.com/openai/v1/models", headers={"Authorization": f"Bearer {settings.groq_api_key}"})
|
||||||
|
if resp.status_code == 200:
|
||||||
|
for item in resp.json().get("data", []):
|
||||||
|
try:
|
||||||
|
m_id = item["id"]
|
||||||
|
models_to_process[m_id] = {"provider": "groq", "name": m_id.capitalize(), "desc": "Modèle rapide LPU Groq.", "domain": determine_domain(m_id), "is_free": True, "ctx": 8192, "pp": 0.0, "pc": 0.0}
|
||||||
|
except: pass
|
||||||
|
except Exception: pass
|
||||||
|
|
||||||
|
# 3. DeepSeek
|
||||||
|
if settings.deepseek_api_key:
|
||||||
|
try:
|
||||||
|
resp = await client.get("https://api.deepseek.com/models", headers={"Authorization": f"Bearer {settings.deepseek_api_key}"})
|
||||||
|
if resp.status_code == 200:
|
||||||
|
for item in resp.json().get("data", []):
|
||||||
|
try:
|
||||||
|
m_id = item["id"]
|
||||||
|
models_to_process[m_id] = {"provider": "deepseek", "name": m_id.capitalize(), "desc": "Modèle officiel DeepSeek.", "domain": determine_domain(m_id), "is_free": False, "ctx": 64000, "pp": 0.14, "pc": 0.28}
|
||||||
|
except: pass
|
||||||
|
except Exception: pass
|
||||||
|
|
||||||
|
# 4. Mistral
|
||||||
|
if settings.mistral_api_key:
|
||||||
|
try:
|
||||||
|
resp = await client.get("https://api.mistral.ai/v1/models", headers={"Authorization": f"Bearer {settings.mistral_api_key}"})
|
||||||
|
if resp.status_code == 200:
|
||||||
|
for item in resp.json().get("data", []):
|
||||||
|
try:
|
||||||
|
m_id = item["id"]
|
||||||
|
models_to_process[m_id] = {"provider": "mistral", "name": m_id.capitalize(), "desc": "Modèle officiel Mistral AI.", "domain": determine_domain(m_id), "is_free": False, "ctx": 32000, "pp": 0.2, "pc": 0.6}
|
||||||
|
except: pass
|
||||||
|
except Exception: pass
|
||||||
|
|
||||||
|
# 5. Gemini (Google)
|
||||||
|
if settings.gemini_api_key:
|
||||||
|
try:
|
||||||
|
resp = await client.get(f"https://generativelanguage.googleapis.com/v1beta/models?key={settings.gemini_api_key}")
|
||||||
|
if resp.status_code == 200:
|
||||||
|
for item in resp.json().get("models", []):
|
||||||
|
try:
|
||||||
|
m_id = item["name"].replace("models/", "")
|
||||||
|
desc = item.get("description", "Modèle Google Gemini.")[:200] + "..."
|
||||||
|
models_to_process[m_id] = {"provider": "gemini", "name": item.get("displayName", m_id), "desc": desc, "domain": determine_domain(m_id), "is_free": True, "ctx": item.get("inputTokenLimit", 32000), "pp": 0.0, "pc": 0.0}
|
||||||
|
except: pass
|
||||||
|
except Exception: pass
|
||||||
|
|
||||||
|
# 6. Cloudflare
|
||||||
|
if settings.cloudflare_account_id and settings.cloudflare_api_token:
|
||||||
|
try:
|
||||||
|
url = f"https://api.cloudflare.com/client/v4/accounts/{settings.cloudflare_account_id}/ai/models/search"
|
||||||
|
resp = await client.get(url, headers={"Authorization": f"Bearer {settings.cloudflare_api_token}"})
|
||||||
|
if resp.status_code == 200:
|
||||||
|
for item in resp.json().get("result", []):
|
||||||
|
try:
|
||||||
|
m_id = item.get("name")
|
||||||
|
desc = item.get("description", "Modèle Cloudflare Workers AI.")[:200] + "..."
|
||||||
|
models_to_process[m_id] = {"provider": "cloudflare", "name": m_id.split("/")[-1], "desc": desc, "domain": determine_domain(m_id), "is_free": True, "ctx": 4096, "pp": 0.0, "pc": 0.0}
|
||||||
|
except: pass
|
||||||
|
except Exception: pass
|
||||||
|
|
||||||
|
# --- Phase d'enregistrement sécurisée ---
|
||||||
|
for m_id, data in models_to_process.items():
|
||||||
|
try:
|
||||||
|
existing = db.query(AIModel).filter(AIModel.model_id == m_id).first()
|
||||||
|
if existing:
|
||||||
|
existing.pricing_prompt = data["pp"]; existing.pricing_completion = data["pc"]; existing.is_free = data["is_free"]; existing.last_updated = datetime.now(timezone.utc)
|
||||||
|
else:
|
||||||
|
db.add(AIModel(provider=data["provider"], model_id=m_id, name=data["name"], description_fr=data["desc"], domain=data["domain"], is_free=data["is_free"], context_length=data["ctx"], pricing_prompt=data["pp"], pricing_completion=data["pc"]))
|
||||||
|
added += 1
|
||||||
|
# Commit très fréquent pour éviter les gros blocs qui plantent
|
||||||
|
if added % 50 == 0:
|
||||||
|
db.commit()
|
||||||
|
except IntegrityError:
|
||||||
|
db.rollback() # Si conflit, on annule cette insertion et on continue
|
||||||
|
except Exception:
|
||||||
|
db.rollback()
|
||||||
|
|
||||||
|
try:
|
||||||
|
settings.last_sync_date = datetime.now(timezone.utc)
|
||||||
|
settings.last_sync_type = sync_type
|
||||||
|
db.commit()
|
||||||
|
except Exception as e:
|
||||||
|
db.rollback()
|
||||||
|
print(f"Erreur DB Commit Sync: {e}")
|
||||||
|
|
||||||
|
await sync_finances(db, settings)
|
||||||
|
return {"status": "success", "models_processed": added}
|
||||||
|
|
||||||
|
def get_client_for_model(db: Session, model_id: str, settings: SystemSettings):
|
||||||
|
"""Récupère dynamiquement le bon client OpenAI en fonction du fournisseur du modèle."""
|
||||||
|
model_db = db.query(AIModel).filter(AIModel.model_id == model_id).first()
|
||||||
|
provider = model_db.provider if model_db else "openrouter"
|
||||||
|
|
||||||
|
if provider == "gemini" and settings.gemini_api_key:
|
||||||
|
return AsyncOpenAI(base_url="https://generativelanguage.googleapis.com/v1beta/openai/", api_key=settings.gemini_api_key), "gemini"
|
||||||
|
elif provider == "groq" and settings.groq_api_key:
|
||||||
|
return AsyncOpenAI(base_url="https://api.groq.com/openai/v1", api_key=settings.groq_api_key), "groq"
|
||||||
|
elif provider == "deepseek" and settings.deepseek_api_key:
|
||||||
|
return AsyncOpenAI(base_url="https://api.deepseek.com/v1", api_key=settings.deepseek_api_key), "deepseek"
|
||||||
|
elif provider == "mistral" and settings.mistral_api_key:
|
||||||
|
return AsyncOpenAI(base_url="https://api.mistral.ai/v1", api_key=settings.mistral_api_key), "mistral"
|
||||||
|
elif provider == "cloudflare" and settings.cloudflare_account_id and settings.cloudflare_api_token:
|
||||||
|
return AsyncOpenAI(base_url=f"https://api.cloudflare.com/client/v4/accounts/{settings.cloudflare_account_id}/ai/v1", api_key=settings.cloudflare_api_token), "cloudflare"
|
||||||
|
|
||||||
|
return AsyncOpenAI(base_url="https://openrouter.ai/api/v1", api_key=settings.openrouter_api_key), "openrouter"
|
||||||
|
|
||||||
|
async def ask_agent(client, model_id, messages, provider="openrouter"):
|
||||||
|
kwargs = {"model": model_id, "messages": messages}
|
||||||
|
if provider == "openrouter":
|
||||||
|
kwargs["extra_headers"] = {"HTTP-Referer": "https://aethas38.duckdns.org", "X-Title": "AETHAS38 Orchestrator"}
|
||||||
|
resp = await client.chat.completions.create(**kwargs)
|
||||||
|
return resp.choices[0].message.content
|
||||||
|
|
||||||
|
async def run_orchestrator(db: Session, history: list, settings: SystemSettings, config: dict) -> str:
|
||||||
|
workers = config.get("workers", ["gemini-3.5-flash-lite"])
|
||||||
|
user_prompt = history[-1].content
|
||||||
|
formatted_history = [{"role": msg.role, "content": msg.content} for msg in history[:-1]]
|
||||||
|
|
||||||
|
final_response = ""
|
||||||
|
try:
|
||||||
|
if len(workers) == 1:
|
||||||
|
w_mod = workers[0]
|
||||||
|
client, provider = get_client_for_model(db, w_mod, settings)
|
||||||
|
final_response = await ask_agent(client, w_mod, formatted_history + [{"role": "user", "content": user_prompt}], provider)
|
||||||
|
else:
|
||||||
|
p_mod = config.get("prompter", "gemini-3.5-flash-lite")
|
||||||
|
p_client, p_prov = get_client_for_model(db, p_mod, settings)
|
||||||
|
optimized = await ask_agent(p_client, p_mod, [{"role": "system", "content": "Optimise cette requête."}, {"role": "user", "content": user_prompt}], p_prov)
|
||||||
|
|
||||||
|
w_tasks = []
|
||||||
|
for w in workers:
|
||||||
|
w_client, w_prov = get_client_for_model(db, w, settings)
|
||||||
|
w_tasks.append(ask_agent(w_client, w, formatted_history + [{"role": "user", "content": optimized}], w_prov))
|
||||||
|
|
||||||
|
responses = await asyncio.gather(*w_tasks, return_exceptions=True)
|
||||||
|
|
||||||
|
c_mod = config.get("concatenator", "gemini-3.5-flash-lite")
|
||||||
|
c_client, c_prov = get_client_for_model(db, c_mod, settings)
|
||||||
|
synth = f"Requête: {user_prompt}\n\n" + "\n".join([f"--- EXPERT {i+1} ---\n{r}" for i, r in enumerate(responses)]) + "\n\nFais une synthèse finale."
|
||||||
|
final_response = await ask_agent(c_client, c_mod, [{"role": "user", "content": synth}], c_prov)
|
||||||
|
except Exception as e:
|
||||||
|
final_response = f"L'IA a rencontré une erreur critique: {str(e)}"
|
||||||
|
|
||||||
|
await sync_finances(db, settings)
|
||||||
|
return final_response
|
||||||
+23
-13
@@ -1,52 +1,62 @@
|
|||||||
from pydantic import BaseModel, EmailStr
|
from pydantic import BaseModel, EmailStr
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Optional
|
from typing import Optional, List
|
||||||
|
|
||||||
class AdminCreate(BaseModel):
|
class AdminCreate(BaseModel):
|
||||||
email: EmailStr
|
email: EmailStr
|
||||||
username: str
|
username: str
|
||||||
password: str
|
password: str
|
||||||
# Serveur Mail (Obligatoire)
|
|
||||||
smtp_host: str
|
smtp_host: str
|
||||||
smtp_port: int
|
smtp_port: int
|
||||||
smtp_user: str
|
smtp_user: str
|
||||||
smtp_password: str
|
smtp_password: str
|
||||||
# Clés API (Optionnelles)
|
|
||||||
gemini_api_key: Optional[str] = None
|
|
||||||
openrouter_api_key: Optional[str] = None
|
openrouter_api_key: Optional[str] = None
|
||||||
|
openrouter_management_key: Optional[str] = None
|
||||||
|
groq_api_key: Optional[str] = None
|
||||||
|
gemini_api_key: Optional[str] = None
|
||||||
|
deepseek_api_key: Optional[str] = None
|
||||||
|
mistral_api_key: Optional[str] = None
|
||||||
|
cloudflare_account_id: Optional[str] = None
|
||||||
|
cloudflare_api_token: Optional[str] = None
|
||||||
|
huggingface_api_key: Optional[str] = None
|
||||||
|
|
||||||
class LoginRequest(BaseModel):
|
class LoginRequest(BaseModel):
|
||||||
username: str
|
username: str
|
||||||
password: str
|
password: str
|
||||||
totp_code: str
|
totp_code: str
|
||||||
|
|
||||||
# --- NOUVEAU : Schémas pour les Projets ---
|
|
||||||
class ProjectBase(BaseModel):
|
class ProjectBase(BaseModel):
|
||||||
title: str
|
title: str
|
||||||
|
|
||||||
class ProjectCreate(ProjectBase):
|
class ProjectCreate(ProjectBase): pass
|
||||||
pass
|
|
||||||
|
|
||||||
class ProjectResponse(ProjectBase):
|
class ProjectResponse(ProjectBase):
|
||||||
id: int
|
id: int
|
||||||
created_at: datetime
|
created_at: datetime
|
||||||
is_pinned: bool
|
is_pinned: bool
|
||||||
|
class Config: from_attributes = True
|
||||||
|
|
||||||
class Config:
|
class ProjectRename(BaseModel):
|
||||||
from_attributes = True
|
title: str
|
||||||
|
|
||||||
|
class OrchestratorConfig(BaseModel):
|
||||||
|
workers: List[str]
|
||||||
|
prompter: Optional[str] = "gemini-3.5-flash-lite"
|
||||||
|
concatenator: Optional[str] = "gemini-3.5-flash-lite"
|
||||||
|
|
||||||
# --- NOUVEAU : Schémas pour les Messages ---
|
|
||||||
class MessageBase(BaseModel):
|
class MessageBase(BaseModel):
|
||||||
role: str
|
role: str
|
||||||
content: str
|
content: str
|
||||||
|
|
||||||
class MessageCreate(MessageBase):
|
class MessageCreate(MessageBase):
|
||||||
pass
|
config: Optional[OrchestratorConfig] = None
|
||||||
|
|
||||||
class MessageResponse(MessageBase):
|
class MessageResponse(MessageBase):
|
||||||
id: int
|
id: int
|
||||||
created_at: datetime
|
created_at: datetime
|
||||||
project_id: int
|
project_id: int
|
||||||
|
class Config: from_attributes = True
|
||||||
|
|
||||||
class ProjectRename(BaseModel):
|
class PasswordChange(BaseModel):
|
||||||
title: str
|
old_password: str
|
||||||
|
new_password: str
|
||||||
+383
-190
@@ -6,10 +6,7 @@
|
|||||||
<title>AETHAS38 - Dashboard</title>
|
<title>AETHAS38 - Dashboard</title>
|
||||||
<script src="https://cdn.tailwindcss.com"></script>
|
<script src="https://cdn.tailwindcss.com"></script>
|
||||||
<script>
|
<script>
|
||||||
tailwind.config = {
|
tailwind.config = { darkMode: 'class', theme: { extend: { colors: { aethas: { dark: '#0f172a', panel: '#1e293b', cyan: '#06b6d4', purple: '#a855f7' } } } } }
|
||||||
darkMode: 'class',
|
|
||||||
theme: { extend: { colors: { aethas: { dark: '#0f172a', panel: '#1e293b', cyan: '#06b6d4', purple: '#a855f7' } } } }
|
|
||||||
}
|
|
||||||
</script>
|
</script>
|
||||||
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
|
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
|
||||||
<script src="https://unpkg.com/lucide@latest"></script>
|
<script src="https://unpkg.com/lucide@latest"></script>
|
||||||
@@ -17,120 +14,220 @@
|
|||||||
body { background-color: #0f172a; color: #f8fafc; font-family: 'Inter', sans-serif; }
|
body { background-color: #0f172a; color: #f8fafc; font-family: 'Inter', sans-serif; }
|
||||||
.neon-text { background: linear-gradient(to right, #06b6d4, #a855f7); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
|
.neon-text { background: linear-gradient(to right, #06b6d4, #a855f7); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
|
||||||
::-webkit-scrollbar { width: 6px; }
|
::-webkit-scrollbar { width: 6px; }
|
||||||
::-webkit-scrollbar-track { background: transparent; }
|
|
||||||
::-webkit-scrollbar-thumb { background: #334155; border-radius: 10px; }
|
::-webkit-scrollbar-thumb { background: #334155; border-radius: 10px; }
|
||||||
|
.custom-scrollbar::-webkit-scrollbar { width: 4px; }
|
||||||
|
.custom-scrollbar::-webkit-scrollbar-thumb { background: #334155; border-radius: 4px; }
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body class="h-screen flex overflow-hidden">
|
<body class="h-screen flex overflow-hidden">
|
||||||
|
|
||||||
<div id="app" class="flex w-full h-full relative bg-aethas-dark">
|
<div id="app" class="flex w-full h-full relative bg-aethas-dark">
|
||||||
<div v-if="isSidebarOpen" @click="toggleSidebar" class="md:hidden fixed inset-0 bg-black/60 z-40 transition-opacity"></div>
|
|
||||||
|
<!-- MODAL PARAMÈTRES -->
|
||||||
|
<div v-if="isSettingsModalOpen" class="fixed inset-0 bg-black/80 z-[100] flex items-center justify-center p-4">
|
||||||
|
<div class="bg-aethas-panel border border-gray-600 rounded-2xl w-full max-w-md overflow-hidden shadow-[0_0_30px_rgba(0,0,0,0.7)]">
|
||||||
|
<div class="p-4 border-b border-gray-700 flex justify-between items-center bg-gray-800/50">
|
||||||
|
<h2 class="text-lg font-bold text-white flex items-center gap-2"><i data-lucide="settings" class="w-5 h-5 text-aethas-cyan"></i> Paramètres</h2>
|
||||||
|
<button @click="closeSettings" class="text-gray-400 hover:text-white"><i data-lucide="x" class="w-5 h-5"></i></button>
|
||||||
|
</div>
|
||||||
|
<div class="p-6 space-y-4">
|
||||||
|
<h3 class="text-sm font-semibold text-aethas-cyan uppercase tracking-wider mb-2">Sécurité du compte</h3>
|
||||||
|
<div v-if="settingsMessage" :class="['p-3 rounded text-sm text-center', settingsMessage.includes('succès') ? 'bg-green-900/50 text-green-200 border border-green-500' : 'bg-red-900/50 text-red-200 border border-red-500']">{{ settingsMessage }}</div>
|
||||||
|
<div><label class="block text-sm text-gray-300 mb-1">Ancien mot de passe</label><input v-model="passForm.old" type="password" class="w-full bg-aethas-dark border border-gray-600 rounded-lg px-4 py-2 focus:border-aethas-cyan focus:outline-none"></div>
|
||||||
|
<div><label class="block text-sm text-gray-300 mb-1">Nouveau mot de passe</label><input v-model="passForm.new" type="password" class="w-full bg-aethas-dark border border-gray-600 rounded-lg px-4 py-2 focus:border-aethas-cyan focus:outline-none"></div>
|
||||||
|
<div><label class="block text-sm text-gray-300 mb-1">Confirmer</label><input v-model="passForm.confirm" type="password" class="w-full bg-aethas-dark border border-gray-600 rounded-lg px-4 py-2 focus:border-aethas-cyan focus:outline-none"></div>
|
||||||
|
<button @click="changePassword" :disabled="isSavingSettings" class="w-full mt-4 bg-gray-700 hover:bg-gray-600 text-white font-semibold py-2.5 px-4 rounded-lg transition-colors border border-gray-500 disabled:opacity-50">
|
||||||
|
<span v-if="isSavingSettings">Mise à jour...</span><span v-else>Modifier</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- BARRE LATÉRALE -->
|
<!-- BARRE LATÉRALE -->
|
||||||
<div :class="['transition-all duration-300 flex-shrink-0 relative z-50', isSidebarOpen ? 'w-72' : 'w-0']">
|
<div :class="['transition-all duration-300 flex-shrink-0 relative z-50 flex flex-col', isSidebarOpen ? 'w-72' : 'w-0']">
|
||||||
<aside :class="['absolute top-0 left-0 h-full w-72 bg-aethas-panel border-r border-gray-700 flex flex-col transition-transform duration-300', isSidebarOpen ? 'translate-x-0' : '-translate-x-full']">
|
<aside :class="['absolute top-0 left-0 h-full w-72 bg-aethas-panel border-r border-gray-700 flex flex-col transition-transform duration-300', isSidebarOpen ? 'translate-x-0' : '-translate-x-full']">
|
||||||
<div class="p-4 border-b border-gray-700 flex items-center justify-between">
|
<div class="p-4 border-b border-gray-700 flex items-center justify-between">
|
||||||
<div class="flex items-center gap-3">
|
<div class="flex items-center gap-3">
|
||||||
<img src="/static/logo.png" alt="Logo" class="w-10 h-10 rounded-full border border-aethas-cyan object-cover bg-gray-800 flex-shrink-0">
|
<img src="/assets/logo.png" class="w-10 h-10 rounded-full border border-aethas-cyan object-cover bg-gray-800">
|
||||||
<span class="font-bold text-lg tracking-wider neon-text">AETHAS38</span>
|
<span class="font-bold text-lg tracking-wider neon-text">AETHAS38</span>
|
||||||
</div>
|
</div>
|
||||||
<button @click="toggleSidebar" class="md:hidden text-gray-400 hover:text-white"><i data-lucide="x" class="w-5 h-5"></i></button>
|
<button @click="toggleSidebar" class="md:hidden text-gray-400 hover:text-white"><i data-lucide="x" class="w-5 h-5"></i></button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="p-4">
|
<div class="p-4 space-y-2">
|
||||||
<button @click="createNewProject" :disabled="isLoading" class="w-full bg-gray-800 hover:bg-gray-700 text-white border border-gray-600 rounded-lg py-2.5 px-4 flex items-center justify-center gap-2 transition-colors disabled:opacity-50 shadow-md">
|
<button @click="createNewProject" :disabled="isLoading" class="w-full bg-gray-800 hover:bg-gray-700 text-white border border-gray-600 rounded-lg py-2 px-4 flex items-center justify-center gap-2 shadow-md">
|
||||||
<i data-lucide="plus" class="w-5 h-5 text-aethas-cyan"></i> Nouveau Projet IA
|
<i data-lucide="plus" class="w-4 h-4 text-aethas-cyan"></i> Nouveau Projet
|
||||||
|
</button>
|
||||||
|
<button v-if="user.is_admin" @click="activeView = 'models'" :class="['w-full border rounded-lg py-2 px-4 flex items-center justify-center gap-2 transition-colors', activeView === 'models' ? 'bg-aethas-cyan/10 border-aethas-cyan text-aethas-cyan' : 'bg-aethas-dark hover:bg-gray-800 text-gray-300 border-gray-700']">
|
||||||
|
<i data-lucide="database" class="w-4 h-4"></i> Modèles & Finances
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="flex-1 overflow-y-auto p-4 space-y-6">
|
<div class="flex-1 overflow-y-auto p-4 space-y-6 custom-scrollbar">
|
||||||
<!-- Projets Épinglés -->
|
|
||||||
<div v-if="pinnedProjects.length > 0">
|
<div v-if="pinnedProjects.length > 0">
|
||||||
<h3 class="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-3">Épinglés</h3>
|
<h3 class="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-2">Épinglés</h3>
|
||||||
<ul class="space-y-1">
|
<ul class="space-y-1">
|
||||||
<li v-for="project in pinnedProjects" :key="project.id" @click="selectProject(project)" :class="['group flex items-center justify-between p-2 rounded cursor-pointer text-sm transition-colors', activeProject && activeProject.id === project.id ? 'bg-gray-700 text-white' : 'hover:bg-gray-800 text-gray-300']">
|
<li v-for="project in pinnedProjects" :key="project.id" @click="selectProject(project)" :class="['group flex items-center justify-between p-2 rounded cursor-pointer text-sm', activeView === 'chat' && activeProject && activeProject.id === project.id ? 'bg-gray-700 text-white' : 'hover:bg-gray-800 text-gray-300']">
|
||||||
<div class="flex items-center gap-2 truncate">
|
<div class="flex items-center gap-2 truncate"><i data-lucide="pin" class="w-3 h-3 text-aethas-cyan"></i><span class="truncate">{{ project.title }}</span></div>
|
||||||
<i data-lucide="pin" class="w-4 h-4 text-aethas-cyan fill-aethas-cyan flex-shrink-0"></i>
|
<div class="hidden group-hover:flex items-center gap-1 bg-gray-800 pl-2 rounded">
|
||||||
<span class="truncate">{{ project.title }}</span>
|
<button @click.stop="togglePin(project.id)" class="text-gray-400 hover:text-white"><i data-lucide="pin-off" class="w-3.5 h-3.5"></i></button>
|
||||||
</div>
|
<button @click.stop="deleteProject(project.id)" class="text-red-500 hover:text-red-400"><i data-lucide="trash-2" class="w-3.5 h-3.5"></i></button>
|
||||||
<div class="hidden group-hover:flex items-center gap-1 flex-shrink-0 bg-gray-800 pl-2 rounded">
|
|
||||||
<button @click.stop="renameProject(project)" class="text-gray-400 hover:text-aethas-cyan p-1 rounded hover:bg-gray-700" title="Renommer"><i data-lucide="edit-2" class="w-3.5 h-3.5"></i></button>
|
|
||||||
<button @click.stop="togglePin(project.id)" class="text-gray-400 hover:text-white p-1 rounded hover:bg-gray-700" title="Désépingler"><i data-lucide="pin-off" class="w-3.5 h-3.5"></i></button>
|
|
||||||
<button @click.stop="deleteProject(project.id)" class="text-gray-400 hover:text-red-400 p-1 rounded hover:bg-gray-700" title="Supprimer"><i data-lucide="trash-2" class="w-3.5 h-3.5"></i></button>
|
|
||||||
</div>
|
</div>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Projets Récents -->
|
|
||||||
<div>
|
<div>
|
||||||
<h3 class="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-3">Récents</h3>
|
<h3 class="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-2">Récents</h3>
|
||||||
<ul class="space-y-1">
|
<ul class="space-y-1">
|
||||||
<li v-if="recentProjects.length === 0 && pinnedProjects.length === 0" class="text-sm text-gray-500 italic p-2">Aucun projet.</li>
|
<li v-for="project in recentProjects" :key="project.id" @click="selectProject(project)" :class="['group flex items-center justify-between p-2 rounded cursor-pointer text-sm', activeView === 'chat' && activeProject && activeProject.id === project.id ? 'bg-gray-700 text-white' : 'hover:bg-gray-800 text-gray-300']">
|
||||||
<li v-for="project in recentProjects" :key="project.id" @click="selectProject(project)" :class="['group flex items-center justify-between p-2 rounded cursor-pointer text-sm transition-colors', activeProject && activeProject.id === project.id ? 'bg-gray-700 text-white' : 'hover:bg-gray-800 text-gray-300']">
|
<div class="flex items-center gap-2 truncate"><i data-lucide="message-square" class="w-3 h-3 text-gray-500"></i><span class="truncate">{{ project.title }}</span></div>
|
||||||
<div class="flex items-center gap-2 truncate">
|
<div class="hidden group-hover:flex items-center gap-1 bg-gray-800 pl-2 rounded">
|
||||||
<i data-lucide="message-square" class="w-4 h-4 text-gray-500 flex-shrink-0"></i>
|
<button @click.stop="renameProject(project)" class="text-gray-400 hover:text-aethas-cyan"><i data-lucide="edit-2" class="w-3.5 h-3.5"></i></button>
|
||||||
<span class="truncate">{{ project.title }}</span>
|
<button @click.stop="togglePin(project.id)" class="text-gray-400 hover:text-white"><i data-lucide="pin" class="w-3.5 h-3.5"></i></button>
|
||||||
</div>
|
<button @click.stop="deleteProject(project.id)" class="text-gray-400 hover:text-red-400"><i data-lucide="trash-2" class="w-3.5 h-3.5"></i></button>
|
||||||
<div class="hidden group-hover:flex items-center gap-1 flex-shrink-0 bg-gray-800 pl-2 rounded">
|
|
||||||
<button @click.stop="renameProject(project)" class="text-gray-400 hover:text-aethas-cyan p-1 rounded hover:bg-gray-700" title="Renommer"><i data-lucide="edit-2" class="w-3.5 h-3.5"></i></button>
|
|
||||||
<button @click.stop="togglePin(project.id)" class="text-gray-400 hover:text-white p-1 rounded hover:bg-gray-700" title="Épingler"><i data-lucide="pin" class="w-3.5 h-3.5"></i></button>
|
|
||||||
<button @click.stop="deleteProject(project.id)" class="text-gray-400 hover:text-red-400 p-1 rounded hover:bg-gray-700" title="Supprimer"><i data-lucide="trash-2" class="w-3.5 h-3.5"></i></button>
|
|
||||||
</div>
|
</div>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="p-4 border-t border-gray-700 flex items-center gap-2">
|
<!-- ENCART FINANCIER -->
|
||||||
<div class="w-8 h-8 rounded-full bg-gradient-to-tr from-aethas-cyan to-aethas-purple flex items-center justify-center text-sm font-bold shadow-md">{{ username.charAt(0).toUpperCase() }}</div>
|
<div class="px-4 pb-2 border-b border-gray-700">
|
||||||
<span class="text-sm font-medium">{{ username }}</span>
|
<div v-if="financesList.length > 0" class="flex flex-col gap-1.5 mb-2">
|
||||||
|
<div v-for="fin in financesList" :key="fin.provider" class="text-[10px] bg-gray-800/80 border border-gray-600/50 px-2 py-1.5 rounded flex justify-between items-center shadow-inner">
|
||||||
|
<span class="text-gray-400 capitalize">{{ fin.provider }}</span>
|
||||||
|
<span :class="fin.balance > 0 ? 'text-green-400 font-bold' : 'text-aethas-cyan'">${{ fin.balance > 0 ? fin.balance.toFixed(4) : Math.abs(fin.total_usage).toFixed(4) }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="p-4 flex justify-between items-center cursor-pointer hover:bg-gray-800 transition-colors" @click="openSettings">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<img v-if="user.avatar_path" :src="user.avatar_path" class="w-8 h-8 rounded-full object-cover border border-gray-600 bg-gray-900">
|
||||||
|
<div v-else class="w-8 h-8 rounded-full bg-gradient-to-tr from-aethas-cyan to-aethas-purple flex items-center justify-center text-sm font-bold shadow-md">{{ user.username.charAt(0).toUpperCase() }}</div>
|
||||||
|
<div class="flex flex-col leading-tight">
|
||||||
|
<span class="text-sm font-medium">{{ user.username }}</span>
|
||||||
|
<span v-if="user.is_superadmin" class="text-[9px] text-purple-300">SUPER-ADMIN</span>
|
||||||
|
<span v-else-if="user.is_admin" class="text-[9px] text-red-300">ADMINISTRATEUR</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<i data-lucide="settings" class="w-5 h-5 text-gray-400"></i>
|
||||||
</div>
|
</div>
|
||||||
</aside>
|
</aside>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- ZONE PRINCIPALE -->
|
<!-- ZONE PRINCIPALE -->
|
||||||
<main class="flex-1 flex flex-col min-w-0 z-10 transition-all duration-300">
|
<main class="flex-1 flex flex-col min-w-0 z-10 transition-all duration-300 bg-aethas-dark relative">
|
||||||
|
|
||||||
<header class="flex items-center justify-between p-4 border-b border-gray-700 bg-aethas-panel h-[73px]">
|
<header class="flex items-center justify-between p-4 border-b border-gray-700 bg-aethas-panel h-[73px]">
|
||||||
<div class="flex items-center gap-3">
|
<div class="flex items-center gap-3">
|
||||||
<button @click="toggleSidebar" class="text-gray-400 hover:text-white transition-colors p-1.5 rounded hover:bg-gray-700"><i data-lucide="menu" class="w-6 h-6"></i></button>
|
<button @click="toggleSidebar" class="text-gray-400 hover:text-white p-1.5 rounded hover:bg-gray-700"><i data-lucide="menu" class="w-6 h-6"></i></button>
|
||||||
<div v-show="!isSidebarOpen" class="flex items-center gap-2 transition-opacity duration-300">
|
<div v-show="!isSidebarOpen" class="flex items-center gap-2">
|
||||||
<img src="/static/logo.png" alt="Logo" class="w-8 h-8 rounded-full border border-aethas-cyan object-cover bg-gray-800 flex-shrink-0">
|
<img src="/assets/logo.png" class="w-8 h-8 rounded-full border border-aethas-cyan">
|
||||||
<span class="font-bold text-lg neon-text">AETHAS38</span>
|
<span class="font-bold text-lg neon-text">AETHAS38</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="activeProject" class="text-sm font-medium text-gray-300 flex items-center gap-2">
|
<div v-if="activeView === 'chat' && activeProject" class="text-sm font-medium text-gray-300 flex items-center gap-4">
|
||||||
{{ activeProject.title }}
|
<span class="truncate max-w-[200px] md:max-w-md">{{ activeProject.title }}</span>
|
||||||
<button @click="renameProject(activeProject)" class="text-gray-500 hover:text-aethas-cyan"><i data-lucide="edit-2" class="w-4 h-4"></i></button>
|
<div class="flex items-center gap-2 border-l border-gray-600 pl-4">
|
||||||
|
<button @click="exportProject('txt')" class="text-xs bg-gray-800 hover:bg-gray-700 text-gray-300 border border-gray-600 px-2 py-1 rounded flex items-center gap-1"><i data-lucide="download" class="w-3 h-3"></i> TXT</button>
|
||||||
|
<button @click="exportProject('json')" class="text-xs bg-gray-800 hover:bg-gray-700 text-gray-300 border border-gray-600 px-2 py-1 rounded flex items-center gap-1"><i data-lucide="file-json" class="w-3 h-3"></i> JSON</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<!-- Affichage par défaut -->
|
<!-- VUE : MODÈLES ET FINANCES -->
|
||||||
<div v-if="!activeProject" class="flex-1 overflow-y-auto p-4 md:p-8 flex flex-col items-center justify-center">
|
<div v-if="activeView === 'models' && user.is_admin" class="flex-1 overflow-y-auto p-4 md:p-8 space-y-6 custom-scrollbar">
|
||||||
<img src="/static/logo.png" alt="AETHAS38 Logo" class="w-24 h-24 mb-6 rounded-full border-2 border-aethas-cyan shadow-[0_0_15px_rgba(6,182,212,0.5)] object-cover bg-gray-800 flex-shrink-0">
|
<div class="flex justify-between items-end border-b border-gray-700 pb-4">
|
||||||
<h2 class="text-2xl font-bold text-gray-200 mb-2 text-center">Comment puis-je vous aider aujourd'hui ?</h2>
|
<div>
|
||||||
<p class="text-gray-500 text-sm text-center">Sélectionnez ou créez un projet pour commencer.</p>
|
<h2 class="text-2xl font-bold text-white flex items-center gap-2"><i data-lucide="cpu" class="w-6 h-6 text-aethas-cyan"></i> Modèles & Finances API</h2>
|
||||||
|
<p class="text-sm text-gray-400 mt-1">Dernière extraction : <span class="text-gray-200 font-mono">{{ formatDate(modelInfo.last_sync_date) }}</span> <span class="text-xs bg-gray-800 px-2 py-0.5 rounded border border-gray-600 ml-2 uppercase">{{ modelInfo.last_sync_type || 'Aucune' }}</span></p>
|
||||||
|
</div>
|
||||||
|
<button @click="syncModels" :disabled="isSyncing" class="bg-aethas-cyan hover:bg-cyan-600 text-aethas-dark font-semibold py-2 px-4 rounded flex items-center gap-2 text-sm disabled:opacity-50"><i data-lucide="refresh-cw" :class="{'animate-spin': isSyncing}" class="w-4 h-4"></i> Forcer Extraction</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Zone de Chat -->
|
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||||
<div v-else class="flex-1 overflow-y-auto p-4 md:p-8 space-y-6 flex flex-col" id="chat-container">
|
<div v-for="fin in financesList" :key="fin.provider" class="bg-gray-800 border border-gray-700 rounded-xl p-4 flex flex-col justify-between">
|
||||||
|
<div class="flex justify-between items-start mb-2"><span class="font-bold text-gray-200 capitalize">{{ fin.provider }}</span><i data-lucide="wallet" class="w-5 h-5 text-gray-500"></i></div>
|
||||||
|
<div>
|
||||||
|
<div class="text-2xl font-mono" :class="fin.balance > 0 ? 'text-green-400' : 'text-aethas-cyan'">${{ fin.balance > 0 ? fin.balance.toFixed(4) : Math.abs(fin.total_usage).toFixed(4) }}</div>
|
||||||
|
<div class="text-xs text-gray-400 mt-1">Conso. API : ${{ fin.total_usage.toFixed(4) }}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="bg-aethas-panel border border-gray-700 rounded-xl overflow-hidden flex flex-col">
|
||||||
|
<div class="p-4 bg-gray-800/50 border-b border-gray-700 flex flex-wrap gap-4 items-center">
|
||||||
|
<input v-model="filterSearch" type="text" placeholder="Rechercher..." class="bg-gray-900 border border-gray-600 rounded px-3 py-1.5 text-sm text-gray-200 w-full md:w-64 focus:border-aethas-cyan focus:outline-none">
|
||||||
|
<select v-model="filterDomain" class="bg-gray-900 border border-gray-600 rounded px-3 py-1.5 text-sm text-gray-200 focus:outline-none">
|
||||||
|
<option value="">Tous les domaines</option>
|
||||||
|
<option value="Texte Polyvalent">Texte Polyvalent</option>
|
||||||
|
<option value="Code & Logique">Code & Logique</option>
|
||||||
|
<option value="Vision & Texte">Vision & Texte</option>
|
||||||
|
<option value="Audio">Audio</option>
|
||||||
|
</select>
|
||||||
|
<select v-model="filterPricing" class="bg-gray-900 border border-gray-600 rounded px-3 py-1.5 text-sm text-gray-200 focus:outline-none">
|
||||||
|
<option value="">Tous les prix</option>
|
||||||
|
<option value="free">Gratuits uniquement</option>
|
||||||
|
<option value="paid">Payants</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="overflow-x-auto max-h-[500px] custom-scrollbar">
|
||||||
|
<table class="w-full text-left text-sm text-gray-300">
|
||||||
|
<thead class="text-xs uppercase bg-gray-800 text-gray-400 sticky top-0"><tr><th class="px-4 py-3">Modèle</th><th class="px-4 py-3">Fournisseur</th><th class="px-4 py-3">Domaine</th><th class="px-4 py-3">Coût (1M Tokens)</th><th class="px-4 py-3">Contexte</th><th class="px-4 py-3 w-1/3">Description</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="model in filteredModels" :key="model.model_id" class="border-b border-gray-700 hover:bg-gray-800/50 transition-colors">
|
||||||
|
<td class="px-4 py-3 font-mono text-xs text-aethas-cyan break-all">{{ model.model_id }}</td>
|
||||||
|
<td class="px-4 py-3 capitalize">{{ model.provider }}</td>
|
||||||
|
<td class="px-4 py-3"><span class="bg-gray-700 text-gray-200 px-2 py-1 rounded text-xs">{{ model.domain }}</span></td>
|
||||||
|
<td class="px-4 py-3 font-mono text-xs"><span v-if="model.is_free" class="text-green-400 font-bold">GRATUIT</span><span v-else>In: ${{ model.pricing_prompt.toFixed(2) }}<br>Out: ${{ model.pricing_completion.toFixed(2) }}</span></td>
|
||||||
|
<td class="px-4 py-3">{{ (model.context_length / 1000).toFixed(0) }}k</td>
|
||||||
|
<td class="px-4 py-3 text-xs text-gray-400 truncate max-w-[250px]" :title="model.description_fr">{{ model.description_fr }}</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- VUE : CHAT -->
|
||||||
|
<div v-show="activeView === 'chat'" class="flex-1 flex flex-col min-h-0">
|
||||||
|
<div v-if="!activeProject" class="flex-1 overflow-y-auto p-4 flex flex-col items-center justify-center">
|
||||||
|
<img src="/assets/logo.png" class="w-24 h-24 mb-6 rounded-full border-2 border-aethas-cyan shadow-[0_0_15px_rgba(6,182,212,0.5)]">
|
||||||
|
<h2 class="text-2xl font-bold text-gray-200 mb-2">Comment puis-je vous aider aujourd'hui ?</h2>
|
||||||
|
<p class="text-gray-500 text-sm">Sélectionnez ou créez un projet dans la barre latérale.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template v-else>
|
||||||
|
<div class="flex-1 overflow-y-auto p-4 md:p-8 space-y-6 flex flex-col custom-scrollbar" id="chat-container">
|
||||||
<div v-if="messages.length === 0" class="flex-1 flex items-center justify-center text-gray-500 italic">Démarrez la conversation ci-dessous.</div>
|
<div v-if="messages.length === 0" class="flex-1 flex items-center justify-center text-gray-500 italic">Démarrez la conversation ci-dessous.</div>
|
||||||
|
|
||||||
<div v-for="msg in messages" :key="msg.id" :class="['max-w-3xl rounded-2xl p-4', msg.role === 'user' ? 'bg-gray-800 ml-auto border border-gray-700' : 'bg-aethas-panel mr-auto border border-aethas-cyan/30']">
|
<div v-for="msg in messages" :key="msg.id" :class="['max-w-4xl rounded-2xl p-4', msg.role === 'user' ? 'bg-gray-800 ml-auto border border-gray-700' : 'bg-aethas-panel mr-auto border border-aethas-cyan/30 flex flex-col']">
|
||||||
<div class="flex items-center gap-2 mb-2">
|
<div class="flex items-center gap-2 mb-2">
|
||||||
<i v-if="msg.role === 'user'" data-lucide="user" class="w-4 h-4 text-gray-400"></i>
|
<img v-if="msg.role === 'user' && user.avatar_path" :src="user.avatar_path" class="w-5 h-5 rounded-full object-cover">
|
||||||
<i v-else data-lucide="bot" class="w-4 h-4 text-aethas-cyan"></i>
|
|
||||||
<span class="text-xs font-semibold uppercase tracking-wider text-gray-400">{{ msg.role === 'user' ? 'Vous' : 'AETHAS38' }}</span>
|
<span class="text-xs font-semibold uppercase tracking-wider text-gray-400">{{ msg.role === 'user' ? 'Vous' : 'AETHAS38' }}</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="text-gray-200 whitespace-pre-wrap text-sm leading-relaxed">{{ msg.content }}</div>
|
|
||||||
|
<div class="text-gray-200 text-sm leading-relaxed w-full">
|
||||||
|
<template v-for="(part, index) in parseMessage(msg.content)" :key="index">
|
||||||
|
<div v-if="part.type === 'text'" class="whitespace-pre-wrap font-sans">{{ part.content }}</div>
|
||||||
|
<div v-if="part.type === 'code'" class="my-4 bg-gray-900 rounded-lg border border-gray-700 overflow-hidden shadow-inner">
|
||||||
|
<div class="flex justify-between items-center px-4 py-2 bg-gray-800 border-b border-gray-700">
|
||||||
|
<span class="text-xs text-gray-400 font-mono flex items-center gap-2"><i data-lucide="file-code-2" class="w-4 h-4"></i> {{ part.language || 'code' }}</span>
|
||||||
|
<button @click="downloadFile(part.content, part.language)" class="text-aethas-cyan hover:text-white flex items-center gap-1 text-xs transition-colors bg-gray-700 hover:bg-gray-600 px-2 py-1 rounded"><i data-lucide="download" class="w-3 h-3"></i> Fichier</button>
|
||||||
|
</div>
|
||||||
|
<pre class="p-4 text-xs font-mono text-gray-300 overflow-x-auto custom-scrollbar"><code>{{ part.content }}</code></pre>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Indicateur de chargement IA -->
|
<div v-if="msg.role !== 'user'" class="mt-3 flex items-center gap-3 border-t border-gray-700/50 pt-2 opacity-50 hover:opacity-100 transition-opacity">
|
||||||
<div v-if="isAiThinking" class="max-w-3xl rounded-2xl p-4 bg-aethas-panel mr-auto border border-aethas-cyan/30 w-24">
|
<button @click="copyToClipboard(msg.content)" class="text-xs text-gray-400 hover:text-aethas-cyan flex items-center gap-1"><i data-lucide="copy" class="w-3 h-3"></i> Copier</button>
|
||||||
<div class="flex items-center gap-2 mb-2">
|
<button @click="downloadMessage(msg.content, msg.created_at)" class="text-xs text-gray-400 hover:text-aethas-cyan flex items-center gap-1"><i data-lucide="file-down" class="w-3 h-3"></i> Extraire</button>
|
||||||
<i data-lucide="bot" class="w-4 h-4 text-aethas-cyan"></i>
|
|
||||||
<span class="text-xs font-semibold uppercase tracking-wider text-gray-400">AETHAS38</span>
|
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="isAiThinking" class="max-w-3xl rounded-2xl p-4 bg-aethas-panel mr-auto border border-aethas-cyan/30 w-24">
|
||||||
<div class="flex space-x-1.5 h-4 items-center">
|
<div class="flex space-x-1.5 h-4 items-center">
|
||||||
<div class="w-2 h-2 bg-aethas-cyan rounded-full animate-bounce"></div>
|
<div class="w-2 h-2 bg-aethas-cyan rounded-full animate-bounce"></div>
|
||||||
<div class="w-2 h-2 bg-aethas-cyan rounded-full animate-bounce" style="animation-delay: 0.15s"></div>
|
<div class="w-2 h-2 bg-aethas-cyan rounded-full animate-bounce" style="animation-delay: 0.15s"></div>
|
||||||
@@ -139,181 +236,277 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Saisie du Prompt -->
|
<!-- BARRE DE SÉLECTION DE STYLE TABULAIRE (9 COLONNES STRICTES) -->
|
||||||
<div class="p-4 md:p-6 w-full max-w-4xl mx-auto">
|
<div class="p-4 md:p-6 w-full max-w-7xl mx-auto space-y-2 flex-shrink-0">
|
||||||
<div class="relative flex items-end bg-gray-800 border border-gray-600 rounded-2xl p-2 shadow-lg focus-within:border-aethas-cyan focus-within:ring-1 focus-within:ring-aethas-cyan transition-all">
|
<div class="grid grid-cols-9 border border-black bg-gray-900 rounded-lg overflow-hidden text-center text-xs font-bold shadow-lg">
|
||||||
<button class="p-3 text-gray-400 hover:text-aethas-cyan transition-colors flex-shrink-0" :disabled="!activeProject || isAiThinking"><i data-lucide="paperclip" class="w-5 h-5"></i></button>
|
|
||||||
<textarea
|
<!-- 1. PAYANT / GRATUIT -->
|
||||||
v-model="prompt"
|
<div class="border-r border-black p-1.5 bg-gray-800 flex flex-col justify-center">
|
||||||
@input="autoResize"
|
<label class="block text-[9px] text-gray-400 mb-1">PRIX</label>
|
||||||
@keydown.enter.exact.prevent="sendMessage"
|
<select v-model="filterPricing" class="w-full bg-aethas-dark border border-gray-700 rounded text-gray-200 text-[10px] p-1 outline-none">
|
||||||
ref="promptTextarea"
|
<option value="">TOUS</option>
|
||||||
:disabled="!activeProject || isAiThinking"
|
<option value="free">GRATUIT</option>
|
||||||
rows="1"
|
<option value="paid">PAYANT</option>
|
||||||
class="w-full bg-transparent text-gray-200 p-3 max-h-[200px] overflow-y-auto focus:outline-none resize-none leading-relaxed disabled:opacity-50"
|
</select>
|
||||||
placeholder="Posez votre question à l'Orchestrateur..."></textarea>
|
|
||||||
<button @click="sendMessage" :disabled="!activeProject || !prompt.trim() || isAiThinking" class="p-3 text-aethas-cyan hover:text-white transition-colors flex-shrink-0 disabled:opacity-50 disabled:text-gray-500"><i data-lucide="send" class="w-5 h-5"></i></button>
|
|
||||||
</div>
|
</div>
|
||||||
<p class="text-center text-xs text-gray-500 mt-3">AETHAS38 peut faire des erreurs. Vérifiez toujours les informations importantes.</p>
|
|
||||||
|
<!-- 2. TYPE (DOMAINE) -->
|
||||||
|
<div class="border-r border-black p-1.5 bg-gray-800 flex flex-col justify-center">
|
||||||
|
<label class="block text-[9px] text-gray-400 mb-1">TYPE</label>
|
||||||
|
<select v-model="filterDomain" class="w-full bg-aethas-dark border border-gray-700 rounded text-gray-200 text-[10px] p-1 outline-none">
|
||||||
|
<option value="">TOUS</option>
|
||||||
|
<option value="Texte Polyvalent">Texte</option>
|
||||||
|
<option value="Code & Logique">Codage</option>
|
||||||
|
<option value="Vision & Texte">Vision</option>
|
||||||
|
<option value="Audio">Audio</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 3. TRAVAILLEUR 1 -->
|
||||||
|
<div class="border-r border-black p-1.5 bg-gray-800 flex flex-col justify-center">
|
||||||
|
<label class="block text-[9px] text-aethas-cyan mb-1">TRAVAILLEUR 1</label>
|
||||||
|
<select v-model="workers[0]" class="w-full bg-aethas-dark border border-gray-700 rounded text-gray-200 text-[10px] p-1 outline-none truncate">
|
||||||
|
<option value="">(Aucun)</option>
|
||||||
|
<option v-for="m in filteredBarModels" :key="m.model_id" :value="m.model_id">{{ m.name || m.model_id }}</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 4. TRAVAILLEUR 2 -->
|
||||||
|
<div class="border-r border-black p-1.5 bg-gray-800 flex flex-col justify-center">
|
||||||
|
<label class="block text-[9px] text-aethas-cyan mb-1">TRAVAILLEUR 2</label>
|
||||||
|
<select v-model="workers[1]" class="w-full bg-aethas-dark border border-gray-700 rounded text-gray-200 text-[10px] p-1 outline-none truncate">
|
||||||
|
<option value="">(Aucun)</option>
|
||||||
|
<option v-for="m in filteredBarModels" :key="m.model_id" :value="m.model_id">{{ m.name || m.model_id }}</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 5. TRAVAILLEUR 3 -->
|
||||||
|
<div class="border-r border-black p-1.5 bg-gray-800 flex flex-col justify-center">
|
||||||
|
<label class="block text-[9px] text-aethas-cyan mb-1">TRAVAILLEUR 3</label>
|
||||||
|
<select v-model="workers[2]" class="w-full bg-aethas-dark border border-gray-700 rounded text-gray-200 text-[10px] p-1 outline-none truncate">
|
||||||
|
<option value="">(Aucun)</option>
|
||||||
|
<option v-for="m in filteredBarModels" :key="m.model_id" :value="m.model_id">{{ m.name || m.model_id }}</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 6. TRAVAILLEUR 4 -->
|
||||||
|
<div class="border-r border-black p-1.5 bg-gray-800 flex flex-col justify-center">
|
||||||
|
<label class="block text-[9px] text-aethas-cyan mb-1">TRAVAILLEUR 4</label>
|
||||||
|
<select v-model="workers[3]" class="w-full bg-aethas-dark border border-gray-700 rounded text-gray-200 text-[10px] p-1 outline-none truncate">
|
||||||
|
<option value="">(Aucun)</option>
|
||||||
|
<option v-for="m in filteredBarModels" :key="m.model_id" :value="m.model_id">{{ m.name || m.model_id }}</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 7. TRAVAILLEUR 5 -->
|
||||||
|
<div class="border-r border-black p-1.5 bg-gray-800 flex flex-col justify-center">
|
||||||
|
<label class="block text-[9px] text-aethas-cyan mb-1">TRAVAILLEUR 5</label>
|
||||||
|
<select v-model="workers[4]" class="w-full bg-aethas-dark border border-gray-700 rounded text-gray-200 text-[10px] p-1 outline-none truncate">
|
||||||
|
<option value="">(Aucun)</option>
|
||||||
|
<option v-for="m in filteredBarModels" :key="m.model_id" :value="m.model_id">{{ m.name || m.model_id }}</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 8. PROMPTEUR -->
|
||||||
|
<div class="border-r border-black p-1.5 bg-gray-800 flex flex-col justify-center">
|
||||||
|
<label class="block text-[9px] text-gray-400 mb-1">PROMPTEUR</label>
|
||||||
|
<select v-model="selectedPrompter" class="w-full bg-aethas-dark border border-gray-700 rounded text-gray-200 text-[10px] p-1 outline-none truncate">
|
||||||
|
<option value="gemini-3.5-flash-lite">Gemini Flash</option>
|
||||||
|
<option v-for="m in modelInfo.models" :key="m.model_id" :value="m.model_id">{{ m.name || m.model_id }}</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 9. CONCATENEUR -->
|
||||||
|
<div class="p-1.5 bg-gray-800 flex flex-col justify-center">
|
||||||
|
<label class="block text-[9px] text-aethas-purple mb-1">CONCATENEUR</label>
|
||||||
|
<select v-model="selectedConcatenator" class="w-full bg-aethas-dark border border-gray-700 rounded text-gray-200 text-[10px] p-1 outline-none truncate">
|
||||||
|
<option value="gemini-3.5-flash-lite">Gemini Flash</option>
|
||||||
|
<option v-for="m in modelInfo.models" :key="m.model_id" :value="m.model_id">{{ m.name || m.model_id }}</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Champ de texte du message -->
|
||||||
|
<div class="relative flex items-end bg-gray-800 border border-gray-600 rounded-2xl p-2 shadow-lg focus-within:border-aethas-cyan">
|
||||||
|
<textarea v-model="prompt" @input="autoResize" @keydown.enter.exact.prevent="sendMessage" ref="promptTextarea" :disabled="isAiThinking" rows="1" class="w-full bg-transparent text-gray-200 p-3 max-h-[200px] overflow-y-auto focus:outline-none resize-none disabled:opacity-50 custom-scrollbar" placeholder="Posez votre question à l'orchestrateur..."></textarea>
|
||||||
|
<button @click="sendMessage" :disabled="!prompt.trim() || isAiThinking" class="p-3 text-aethas-cyan hover:text-white disabled:opacity-50"><i data-lucide="send" class="w-5 h-5"></i></button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
const { createApp, ref, onMounted, nextTick, computed } = Vue;
|
const { createApp, ref, reactive, onMounted, nextTick, computed } = Vue;
|
||||||
|
|
||||||
createApp({
|
createApp({
|
||||||
setup() {
|
setup() {
|
||||||
const username = ref("Admin");
|
const user = ref({ username: "Guest", is_admin: false, is_superadmin: false, avatar_path: null });
|
||||||
|
const activeView = ref('chat');
|
||||||
|
const settingsTab = ref('user');
|
||||||
const isSidebarOpen = ref(true);
|
const isSidebarOpen = ref(true);
|
||||||
const prompt = ref("");
|
const prompt = ref("");
|
||||||
const promptTextarea = ref(null);
|
const promptTextarea = ref(null);
|
||||||
|
|
||||||
const projects = ref([]);
|
const projects = ref([]);
|
||||||
const activeProject = ref(null);
|
const activeProject = ref(null);
|
||||||
const messages = ref([]);
|
const messages = ref([]);
|
||||||
|
|
||||||
const isLoading = ref(false);
|
const isLoading = ref(false);
|
||||||
const isAiThinking = ref(false);
|
const isAiThinking = ref(false);
|
||||||
|
const isSyncing = ref(false);
|
||||||
|
const isSavingSettings = ref(false);
|
||||||
|
|
||||||
|
const isSettingsModalOpen = ref(false);
|
||||||
|
const settingsMessage = ref("");
|
||||||
|
const passForm = reactive({ old: '', new: '', confirm: '' });
|
||||||
|
|
||||||
|
const modelInfo = reactive({ last_sync_date: null, last_sync_type: null, models: [] });
|
||||||
|
const financesList = ref([]);
|
||||||
|
const filterSearch = ref("");
|
||||||
|
const filterDomain = ref("");
|
||||||
|
const filterPricing = ref("");
|
||||||
|
|
||||||
|
const workers = ref(["gemini-3.5-flash-lite", "", "", "", ""]);
|
||||||
|
const selectedPrompter = ref("gemini-3.5-flash-lite");
|
||||||
|
const selectedConcatenator = ref("gemini-3.5-flash-lite");
|
||||||
|
|
||||||
const pinnedProjects = computed(() => projects.value.filter(p => p.is_pinned));
|
const pinnedProjects = computed(() => projects.value.filter(p => p.is_pinned));
|
||||||
const recentProjects = computed(() => projects.value.filter(p => !p.is_pinned));
|
const recentProjects = computed(() => projects.value.filter(p => !p.is_pinned));
|
||||||
|
|
||||||
|
const filteredModels = computed(() => {
|
||||||
|
return modelInfo.models.filter(m => {
|
||||||
|
const matchSearch = (m.model_id.toLowerCase().includes(filterSearch.value.toLowerCase()) || m.provider.toLowerCase().includes(filterSearch.value.toLowerCase()));
|
||||||
|
const matchDomain = filterDomain.value === "" || m.domain === filterDomain.value;
|
||||||
|
let matchPrice = true;
|
||||||
|
if (filterPricing.value === 'free') matchPrice = m.is_free;
|
||||||
|
if (filterPricing.value === 'paid') matchPrice = !m.is_free;
|
||||||
|
return matchSearch && matchDomain && matchPrice;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const filteredBarModels = computed(() => {
|
||||||
|
return modelInfo.models.filter(m => {
|
||||||
|
const matchDomain = filterDomain.value === "" || m.domain === filterDomain.value;
|
||||||
|
let matchPrice = true;
|
||||||
|
if (filterPricing.value === 'free') matchPrice = m.is_free;
|
||||||
|
if (filterPricing.value === 'paid') matchPrice = !m.is_free;
|
||||||
|
return matchDomain && matchPrice;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const formatDate = (isoString) => {
|
||||||
|
if (!isoString) return "Jamais";
|
||||||
|
const d = new Date(isoString);
|
||||||
|
return d.toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', year: 'numeric' }) + " à " + d.toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' });
|
||||||
|
};
|
||||||
|
|
||||||
const toggleSidebar = () => { isSidebarOpen.value = !isSidebarOpen.value; };
|
const toggleSidebar = () => { isSidebarOpen.value = !isSidebarOpen.value; };
|
||||||
const autoResize = () => {
|
const autoResize = () => { const el = promptTextarea.value; if(el){ el.style.height = 'auto'; el.style.height = el.scrollHeight + 'px'; }};
|
||||||
const el = promptTextarea.value;
|
const scrollToBottom = () => { nextTick(() => { const c = document.getElementById('chat-container'); if (c) c.scrollTop = c.scrollHeight; }); };
|
||||||
if (!el) return;
|
|
||||||
el.style.height = 'auto';
|
|
||||||
el.style.height = el.scrollHeight + 'px';
|
|
||||||
};
|
|
||||||
const scrollToBottom = () => {
|
|
||||||
nextTick(() => {
|
|
||||||
const container = document.getElementById('chat-container');
|
|
||||||
if (container) container.scrollTop = container.scrollHeight;
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const fetchProjects = async () => {
|
const openSettings = () => { isSettingsModalOpen.value = true; nextTick(() => lucide.createIcons()); };
|
||||||
|
const closeSettings = () => { isSettingsModalOpen.value = false; };
|
||||||
|
|
||||||
|
const fetchUser = async () => { try { const res = await fetch('/api/users/me'); if(res.ok) user.value = await res.json(); } catch(e){} };
|
||||||
|
const fetchModelsInfo = async () => { try { const res = await fetch('/api/models/info'); if(res.ok) { const data = await res.json(); modelInfo.last_sync_date = data.last_sync_date; modelInfo.last_sync_type = data.last_sync_type; modelInfo.models = data.models; } } catch(e){} };
|
||||||
|
const fetchFinances = async () => { try { const res = await fetch('/api/finances'); if(res.ok) financesList.value = await res.json(); } catch(e){} };
|
||||||
|
|
||||||
|
const syncModels = async () => {
|
||||||
|
isSyncing.value = true;
|
||||||
try {
|
try {
|
||||||
const response = await fetch('/api/projects');
|
const res = await fetch('/api/models/sync', { method: 'POST' });
|
||||||
if (response.ok) {
|
if(res.ok) {
|
||||||
projects.value = await response.json();
|
await fetchModelsInfo();
|
||||||
nextTick(() => lucide.createIcons());
|
await fetchFinances();
|
||||||
|
alert("Synchronisation réussie !");
|
||||||
|
} else {
|
||||||
|
let errText = await res.text();
|
||||||
|
try { const errObj = JSON.parse(errText); errText = errObj.detail || errText; } catch(e){}
|
||||||
|
alert("Erreur retournée par le serveur : " + errText);
|
||||||
}
|
}
|
||||||
} catch (error) { console.error(error); }
|
} catch(e) { alert("Erreur réseau: impossible de contacter le serveur."); }
|
||||||
|
isSyncing.value = false;
|
||||||
};
|
};
|
||||||
|
|
||||||
const selectProject = async (project) => {
|
const uploadAvatar = async (event) => {
|
||||||
activeProject.value = project;
|
const file = event.target.files[0];
|
||||||
messages.value = [];
|
if (!file) return;
|
||||||
|
const formData = new FormData(); formData.append("file", file);
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`/api/projects/${project.id}/messages`);
|
const res = await fetch('/api/users/me/avatar', { method: 'POST', body: formData });
|
||||||
if (response.ok) {
|
const data = await res.json();
|
||||||
messages.value = await response.json();
|
if(res.ok) user.value.avatar_path = data.avatar_path;
|
||||||
scrollToBottom();
|
else alert(data.detail);
|
||||||
nextTick(() => lucide.createIcons());
|
} catch(e) { alert("Erreur d'upload"); }
|
||||||
}
|
event.target.value = null;
|
||||||
} catch (error) { console.error(error); }
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const createNewProject = async () => {
|
const exportProject = (format) => { if(activeProject.value) window.open(`/api/projects/${activeProject.value.id}/export?format=${format}`, '_blank'); };
|
||||||
isLoading.value = true;
|
const copyToClipboard = async (text) => { try { await navigator.clipboard.writeText(text); alert("Copié !"); } catch (e) {} };
|
||||||
try {
|
const downloadFile = (content, hint) => { let fname = hint ? hint.trim() : 'code.txt'; if (!fname.includes('.')) fname += '.txt'; const blob = new Blob([content], { type: 'text/plain;charset=utf-8' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = fname; a.click(); URL.revokeObjectURL(url); };
|
||||||
const response = await fetch('/api/projects', {
|
const downloadMessage = (content, dateString) => { downloadFile(content, `message_${dateString.replace(/[:T.Z]/g, '-')}.txt`); };
|
||||||
method: 'POST',
|
const parseMessage = (content) => { const regex = /```([\w.-]*)\n([\s\S]*?)```/g; let parts = [], last = 0, m; while ((m = regex.exec(content)) !== null) { if (m.index > last) parts.push({ type: 'text', content: content.slice(last, m.index) }); parts.push({ type: 'code', language: m[1], content: m[2] }); last = m.index + m[0].length; } if (last < content.length) parts.push({ type: 'text', content: content.slice(last) }); return parts.length > 0 ? parts : [{ type: 'text', content: content }]; };
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({ title: "Nouvelle discussion" })
|
|
||||||
});
|
|
||||||
if (response.ok) {
|
|
||||||
const newProject = await response.json();
|
|
||||||
projects.value.unshift(newProject);
|
|
||||||
selectProject(newProject);
|
|
||||||
}
|
|
||||||
} catch (error) { console.error(error); }
|
|
||||||
finally { isLoading.value = false; }
|
|
||||||
};
|
|
||||||
|
|
||||||
const renameProject = async (project) => {
|
const fetchProjects = async () => { try { const res = await fetch('/api/projects'); if(res.ok) projects.value = await res.json(); nextTick(()=>lucide.createIcons()); } catch(e){} };
|
||||||
const newTitle = window.prompt("Nouveau nom du projet :", project.title);
|
const selectProject = async (project) => { activeView.value = 'chat'; activeProject.value = project; messages.value = []; try { const res = await fetch(`/api/projects/${project.id}/messages`); if(res.ok) { messages.value = await res.json(); scrollToBottom(); nextTick(()=>lucide.createIcons()); } } catch(e){} };
|
||||||
if (!newTitle || newTitle.trim() === "" || newTitle === project.title) return;
|
const createNewProject = async () => { activeView.value = 'chat'; isLoading.value = true; try { const res = await fetch('/api/projects', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({title: "Nouvelle discussion"})}); if(res.ok){ const np = await res.json(); projects.value.unshift(np); selectProject(np); } } catch(e){} finally{isLoading.value = false;} };
|
||||||
|
|
||||||
try {
|
|
||||||
const response = await fetch(`/api/projects/${project.id}/rename`, {
|
|
||||||
method: 'PUT',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
body: JSON.stringify({ title: newTitle.trim() })
|
|
||||||
});
|
|
||||||
if (response.ok) {
|
|
||||||
const updatedProject = await response.json();
|
|
||||||
const index = projects.value.findIndex(p => p.id === project.id);
|
|
||||||
if (index !== -1) projects.value[index] = updatedProject;
|
|
||||||
if (activeProject.value && activeProject.value.id === project.id) {
|
|
||||||
activeProject.value.title = updatedProject.title;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error) { console.error("Erreur de renommage", error); }
|
|
||||||
};
|
|
||||||
|
|
||||||
const sendMessage = async () => {
|
const sendMessage = async () => {
|
||||||
if (!prompt.value.trim() || !activeProject.value) return;
|
const activeWorkers = workers.value.filter(w => w && w.trim() !== "");
|
||||||
const userText = prompt.value.trim();
|
if (!prompt.value.trim() || !activeProject.value || activeWorkers.length === 0) {
|
||||||
prompt.value = "";
|
alert("Veuillez sélectionner au moins un travailleur.");
|
||||||
autoResize();
|
return;
|
||||||
|
}
|
||||||
|
const userText = prompt.value.trim(); prompt.value = ""; autoResize();
|
||||||
messages.value.push({ id: Date.now(), role: 'user', content: userText });
|
messages.value.push({ id: Date.now(), role: 'user', content: userText });
|
||||||
isAiThinking.value = true;
|
isAiThinking.value = true; scrollToBottom();
|
||||||
scrollToBottom();
|
|
||||||
nextTick(() => lucide.createIcons());
|
|
||||||
|
|
||||||
try {
|
const payload = {
|
||||||
await fetch(`/api/projects/${activeProject.value.id}/messages`, {
|
role: 'user',
|
||||||
method: 'POST',
|
content: userText,
|
||||||
headers: { 'Content-Type': 'application/json' },
|
config: {
|
||||||
body: JSON.stringify({ role: 'user', content: userText })
|
workers: activeWorkers,
|
||||||
});
|
prompter: selectedPrompter.value,
|
||||||
|
concatenator: selectedConcatenator.value
|
||||||
// SIMULATION TEMPORAIRE : Attente de l'IA (2 secondes)
|
|
||||||
setTimeout(() => {
|
|
||||||
isAiThinking.value = false;
|
|
||||||
scrollToBottom();
|
|
||||||
// La prochaine étape remplacera ce setTimeout par le véritable appel au moteur IA !
|
|
||||||
}, 2000);
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Erreur envoi message", error);
|
|
||||||
isAiThinking.value = false;
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const togglePin = async (projectId) => { /* ... code existant identique ... */
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`/api/projects/${projectId}/pin`, { method: 'PUT' });
|
const response = await fetch(`/api/projects/${activeProject.value.id}/messages`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
const updatedProject = await response.json();
|
const data = await response.json();
|
||||||
const index = projects.value.findIndex(p => p.id === projectId);
|
if (Array.isArray(data)) messages.value = data;
|
||||||
if (index !== -1) projects.value[index] = updatedProject;
|
await fetchFinances();
|
||||||
|
} else {
|
||||||
|
const err = await response.json(); alert("Erreur API IA : " + err.detail);
|
||||||
}
|
}
|
||||||
} catch (error) { console.error(error); }
|
} catch (error) {} finally { isAiThinking.value = false; scrollToBottom(); nextTick(()=>lucide.createIcons()); }
|
||||||
};
|
};
|
||||||
|
|
||||||
const deleteProject = async (projectId) => { /* ... code existant identique ... */
|
const changePassword = async () => {
|
||||||
if (!confirm("Voulez-vous vraiment supprimer ce projet ?")) return;
|
settingsMessage.value = "";
|
||||||
try {
|
if (passForm.new !== passForm.confirm) { settingsMessage.value = "Mots de passe différents."; return; }
|
||||||
const response = await fetch(`/api/projects/${projectId}`, { method: 'DELETE' });
|
if (passForm.new.length < 8) { settingsMessage.value = "8 caractères minimum."; return; }
|
||||||
if (response.ok) {
|
isSavingSettings.value = true;
|
||||||
projects.value = projects.value.filter(p => p.id !== projectId);
|
try { const res = await fetch('/api/users/me/password', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ old_password: passForm.old, new_password: passForm.new }) }); const data = await res.json(); if (res.ok) { settingsMessage.value = data.message; passForm.old=''; passForm.new=''; passForm.confirm=''; } else { settingsMessage.value = data.detail; } } catch (e) {} finally { isSavingSettings.value = false; }
|
||||||
if (activeProject.value && activeProject.value.id === projectId) activeProject.value = null;
|
|
||||||
}
|
|
||||||
} catch (error) { console.error(error); }
|
|
||||||
};
|
};
|
||||||
|
|
||||||
onMounted(() => {
|
const renameProject = async (project) => { const nt = window.prompt("Nom :", project.title); if (!nt || nt.trim() === "" || nt === project.title) return; try { const res = await fetch(`/api/projects/${project.id}/rename`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: nt.trim() }) }); if (res.ok) { const up = await res.json(); const i = projects.value.findIndex(p => p.id === project.id); if (i !== -1) projects.value[i] = up; if (activeProject.value && activeProject.value.id === project.id) activeProject.value.title = up.title; } } catch (e) {} };
|
||||||
lucide.createIcons();
|
const togglePin = async (pid) => { try { const res = await fetch(`/api/projects/${pid}/pin`, { method: 'PUT' }); if (res.ok) { const up = await res.json(); const i = projects.value.findIndex(p => p.id === pid); if (i !== -1) projects.value[i] = up; } } catch (e) {} };
|
||||||
fetchProjects();
|
const deleteProject = async (pid) => { if (!confirm("Supprimer ce projet ?")) return; try { const res = await fetch(`/api/projects/${pid}`, { method: 'DELETE' }); if (res.ok) { projects.value = projects.value.filter(p => p.id !== pid); if (activeProject.value && activeProject.value.id === pid) activeProject.value = null; } } catch (e) {} };
|
||||||
});
|
|
||||||
|
onMounted(() => { lucide.createIcons(); fetchUser(); fetchProjects(); fetchModelsInfo(); fetchFinances(); });
|
||||||
|
|
||||||
return {
|
return {
|
||||||
username, isSidebarOpen, toggleSidebar, prompt, autoResize, promptTextarea,
|
user, activeView, settingsTab, isSidebarOpen, toggleSidebar, prompt, autoResize, promptTextarea,
|
||||||
projects, pinnedProjects, recentProjects, activeProject, messages, isAiThinking,
|
projects, pinnedProjects, recentProjects, activeProject, messages, isAiThinking,
|
||||||
createNewProject, selectProject, renameProject, sendMessage, isLoading, togglePin, deleteProject
|
createNewProject, selectProject, renameProject, sendMessage, isLoading, togglePin, deleteProject,
|
||||||
|
isSettingsModalOpen, openSettings, closeSettings, passForm, settingsMessage, isSavingSettings, changePassword, uploadAvatar,
|
||||||
|
modelInfo, financesList, filterSearch, filterDomain, filterPricing, filteredModels, filteredBarModels, formatDate, syncModels, isSyncing,
|
||||||
|
workers, selectedPrompter, selectedConcatenator,
|
||||||
|
exportProject, copyToClipboard, downloadFile, downloadMessage, parseMessage
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}).mount('#app');
|
}).mount('#app');
|
||||||
|
|||||||
+59
-13
@@ -20,9 +20,9 @@
|
|||||||
</head>
|
</head>
|
||||||
<body class="flex items-center justify-center min-h-screen p-4 sm:p-8 overflow-y-auto">
|
<body class="flex items-center justify-center min-h-screen p-4 sm:p-8 overflow-y-auto">
|
||||||
|
|
||||||
<div id="app" class="w-full max-w-2xl transition-all duration-500 my-8">
|
<div id="app" class="w-full max-w-3xl transition-all duration-500 my-8">
|
||||||
<div class="text-center mb-8">
|
<div class="text-center mb-8">
|
||||||
<img src="/static/logo.png" alt="AETHAS38 Logo" class="w-24 h-24 mx-auto mb-4 rounded-full border-2 border-aethas-cyan shadow-[0_0_15px_rgba(6,182,212,0.5)] object-cover bg-gray-800">
|
<img src="/assets/logo.png" alt="AETHAS38 Logo" class="w-24 h-24 mx-auto mb-4 rounded-full border-2 border-aethas-cyan shadow-[0_0_15px_rgba(6,182,212,0.5)] object-cover bg-gray-800">
|
||||||
<h1 class="text-3xl font-bold tracking-wider neon-text">AETHAS38</h1>
|
<h1 class="text-3xl font-bold tracking-wider neon-text">AETHAS38</h1>
|
||||||
<p class="text-gray-400 text-sm mt-2">Configuration Initiale (Super Admin)</p>
|
<p class="text-gray-400 text-sm mt-2">Configuration Initiale (Super Admin)</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -61,7 +61,6 @@
|
|||||||
<button type="button" @click="showWiki = !showWiki" class="text-xs text-aethas-cyan hover:text-white underline">Aide FAI Français</button>
|
<button type="button" @click="showWiki = !showWiki" class="text-xs text-aethas-cyan hover:text-white underline">Aide FAI Français</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Wiki d'aide -->
|
|
||||||
<div v-if="showWiki" class="mb-4 p-4 bg-gray-800 rounded-lg border border-gray-600 text-sm text-gray-300 space-y-2">
|
<div v-if="showWiki" class="mb-4 p-4 bg-gray-800 rounded-lg border border-gray-600 text-sm text-gray-300 space-y-2">
|
||||||
<p><strong>Freebox :</strong> Hôte: smtp.free.fr | Port: 465 (SSL) ou 587 (TLS)</p>
|
<p><strong>Freebox :</strong> Hôte: smtp.free.fr | Port: 465 (SSL) ou 587 (TLS)</p>
|
||||||
<p><strong>Orange :</strong> Hôte: smtp.orange.fr | Port: 465 (SSL)</p>
|
<p><strong>Orange :</strong> Hôte: smtp.orange.fr | Port: 465 (SSL)</p>
|
||||||
@@ -93,17 +92,63 @@
|
|||||||
<!-- Section 3 : Clés API IA -->
|
<!-- Section 3 : Clés API IA -->
|
||||||
<div>
|
<div>
|
||||||
<h2 class="text-lg font-semibold text-white border-b border-gray-700 pb-2 mb-4 flex items-center gap-2">
|
<h2 class="text-lg font-semibold text-white border-b border-gray-700 pb-2 mb-4 flex items-center gap-2">
|
||||||
<i data-lucide="cpu" class="w-5 h-5 text-aethas-cyan"></i> Moteurs IA (Optionnel)
|
<i data-lucide="cpu" class="w-5 h-5 text-aethas-cyan"></i> Moteurs IA (Optionnel - modifiable plus tard)
|
||||||
</h2>
|
</h2>
|
||||||
<div class="space-y-4">
|
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||||
<div>
|
|
||||||
<label class="block text-sm text-gray-300 mb-1">Google Gemini API Key</label>
|
<!-- OpenRouter -->
|
||||||
<input v-model="form.gemini_api_key" type="password" class="w-full bg-aethas-dark border border-gray-600 rounded-lg px-4 py-2 focus:border-aethas-cyan outline-none" placeholder="AIzaSy...">
|
<div class="space-y-2 bg-gray-800/50 p-3 rounded-lg border border-gray-700">
|
||||||
|
<h3 class="text-sm font-bold text-white flex items-center justify-between">OpenRouter <a href="https://openrouter.ai/keys" target="_blank" class="text-aethas-cyan hover:underline text-xs"><i data-lucide="external-link" class="w-3 h-3 inline"></i> Récupérer</a></h3>
|
||||||
|
<p class="text-xs text-gray-400">Générez une clé standard pour les requêtes, et une "Management Key" pour la récupération des crédits.</p>
|
||||||
|
<input v-model="form.openrouter_api_key" type="password" class="w-full bg-aethas-dark border border-gray-600 rounded-lg px-3 py-1.5 text-sm focus:border-aethas-cyan outline-none" placeholder="API Key (sk-or-v1-...)">
|
||||||
|
<input v-model="form.openrouter_management_key" type="password" class="w-full bg-aethas-dark border border-gray-600 rounded-lg px-3 py-1.5 text-sm focus:border-aethas-cyan outline-none" placeholder="Management Key">
|
||||||
</div>
|
</div>
|
||||||
<div>
|
|
||||||
<label class="block text-sm text-gray-300 mb-1">OpenRouter API Key</label>
|
<!-- Gemini -->
|
||||||
<input v-model="form.openrouter_api_key" type="password" class="w-full bg-aethas-dark border border-gray-600 rounded-lg px-4 py-2 focus:border-aethas-cyan outline-none" placeholder="sk-or-v1-...">
|
<div class="space-y-2 bg-gray-800/50 p-3 rounded-lg border border-gray-700">
|
||||||
|
<h3 class="text-sm font-bold text-white flex items-center justify-between">Google Gemini <a href="https://aistudio.google.com/app/apikey" target="_blank" class="text-aethas-cyan hover:underline text-xs"><i data-lucide="external-link" class="w-3 h-3 inline"></i> Récupérer</a></h3>
|
||||||
|
<p class="text-xs text-gray-400">Créez une API Key depuis Google AI Studio (Associez un projet Google Cloud pour lever les quotas gratuits limités).</p>
|
||||||
|
<input v-model="form.gemini_api_key" type="password" class="w-full bg-aethas-dark border border-gray-600 rounded-lg px-3 py-1.5 text-sm focus:border-aethas-cyan outline-none" placeholder="AIzaSy...">
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Groq -->
|
||||||
|
<div class="space-y-2 bg-gray-800/50 p-3 rounded-lg border border-gray-700">
|
||||||
|
<h3 class="text-sm font-bold text-white flex items-center justify-between">Groq <a href="https://console.groq.com/keys" target="_blank" class="text-aethas-cyan hover:underline text-xs"><i data-lucide="external-link" class="w-3 h-3 inline"></i> Récupérer</a></h3>
|
||||||
|
<p class="text-xs text-gray-400">Créez une clé d'API. L'accès aux modèles Llama est gratuit avec quotas.</p>
|
||||||
|
<input v-model="form.groq_api_key" type="password" class="w-full bg-aethas-dark border border-gray-600 rounded-lg px-3 py-1.5 text-sm focus:border-aethas-cyan outline-none" placeholder="gsk_...">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- DeepSeek -->
|
||||||
|
<div class="space-y-2 bg-gray-800/50 p-3 rounded-lg border border-gray-700">
|
||||||
|
<h3 class="text-sm font-bold text-white flex items-center justify-between">DeepSeek <a href="https://platform.deepseek.com/api_keys" target="_blank" class="text-aethas-cyan hover:underline text-xs"><i data-lucide="external-link" class="w-3 h-3 inline"></i> Récupérer</a></h3>
|
||||||
|
<p class="text-xs text-gray-400">Créez une clé d'API. Parfait pour le traitement du code de AETHAS38.</p>
|
||||||
|
<input v-model="form.deepseek_api_key" type="password" class="w-full bg-aethas-dark border border-gray-600 rounded-lg px-3 py-1.5 text-sm focus:border-aethas-cyan outline-none" placeholder="sk-...">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Mistral -->
|
||||||
|
<div class="space-y-2 bg-gray-800/50 p-3 rounded-lg border border-gray-700">
|
||||||
|
<h3 class="text-sm font-bold text-white flex items-center justify-between">Mistral AI <a href="https://console.mistral.ai/api-keys/" target="_blank" class="text-aethas-cyan hover:underline text-xs"><i data-lucide="external-link" class="w-3 h-3 inline"></i> Récupérer</a></h3>
|
||||||
|
<p class="text-xs text-gray-400">Assurez-vous d'avoir enregistré une méthode de facturation pour lever la période d'essai.</p>
|
||||||
|
<input v-model="form.mistral_api_key" type="password" class="w-full bg-aethas-dark border border-gray-600 rounded-lg px-3 py-1.5 text-sm focus:border-aethas-cyan outline-none" placeholder="Clé API Mistral">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- HuggingFace -->
|
||||||
|
<div class="space-y-2 bg-gray-800/50 p-3 rounded-lg border border-gray-700">
|
||||||
|
<h3 class="text-sm font-bold text-white flex items-center justify-between">HuggingFace <a href="https://huggingface.co/settings/tokens" target="_blank" class="text-aethas-cyan hover:underline text-xs"><i data-lucide="external-link" class="w-3 h-3 inline"></i> Récupérer</a></h3>
|
||||||
|
<p class="text-xs text-gray-400">Générez un Access Token (Fine-grained) avec les droits de lecture et génération (Inference).</p>
|
||||||
|
<input v-model="form.huggingface_api_key" type="password" class="w-full bg-aethas-dark border border-gray-600 rounded-lg px-3 py-1.5 text-sm focus:border-aethas-cyan outline-none" placeholder="hf_...">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Cloudflare -->
|
||||||
|
<div class="space-y-2 bg-gray-800/50 p-3 rounded-lg border border-gray-700 md:col-span-2">
|
||||||
|
<h3 class="text-sm font-bold text-white flex items-center justify-between">Cloudflare Workers AI <a href="https://dash.cloudflare.com/profile/api-tokens" target="_blank" class="text-aethas-cyan hover:underline text-xs"><i data-lucide="external-link" class="w-3 h-3 inline"></i> Récupérer</a></h3>
|
||||||
|
<p class="text-xs text-gray-400">Créez un "Custom Token" avec l'autorisation "Workers AI : Read/Write". Votre ID de compte se trouve sur la page d'accueil Workers.</p>
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<input v-model="form.cloudflare_account_id" type="text" class="w-1/3 bg-aethas-dark border border-gray-600 rounded-lg px-3 py-1.5 text-sm focus:border-aethas-cyan outline-none" placeholder="Account ID">
|
||||||
|
<input v-model="form.cloudflare_api_token" type="password" class="w-2/3 bg-aethas-dark border border-gray-600 rounded-lg px-3 py-1.5 text-sm focus:border-aethas-cyan outline-none" placeholder="API Token">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -114,7 +159,6 @@
|
|||||||
</form>
|
</form>
|
||||||
|
|
||||||
<div v-else class="text-center space-y-6 animate-fade-in">
|
<div v-else class="text-center space-y-6 animate-fade-in">
|
||||||
<!-- Code existant pour le succès / QR Code -->
|
|
||||||
<div class="inline-flex items-center justify-center w-12 h-12 rounded-full bg-green-900/50 text-green-400 mb-2">
|
<div class="inline-flex items-center justify-center w-12 h-12 rounded-full bg-green-900/50 text-green-400 mb-2">
|
||||||
<i data-lucide="check" class="w-6 h-6"></i>
|
<i data-lucide="check" class="w-6 h-6"></i>
|
||||||
</div>
|
</div>
|
||||||
@@ -145,7 +189,9 @@
|
|||||||
const form = reactive({
|
const form = reactive({
|
||||||
email: '', username: '', password: '',
|
email: '', username: '', password: '',
|
||||||
smtp_host: '', smtp_port: 465, smtp_user: '', smtp_password: '',
|
smtp_host: '', smtp_port: 465, smtp_user: '', smtp_password: '',
|
||||||
gemini_api_key: '', openrouter_api_key: ''
|
openrouter_api_key: '', openrouter_management_key: '',
|
||||||
|
groq_api_key: '', gemini_api_key: '', deepseek_api_key: '', mistral_api_key: '',
|
||||||
|
cloudflare_account_id: '', cloudflare_api_token: '', huggingface_api_key: ''
|
||||||
});
|
});
|
||||||
const isSubmitting = ref(false);
|
const isSubmitting = ref(false);
|
||||||
const setupComplete = ref(false);
|
const setupComplete = ref(false);
|
||||||
|
|||||||
+23
-33
@@ -6,26 +6,12 @@
|
|||||||
<title>AETHAS38 - Connexion</title>
|
<title>AETHAS38 - Connexion</title>
|
||||||
<script src="https://cdn.tailwindcss.com"></script>
|
<script src="https://cdn.tailwindcss.com"></script>
|
||||||
<script>
|
<script>
|
||||||
tailwind.config = {
|
tailwind.config = { darkMode: 'class', theme: { extend: { colors: { aethas: { dark: '#0f172a', panel: '#1e293b', cyan: '#06b6d4', purple: '#a855f7' } } } } }
|
||||||
darkMode: 'class',
|
|
||||||
theme: {
|
|
||||||
extend: {
|
|
||||||
colors: {
|
|
||||||
aethas: {
|
|
||||||
dark: '#0f172a', panel: '#1e293b', cyan: '#06b6d4', purple: '#a855f7'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
</script>
|
||||||
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
|
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
|
||||||
<style>
|
<style>
|
||||||
body { background-color: #0f172a; color: #f8fafc; font-family: 'Inter', sans-serif; }
|
body { background-color: #0f172a; color: #f8fafc; font-family: 'Inter', sans-serif; }
|
||||||
.glass-panel {
|
.glass-panel { background: rgba(30, 41, 59, 0.7); backdrop-filter: blur(10px); border: 1px solid rgba(6, 182, 212, 0.2); box-shadow: 0 4px 30px rgba(0, 0, 0, 0.5); }
|
||||||
background: rgba(30, 41, 59, 0.7); backdrop-filter: blur(10px);
|
|
||||||
border: 1px solid rgba(6, 182, 212, 0.2); box-shadow: 0 4px 30px rgba(0, 0, 0, 0.5);
|
|
||||||
}
|
|
||||||
.neon-text { background: linear-gradient(to right, #06b6d4, #a855f7); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
|
.neon-text { background: linear-gradient(to right, #06b6d4, #a855f7); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
@@ -33,16 +19,14 @@
|
|||||||
|
|
||||||
<div id="app" class="w-full max-w-md transition-all duration-500">
|
<div id="app" class="w-full max-w-md transition-all duration-500">
|
||||||
<div class="text-center mb-8">
|
<div class="text-center mb-8">
|
||||||
<img src="https://via.placeholder.com/150x150/0f172a/06b6d4?text=Logo+A38" alt="AETHAS38 Logo" class="w-24 h-24 mx-auto mb-4 rounded-full border-2 border-aethas-cyan shadow-[0_0_15px_rgba(6,182,212,0.5)]">
|
<img src="/assets/logo.png" alt="AETHAS38 Logo" class="w-24 h-24 mx-auto mb-4 rounded-full border-2 border-aethas-cyan shadow-[0_0_15px_rgba(6,182,212,0.5)] object-cover bg-gray-800">
|
||||||
<h1 class="text-3xl font-bold tracking-wider neon-text">AETHAS38</h1>
|
<h1 class="text-3xl font-bold tracking-wider neon-text">AETHAS38</h1>
|
||||||
<p class="text-gray-400 text-sm mt-2">Authentification Sécurisée</p>
|
<p class="text-gray-400 text-sm mt-2">Authentification Sécurisée</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="glass-panel rounded-2xl p-6 sm:p-8">
|
<div class="glass-panel rounded-2xl p-6 sm:p-8">
|
||||||
<form @submit.prevent="submitLogin" class="space-y-5">
|
<form @submit.prevent="submitLogin" class="space-y-5">
|
||||||
<div v-if="errorMessage" class="p-3 bg-red-900/50 border border-red-500 rounded text-red-200 text-sm text-center">
|
<div v-if="errorMessage" class="p-3 bg-red-900/50 border border-red-500 rounded text-red-200 text-sm text-center">{{ errorMessage }}</div>
|
||||||
{{ errorMessage }}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<label class="block text-sm font-medium text-gray-300 mb-1">Nom d'utilisateur</label>
|
<label class="block text-sm font-medium text-gray-300 mb-1">Nom d'utilisateur</label>
|
||||||
@@ -56,11 +40,11 @@
|
|||||||
|
|
||||||
<div>
|
<div>
|
||||||
<label class="block text-sm font-medium text-gray-300 mb-1">Code 2FA (6 chiffres)</label>
|
<label class="block text-sm font-medium text-gray-300 mb-1">Code 2FA (6 chiffres)</label>
|
||||||
<input v-model="form.totp_code" type="text" inputmode="numeric" pattern="[0-9]{6}" required maxlength="6" class="w-full bg-aethas-dark border border-gray-600 rounded-lg px-4 py-2.5 focus:outline-none focus:border-aethas-cyan focus:ring-1 focus:ring-aethas-cyan transition-colors text-center tracking-widest text-lg" placeholder="123456">
|
<input v-model="form.totp_code" type="text" required pattern="[0-9]{6}" class="w-full bg-aethas-dark border border-gray-600 rounded-lg px-4 py-2.5 focus:outline-none focus:border-aethas-cyan focus:ring-1 focus:ring-aethas-cyan transition-colors text-center tracking-widest text-lg" placeholder="123456">
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<button type="submit" :disabled="isSubmitting" class="w-full bg-gradient-to-r from-aethas-cyan to-aethas-purple hover:opacity-90 text-white font-semibold py-3 px-4 rounded-lg transition-all shadow-[0_0_10px_rgba(168,85,247,0.4)] flex justify-center items-center mt-6">
|
<button type="submit" :disabled="isLoading" class="w-full bg-gradient-to-r from-aethas-cyan to-aethas-purple hover:opacity-90 text-white font-semibold py-3 px-4 rounded-lg transition-all shadow-[0_0_10px_rgba(168,85,247,0.4)] flex justify-center items-center mt-6">
|
||||||
<span v-if="isSubmitting">Vérification...</span>
|
<span v-if="isLoading">Connexion...</span>
|
||||||
<span v-else>Se connecter</span>
|
<span v-else>Se connecter</span>
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
@@ -68,37 +52,43 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
const { createApp, reactive, ref } = Vue;
|
const { createApp, ref, reactive } = Vue;
|
||||||
|
|
||||||
createApp({
|
createApp({
|
||||||
setup() {
|
setup() {
|
||||||
const form = reactive({ username: '', password: '', totp_code: '' });
|
const form = reactive({ username: '', password: '', totp_code: '' });
|
||||||
const isSubmitting = ref(false);
|
const isLoading = ref(false);
|
||||||
const errorMessage = ref('');
|
const errorMessage = ref('');
|
||||||
|
|
||||||
const submitLogin = async () => {
|
const submitLogin = async () => {
|
||||||
isSubmitting.value = true;
|
isLoading.value = true;
|
||||||
errorMessage.value = '';
|
errorMessage.value = '';
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch('/api/login', {
|
const response = await fetch('/api/login', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify(form)
|
body: JSON.stringify(form)
|
||||||
});
|
});
|
||||||
const data = await response.json();
|
|
||||||
if (!response.ok) throw new Error(data.detail || "Erreur de connexion");
|
|
||||||
|
|
||||||
// Redirection vers le tableau de bord une fois connecté
|
const data = await response.json();
|
||||||
window.location.href = "/dashboard";
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(data.detail || "Erreur de connexion");
|
||||||
|
}
|
||||||
|
|
||||||
|
window.location.href = '/dashboard';
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
errorMessage.value = error.message;
|
errorMessage.value = error.message;
|
||||||
} finally {
|
} finally {
|
||||||
isSubmitting.value = false;
|
isLoading.value = false;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
return { form, isSubmitting, errorMessage, submitLogin };
|
|
||||||
|
return { form, isLoading, errorMessage, submitLogin };
|
||||||
}
|
}
|
||||||
}).mount('#app');
|
}).mount('#app');
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
@@ -11,3 +11,7 @@ python-multipart
|
|||||||
bcrypt
|
bcrypt
|
||||||
email-validator
|
email-validator
|
||||||
PyJWT
|
PyJWT
|
||||||
|
openai
|
||||||
|
httpx
|
||||||
|
python-multipart
|
||||||
|
pytz
|
||||||
Reference in new issue
Block a user