|
|
|
import os |
|
import dash |
|
import json |
|
import bcrypt |
|
import glob |
|
import pandas as pd |
|
import numpy as np |
|
import plotly.graph_objects as go |
|
import requests |
|
from typing import Dict, List, TypedDict, Annotated, Sequence, Any, Optional, Union, Tuple |
|
import re |
|
import time |
|
import uuid |
|
import base64 |
|
import io |
|
|
|
from openai import OpenAI |
|
from langchain_openai import ChatOpenAI |
|
from langchain_core.messages import HumanMessage, SystemMessage, AIMessage |
|
from langchain_core.prompts import PromptTemplate |
|
|
|
|
|
from langgraph.graph import StateGraph, END |
|
from langgraph.checkpoint.memory import MemorySaver |
|
from langchain_openai import ChatOpenAI |
|
from langchain_core.messages import HumanMessage, SystemMessage, AIMessage |
|
|
|
import dash |
|
from dash.dependencies import Input, Output, State |
|
from dash import Dash, html, dcc, callback, callback_context, ctx, Output, Input, dash_table, State, no_update, _dash_renderer, clientside_callback |
|
from dash import html |
|
|
|
import dash_bootstrap_components as dbc |
|
from dash.exceptions import PreventUpdate |
|
import dash_mantine_components as dmc |
|
from dash_iconify import DashIconify |
|
_dash_renderer._set_react_version("18.2.0") |
|
import flask |
|
from flask_login import LoginManager, UserMixin, login_user, current_user, login_required, logout_user |
|
from datetime import timedelta |
|
|
|
from IPython.display import display, HTML |
|
|
|
|
|
SIDEBAR_STYLE = { |
|
"font-family": "Inter, sans-serif", |
|
"font-size": "70%", |
|
"position": "fixed", |
|
|
|
"top": "0", |
|
"left": 0, |
|
"bottom": 0, |
|
"width": "16rem", |
|
"padding": "2rem 1rem", |
|
"background-color": "rgb(2,8,23)", |
|
"color": "white", |
|
"overflow": "auto", |
|
"border-right": "1px solid rgb(47,65,93)", |
|
} |
|
|
|
CONTENT_STYLE = { |
|
"min-height": "100vh", |
|
"font-family": "Inter, sans-serif", |
|
"font-size": "70%", |
|
"margin-left": "16rem", |
|
"margin-right": "0", |
|
"padding": "2rem 1rem", |
|
"background-color": "rgb(2,8,23)", |
|
"color": "white", |
|
"border-left": "1px solid rgb(47,65,93)", |
|
} |
|
|
|
llm = ChatOpenAI(model_name="neuralmagic/Meta-Llama-3.1-70B-Instruct-FP8", base_url=os.environ['BASEURL_ALBERT_API_KEY'], api_key=os.environ['ENDPOINT_ALBERT_API_KEY']) |
|
model = ChatOpenAI(model_name="mistralai/Mistral-Small-3.1-24B-Instruct-2503", base_url=os.environ['BASEURL_ALBERT_API_KEY'], api_key=os.environ['ENDPOINT_ALBERT_API_KEY']) |
|
|
|
OWNER = os.environ['GITHUB_OWNER'] |
|
REPO = os.environ['GITHUB_REPO'] |
|
ACCESS_TOKEN = os.environ['GITHUB_ACCESS_TOKEN'] |
|
params = {'ref': 'main'} |
|
|
|
headers = { |
|
'Authorization': f'token {ACCESS_TOKEN}', |
|
'Accept': 'application/vnd.github.v3+json' |
|
} |
|
|
|
|
|
class AgentState(TypedDict): |
|
"""État de l'agent LangGraph.""" |
|
files_list: List[str] |
|
current_file: str |
|
dataframe: Optional[object] |
|
categories: Optional[List[Dict[str, str]]] |
|
classified_teachings: Optional[Dict[str, List[str]]] |
|
learning_situations: Optional[Dict[str, str]] |
|
academic_competencies: Optional[Dict[str, str]] |
|
status: str |
|
|
|
def display_formatted_dataframe(df): |
|
def format_text(text): |
|
return text.replace('\n', '<br>') |
|
|
|
df_formatted = df[['catégorie', 'exemple_situation_apprentissage']].copy() |
|
df_formatted = df_formatted.drop_duplicates(subset=['exemple_situation_apprentissage']) |
|
|
|
df_formatted['catégorie'] = df_formatted['catégorie'].apply(format_text) |
|
df_formatted['exemple_situation_apprentissage'] = df_formatted['exemple_situation_apprentissage'].apply(format_text) |
|
|
|
return HTML(df_formatted.to_html(escape=False, justify='left')) |
|
|
|
def load_csv_files(directory_path: str = "./Maquettes-formation"): |
|
if not os.path.exists(directory_path): |
|
print(f"Erreur: Le répertoire {directory_path} n'existe pas.") |
|
return |
|
|
|
|
|
json_files = glob.glob(os.path.join(directory_path, "*.csv")) |
|
|
|
if not json_files: |
|
print(f"Aucun fichier JSON trouvé dans le répertoire {directory_path}.") |
|
return |
|
|
|
print(f"Fichiers JSON trouvés: {len(json_files)}") |
|
|
|
|
|
return json_files |
|
|
|
def load_and_preprocess_csv(state: AgentState, file: str = "") -> AgentState: |
|
""" |
|
Charge le fichier CSV actuel et prétraite les données. |
|
|
|
Étape 1: Charger les fichiers maquettes, concaténer les colonnes UE et ECUE ou BCC et UE |
|
pour créer la colonne enseignements. |
|
""" |
|
|
|
print(f"Chargement et prétraitement du fichier: {file}") |
|
|
|
|
|
try: |
|
res = requests.get(file, headers=headers, params=params) |
|
if res.status_code == 200: |
|
|
|
|
|
decoded_content = res.text |
|
df = pd.read_csv(io.StringIO(decoded_content), sep=',', encoding='utf-8') |
|
|
|
df = df.loc[:, 'diplome':'ECUE'] |
|
print(f"Colonnes disponibles: {df.columns.tolist()}") |
|
df.fillna(value={"BCC": "BCC"}) |
|
|
|
if 'UE' in df.columns and 'ECUE' in df.columns: |
|
|
|
df['enseignements'] = np.where( |
|
df['ECUE'].notna() & (df['ECUE'] != ''), |
|
df['UE'] + ' - ' + df['ECUE'], |
|
df['BCC'] + ' - ' + df['UE'] if 'BCC' in df.columns else df['UE'] |
|
) |
|
else: |
|
|
|
print("Attention: Colonnes UE/ECUE non trouvées. Vérifiez le format du fichier.") |
|
raise ValueError("Format de fichier incorrect: colonnes UE/ECUE manquantes.") |
|
|
|
print(f"Prétraitement réussi. {len(df)} lignes traitées.") |
|
|
|
|
|
return { |
|
**state, |
|
"dataframe": df, |
|
"status": "preprocessed" |
|
} |
|
|
|
except Exception as e: |
|
print(f"Erreur lors du chargement/prétraitement du fichier: {e}") |
|
|
|
if len(state['files_list']) > 0: |
|
return { |
|
**state, |
|
"current_file": file, |
|
"files_list": file, |
|
"status": "error" |
|
} |
|
else: |
|
return {**state, "status": "finished"} |
|
|
|
def create_thematic_categories(state: AgentState, num_bcc: str = "") -> AgentState: |
|
f""" |
|
Crée {num_bcc} catégories thématiques représentatives des enseignements. |
|
|
|
Étape 2: Créer, par un LLM, {num_bcc} catégories thématiques représentatives des enseignements, |
|
avec au moins 20 mots chacune. |
|
""" |
|
print("Création des catégories thématiques...") |
|
|
|
df = state["dataframe"] |
|
unique_teachings = df['enseignements'].dropna().unique().tolist() |
|
|
|
|
|
messages = [ |
|
SystemMessage(content=f"""Tu es un expert en sciences de l'éducation, spécialisé dans la catégorisation thématique de contenus pédagogiques. |
|
Tu dois créer EXACTEMENT {num_bcc} catégories thématiques distinctes qui représentent au mieux les enseignements listés. |
|
Pour chaque catégorie, fournis: |
|
1. Un nom précis et représentatif de 20 mots minimum |
|
2. Une description détaillée d'au moins 20 mots expliquant le contenu de cette catégorie |
|
|
|
Réponds UNIQUEMENT au format JSON avec la structure suivante: |
|
[ |
|
{{ |
|
"nom": "Nom de la catégorie 1", |
|
"description": "Description détaillée de la catégorie 1 (min 20 mots)" |
|
}}, |
|
... |
|
] |
|
"""), |
|
HumanMessage(content=f"Voici la liste des enseignements à catégoriser: {json.dumps(unique_teachings, ensure_ascii=False)}") |
|
] |
|
|
|
try: |
|
|
|
response = llm.invoke(messages) |
|
|
|
|
|
content = response.content |
|
|
|
|
|
if "```json" in content: |
|
content = content.split("```json")[1].split("```")[0].strip() |
|
elif "```" in content: |
|
content = content.split("```")[1].split("```")[0].strip() |
|
|
|
|
|
categories = json.loads(content) |
|
|
|
print("Catégories thématiques créées avec succès:") |
|
for idx, cat in enumerate(categories, 1): |
|
print(f"{idx}. {cat['nom']} - {cat['description'][:50]}...") |
|
|
|
|
|
return { |
|
**state, |
|
"categories": categories, |
|
"status": "categories_created" |
|
} |
|
|
|
except Exception as e: |
|
print(f"Erreur lors de la création des catégories: {e}") |
|
return {**state, "status": "error"} |
|
|
|
def classify_teachings(state: AgentState, num_bcc: str = "") -> AgentState: |
|
f""" |
|
Classe les enseignements selon les {num_bcc} catégories créées. |
|
|
|
Étape 3: Classer les enseignements à l'aide des {num_bcc} catégories. |
|
""" |
|
print("Classification des enseignements...") |
|
|
|
df = state["dataframe"] |
|
categories = state["categories"] |
|
unique_teachings = df['enseignements'].dropna().unique().tolist() |
|
|
|
|
|
categories_info = "\n".join([f"Catégorie {idx+1}: {cat['nom']} - {cat['description']}" |
|
for idx, cat in enumerate(categories)]) |
|
|
|
|
|
messages = [ |
|
SystemMessage(content=f"""Tu es un expert en sciences de l'éducation, chargé de classifier des enseignements académiques. |
|
Ta tâche est de classer chaque enseignement dans l'une des {num_bcc} catégories suivantes: |
|
|
|
{categories_info} |
|
|
|
Chaque enseignement doit être classé dans UNE SEULE catégorie la plus pertinente. |
|
Réponds UNIQUEMENT au format JSON avec la structure suivante: |
|
{{ |
|
"Nom de la catégorie 1": [liste des enseignements classés dans cette catégorie], |
|
"Nom de la catégorie 2": [liste des enseignements classés dans cette catégorie], |
|
"Nom de la catégorie 3": [liste des enseignements classés dans cette catégorie], |
|
"Nom de la catégorie 4": [liste des enseignements classés dans cette catégorie], |
|
... |
|
}} |
|
|
|
Assure-toi que TOUS les enseignements sont classés et qu'aucun n'est oublié. |
|
"""), |
|
HumanMessage(content=f"Voici la liste des enseignements à classifier: {json.dumps(unique_teachings, ensure_ascii=False)}") |
|
] |
|
|
|
try: |
|
|
|
response = model.invoke(messages) |
|
|
|
|
|
content = response.content |
|
|
|
|
|
if "```json" in content: |
|
content = content.split("```json")[1].split("```")[0].strip() |
|
elif "```" in content: |
|
content = content.split("```")[1].split("```")[0].strip() |
|
|
|
|
|
classified_teachings = json.loads(content) |
|
|
|
|
|
category_names = [cat["nom"] for cat in categories] |
|
for cat_name in category_names: |
|
if cat_name not in classified_teachings: |
|
print(f"Attention: La catégorie '{cat_name}' n'est pas présente dans la classification.") |
|
|
|
|
|
df['catégorie'] = df['enseignements'].apply( |
|
lambda x: next((cat_name for cat_name, teachings in classified_teachings.items() |
|
if x in teachings), None) if pd.notna(x) else None |
|
) |
|
|
|
print("Classification des enseignements réussie.") |
|
|
|
|
|
return { |
|
**state, |
|
"dataframe": df, |
|
"classified_teachings": classified_teachings, |
|
"status": "teachings_classified" |
|
} |
|
|
|
except Exception as e: |
|
print(f"Erreur lors de la classification des enseignements: {e}") |
|
return {**state, "status": "error"} |
|
|
|
def create_learning_situations(state: AgentState, pathname: str = "") -> AgentState: |
|
""" |
|
Crée 4 situations d'apprentissage, une pour chaque catégorie thématique. |
|
|
|
Étape 5: Créer 4 situations d'apprentissage pour les 4 blocs de catégorie d'enseignement. |
|
""" |
|
print("Création des situations d'apprentissage...") |
|
|
|
df = state["dataframe"] |
|
categories = state["categories"] |
|
classified_teachings = state["classified_teachings"] |
|
|
|
|
|
learning_situations = {} |
|
|
|
|
|
for category in categories: |
|
cat_name = category["nom"] |
|
cat_desc = category["description"] |
|
teachings = classified_teachings.get(cat_name, []) |
|
|
|
if not teachings: |
|
print(f"Aucun enseignement classé dans la catégorie '{cat_name}'. Passage à la suivante.") |
|
continue |
|
|
|
|
|
if pathname == "/bcc": |
|
messageSystem = """Tu es un expert en sciences de l'éducation, spécialisé dans la conception de situations d'apprentissage. |
|
|
|
Une situation d'apprentissage est un scénario pédagogique concret qui: |
|
1. Place l'apprenant dans un contexte réaliste et signifiant |
|
2. Mobilise plusieurs connaissances et compétences de façon intégrée |
|
3. Implique la résolution d'un problème ou la réalisation d'une tâche complexe |
|
4. Favorise l'autonomie et la réflexion critique |
|
5. Permet l'évaluation de l'acquisition des savoirs et savoir-faire |
|
|
|
Ta mission est de créer UNE situation d'apprentissage cohérente et détaillée qui: |
|
- Intègre l'ensemble des enseignements de la catégorie fournie |
|
- Soit adaptée au niveau d'études supérieures |
|
- Comprenne un contexte, des objectifs, des activités et des modalités d'évaluation |
|
- Soit rédigée en 150-250 mots |
|
|
|
Réponds en français avec un texte continu, bien structuré, sans titre ni puces. |
|
""" |
|
elif pathname == "/bcc-avid": |
|
messageSystem = """Tu es un expert en pédagogie universitaire et en développement durable, spécialisé dans l'ODD11 (villes et communautés durables). |
|
|
|
Je souhaite créer UNE situation d'apprentissage liée à la ville durable pour une formation d'un niveau d'étude que tu détermines grâce aux objectifs pédagogiques des enseignements concernés. |
|
|
|
Définition d'une situation d'apprentissage: |
|
Une situation d'apprentissage est un scénario pédagogique contextualisé qui place l'apprenant face à un défi concret nécessitant la mobilisation de savoirs, savoir-faire et savoir-être. Elle s'articule autour d'une problématique réelle, favorise l'interdisciplinarité et vise le développement de compétences transversales. |
|
|
|
Objectif de développement durable 11 (ODD11): |
|
L'ODD11 vise à "faire en sorte que les villes et les établissements humains soient ouverts à tous, sûrs, résilients et durables". Cela inclut l'accès au logement décent, aux transports durables, l'urbanisation inclusive, la préservation du patrimoine, la réduction des risques de catastrophes, la qualité de l'air, la gestion des déchets et l'accès aux espaces verts. |
|
|
|
Pour cette catégorie, crée une situation d'apprentissage qui: |
|
1. S'inscrit dans le contexte de la ville durable (ODD11) |
|
2. Mobilise les enseignements de la catégorie |
|
3. Est adaptée au niveau d'étude |
|
4. Propose une mise en situation concrète et professionnalisante |
|
5. Intègre une dimension collaborative et interdisciplinaire |
|
|
|
Réponds en français avec un texte continu, bien structuré, sans titre ni puces.""" |
|
|
|
messages = [ |
|
SystemMessage(content=messageSystem), |
|
HumanMessage(content=f""" |
|
Catégorie: {cat_name} |
|
Description de la catégorie: {cat_desc} |
|
Enseignements concernés: {json.dumps(teachings, ensure_ascii=False)} |
|
|
|
Génère une situation d'apprentissage qui intègre ces enseignements de façon cohérente. |
|
""") |
|
] |
|
|
|
try: |
|
|
|
response = llm.invoke(messages) |
|
|
|
|
|
situation = response.content.strip() |
|
|
|
|
|
learning_situations[cat_name] = situation |
|
|
|
print(f"Situation d'apprentissage créée pour la catégorie '{cat_name}'") |
|
|
|
except Exception as e: |
|
print(f"Erreur lors de la création de la situation d'apprentissage pour '{cat_name}': {e}") |
|
learning_situations[cat_name] = "Erreur: impossible de générer la situation d'apprentissage." |
|
|
|
|
|
df['exemple_situation_apprentissage'] = df['catégorie'].map(learning_situations) |
|
|
|
|
|
return { |
|
**state, |
|
"dataframe": df, |
|
"learning_situations": learning_situations, |
|
"status": "learning_situations_created" |
|
} |
|
|
|
def create_academic_competencies(state: AgentState, pathname: str = "") -> AgentState: |
|
""" |
|
Crée 4 compétences académiques, une pour chaque catégorie thématique. |
|
|
|
Étape 7: Créer 4 compétences académiques, une par bloc composé par une situation |
|
d'apprentissage et des enseignements associés. |
|
""" |
|
print("Création des compétences académiques...") |
|
|
|
df = state["dataframe"] |
|
categories = state["categories"] |
|
classified_teachings = state["classified_teachings"] |
|
learning_situations = state.get("learning_situations", {}) |
|
|
|
|
|
academic_competencies = {} |
|
|
|
|
|
for category in categories: |
|
cat_name = category["nom"] |
|
cat_desc = category["description"] |
|
teachings = classified_teachings.get(cat_name, []) |
|
situation = learning_situations.get(cat_name, "") |
|
|
|
if not teachings: |
|
print(f"Aucun enseignement classé dans la catégorie '{cat_name}'. Passage à la suivante.") |
|
continue |
|
|
|
|
|
if pathname == "/bcc": |
|
messageSystem = """Tu es un expert en sciences de l'éducation, spécialisé dans la formulation de compétences académiques. |
|
|
|
Une compétence académique est: |
|
1. Un savoir-agir complexe prenant appui sur la mobilisation et la combinaison efficaces de ressources internes et externes |
|
2. Une capacité à utiliser efficacement un ensemble de connaissances, d'aptitudes et d'attitudes dans un contexte déterminé |
|
3. Formulée avec un verbe d'action à l'infinitif suivi d'un complément d'objet direct et d'un contexte |
|
4. Évaluable selon des critères de performance définis |
|
|
|
Exemples de formulation: |
|
- "Analyser des problèmes complexes en mobilisant des approches multidisciplinaires pour proposer des solutions innovantes" |
|
- "Concevoir et mettre en œuvre des projets de recherche en respectant les normes éthiques et méthodologiques du domaine" |
|
- "Interpréter des données scientifiques pour prendre des décisions éclairées dans un contexte d'incertitude" |
|
|
|
Ta mission est de formuler UNE compétence académique de niveau universitaire qui: |
|
- Synthétise l'ensemble des enseignements de la catégorie fournie |
|
- S'articule avec la situation d'apprentissage associée |
|
- Soit précise, mesurable et pertinente pour le domaine d'études |
|
- Comporte entre 15 et 25 mots |
|
|
|
Réponds avec une seule phrase complète, sans préambule ni explications. |
|
""" |
|
elif pathname == "/bcc-avid": |
|
messageSystem = """Tu es un expert en ingénierie pédagogique universitaire et en développement durable, spécialisé dans l'ODD11 (villes et communautés durables). |
|
|
|
Je souhaite formuler UNE compétence académique liée à la ville durable pour une formation d'un niveau d'étude que tu détermines grâce aux objectifs pédagogiques des enseignements concernés. |
|
|
|
Définition d'une compétence académique: |
|
Une compétence académique est une capacité avérée à mobiliser des ressources (savoirs, savoir-faire, savoir-être) dans une famille de situations complexes, pour résoudre des problèmes ou réaliser des tâches. Elle est formulée avec un verbe d'action, un objet, un contexte et un niveau de performance attendu. Elle s'inscrit dans une taxonomie (comme celle de Bloom) et peut être évaluée à travers des indicateurs observables. |
|
|
|
Pour cette catégorie, formule une compétence académique qui: |
|
1. Est en lien direct avec la situation d'apprentissage correspondante |
|
2. S'inscrit dans les enjeux de la ville durable (ODD11) |
|
3. Est adaptée au niveau d'étude |
|
4. Est formulée selon le format: "Verbe d'action + objet + contexte + critère de qualité" |
|
5. Est accompagnée d'indicateurs d'évaluation observables |
|
6. Comporte entre 15 et 25 mots |
|
|
|
Utilise les niveaux taxonomiques de Bloom appropriés au niveau d'étude: |
|
- Licence 1-2: se concentrer sur "se rappeler", "comprendre", "appliquer" |
|
- Licence 3/BUT: privilégier "appliquer", "analyser" |
|
- Master: privilégier "analyser", "évaluer", "créer" |
|
|
|
Réponds avec une seule phrase complète, sans préambule ni explications. |
|
""" |
|
|
|
messages = [ |
|
SystemMessage(content=messageSystem), |
|
HumanMessage(content=f""" |
|
Catégorie: {cat_name} |
|
Description de la catégorie: {cat_desc} |
|
Enseignements concernés: {json.dumps(teachings, ensure_ascii=False)} |
|
Situation d'apprentissage associée: {situation} |
|
|
|
Formule une compétence académique qui intègre ces éléments de façon cohérente. |
|
""") |
|
] |
|
|
|
try: |
|
|
|
response = model.invoke(messages) |
|
|
|
|
|
competency = response.content.strip() |
|
|
|
|
|
academic_competencies[cat_name] = competency |
|
|
|
print(f"Compétence académique créée pour la catégorie '{cat_name}'") |
|
|
|
except Exception as e: |
|
print(f"Erreur lors de la création de la compétence académique pour '{cat_name}': {e}") |
|
academic_competencies[cat_name] = "Erreur: impossible de générer la compétence académique." |
|
|
|
|
|
df['BCC'] = df['catégorie'].map(academic_competencies) |
|
df['Bloc de Compétences et de Connaissances'] = df['catégorie'].map(academic_competencies) |
|
|
|
|
|
|
|
|
|
|
|
|
|
return { |
|
**state, |
|
"dataframe": df, |
|
"academic_competencies": academic_competencies, |
|
"status": "academic_competencies_created" |
|
} |
|
|
|
def build_workflow(num_bcc,file,pathname) -> StateGraph: |
|
"""Construit le graphe de workflow LangGraph.""" |
|
|
|
|
|
workflow = StateGraph(AgentState) |
|
|
|
|
|
workflow.add_node("load_and_preprocess", lambda state: load_and_preprocess_csv(state, file)) |
|
workflow.add_node("create_categories", lambda state: create_thematic_categories(state, num_bcc)) |
|
workflow.add_node("classify_teachings", lambda state: classify_teachings(state, num_bcc)) |
|
workflow.add_node("create_learning_situations", lambda state: create_learning_situations(state, pathname)) |
|
|
|
workflow.add_node("create_academic_competencies", lambda state: create_academic_competencies(state, pathname)) |
|
|
|
|
|
|
|
|
|
workflow.add_edge("load_and_preprocess", "create_categories") |
|
workflow.add_edge("create_categories", "classify_teachings") |
|
workflow.add_edge("classify_teachings", "create_learning_situations") |
|
workflow.add_edge("create_learning_situations", "create_academic_competencies") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
workflow.set_entry_point("load_and_preprocess") |
|
|
|
return workflow |
|
|
|
def init_agent_state(current_url, num, pathname) -> AgentState: |
|
initial_state: AgentState = { |
|
|
|
|
|
"files_list": current_url, |
|
"current_file": current_url, |
|
"dataframe": None, |
|
"categories": None, |
|
"classified_teachings": None, |
|
"learning_situations": None, |
|
"academic_competencies": None, |
|
"status": "ready" |
|
} |
|
|
|
|
|
workflow = build_workflow(num,current_url,pathname) |
|
|
|
|
|
app = workflow.compile() |
|
|
|
processed_files = 0 |
|
start_time = time.time() |
|
|
|
result = "" |
|
try: |
|
for s in app.stream(initial_state, {"recursion_limit": 200}): |
|
|
|
|
|
|
|
for task, taskInfo in s.items(): |
|
for key in taskInfo: |
|
if task == "load_and_preprocess": |
|
if key == "current_file": |
|
result += f"Traitement du fichier {taskInfo['current_file']} en cours...\n" |
|
if task == "classify_teachings": |
|
if key == "status": |
|
for key, value in taskInfo['classified_teachings'].items(): |
|
result += f"\n\n-**Enseignement classé dans la catégorie '{key}'** : " |
|
for enseignement in value: |
|
result += f"{enseignement}, " |
|
result += f"\n\nTraitement de la tâche : {taskInfo['status']}...\n" |
|
if task == "create_categories": |
|
if key == "status": |
|
result += f"\n\nTraitement de la tâche : {taskInfo['status']}...\n" |
|
if task == "create_learning_situations": |
|
if key == "status": |
|
if taskInfo['learning_situations'].items(): |
|
for key, value in taskInfo['learning_situations'].items(): |
|
result += f"\n\n-**Situation d'apprentissage créée pour la catégorie '{key}'** : {value}\n" |
|
result += f"\n\nTraitement de la tâche : {taskInfo['status']}...\n" |
|
else: |
|
result += f"\n\nTraitement de la tâche : pas de situations d'apprentissage créées\n" |
|
if task == "create_academic_competencies": |
|
if key == "dataframe": |
|
df = taskInfo['dataframe'] |
|
if key == "status": |
|
if taskInfo['academic_competencies'].items(): |
|
for key, value in taskInfo['academic_competencies'].items(): |
|
result += f"\n\n-**Compétence académique créée pour la catégorie '{key}'** : {value}\n" |
|
result += f"\n\nTraitement de la tâche : {taskInfo['status']}...\n" |
|
else: |
|
result += f"\n\nTraitement de la tâche : pas de BCC créés\n" |
|
if task == "export_to_excel_2": |
|
if key == "status": |
|
result += f"\n\nTraitement de la tâche : {taskInfo['status']}...\n" |
|
|
|
except Exception as e: |
|
print(f"Erreur lors de l'exécution du workflow: {e}") |
|
|
|
try: |
|
return [df,result] |
|
except: |
|
return result |
|
|
|
def getGitFilesFromRepo(DIRECTORY): |
|
contents_url = f"https://api.github.com/repos/{OWNER}/{REPO}/contents/{DIRECTORY}" |
|
|
|
response = requests.get(contents_url, headers=headers, params=params) |
|
items = response.json() |
|
all_files = [] |
|
for item in items: |
|
if item['type'] == 'file': |
|
raw_url = f"https://raw.githubusercontent.com/{OWNER}/{REPO}/main/{item['path']}" |
|
pandas_url = f"{raw_url}?token={ACCESS_TOKEN}" |
|
all_files.append({ |
|
'name': item['name'], |
|
'path': item['path'], |
|
'download_url': item['download_url'], |
|
'pandas_url': pandas_url, |
|
}) |
|
return all_files |
|
|
|
def load_json_files(directory_path: str = "./BCC-Application/JSON"): |
|
if not os.path.exists(directory_path): |
|
print(f"Erreur: Le répertoire {directory_path} n'existe pas.") |
|
return |
|
|
|
|
|
json_files = glob.glob(os.path.join(directory_path, "*.json")) |
|
|
|
if not json_files: |
|
print(f"Aucun fichier JSON trouvé dans le répertoire {directory_path}.") |
|
return |
|
|
|
print(f"Fichiers JSON trouvés: {len(json_files)}") |
|
|
|
|
|
return json_files |
|
|
|
def load_json_AVID_files(directory_path: str = "./VD-Agent/JSON"): |
|
if not os.path.exists(directory_path): |
|
print(f"Erreur: Le répertoire {directory_path} n'existe pas.") |
|
return |
|
|
|
|
|
json_files = glob.glob(os.path.join(directory_path, "*.json")) |
|
|
|
if not json_files: |
|
print(f"Aucun fichier JSON trouvé dans le répertoire {directory_path}.") |
|
return |
|
|
|
print(f"Fichiers JSON trouvés: {len(json_files)}") |
|
|
|
|
|
return json_files |
|
|
|
|
|
def extract_categories_enseignements(data: Dict) -> pd.DataFrame: |
|
"""Extraire les catégories et enseignements associés dans un DataFrame.""" |
|
categories_list = [] |
|
|
|
for categorie in data.get("categories", []): |
|
|
|
cat_name = categorie.get("nom", "") |
|
for enseignement in categorie.get("enseignements", []): |
|
ens_name = enseignement.get("nom", "") |
|
categories_list.append({ |
|
"categorie_id": categorie.get("id", ""), |
|
"categorie_nom": cat_name, |
|
"enseignement_id": enseignement.get("id", ""), |
|
"enseignement_nom": ens_name |
|
}) |
|
|
|
return pd.DataFrame(categories_list) |
|
|
|
|
|
def extract_situations_apprentissage(data: Dict) -> pd.DataFrame: |
|
"""Extraire les situations d'apprentissage dans un DataFrame.""" |
|
situations_list = [] |
|
|
|
for categorie in data.get("categories", []): |
|
cat_id = categorie.get("id", "") |
|
cat_name = categorie.get("nom", "") |
|
|
|
for enseignement in categorie.get("enseignements", []): |
|
ens_id = enseignement.get("id", "") |
|
ens_name = enseignement.get("nom", "") |
|
|
|
for situation in enseignement.get("situations", []): |
|
situations_list.append({ |
|
"categorie_id": cat_id, |
|
"categorie_nom": cat_name, |
|
"enseignement_id": ens_id, |
|
"enseignement_nom": ens_name, |
|
"situation_id": situation.get("id", ""), |
|
"situation_nom": situation.get("nom", ""), |
|
"situation_description": situation.get("description", "") |
|
}) |
|
|
|
return pd.DataFrame(situations_list) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server = flask.Flask(__name__) |
|
|
|
app = dash.Dash(__name__, server=server, external_stylesheets=[dmc.styles.ALL, dbc.themes.DARKLY], |
|
title='BCC Agent', |
|
update_title='Chargement...', |
|
suppress_callback_exceptions=True) |
|
|
|
|
|
server.config['REMEMBER_COOKIE_DURATION'] = timedelta(seconds=3600) |
|
|
|
server.config.update(SECRET_KEY=os.getenv('DASH_APP_SECRET_KEY')) |
|
|
|
|
|
login_manager = LoginManager() |
|
login_manager.init_app(server) |
|
login_manager.login_view = '/' |
|
|
|
|
|
|
|
class User(UserMixin): |
|
def __init__(self, username): |
|
self.id = username |
|
|
|
@ login_manager.user_loader |
|
def load_user(username): |
|
''' This function loads the user by user id. Typically this looks up the user from a user database. |
|
We won't be registering or looking up users in this example, since we'll just login using LDAP server. |
|
So we'll simply return a User object with the passed in username. |
|
''' |
|
return User(username) |
|
|
|
|
|
index_page = dmc.MantineProvider( |
|
[ |
|
dmc.Container( |
|
children=[ |
|
dmc.Grid( |
|
children=[ |
|
dmc.GridCol( |
|
html.Div([dcc.Location(id='url_login', refresh=True), |
|
dmc.Text("BCC Agent", id='h1',style={"fontSize": 48}, fw=900), |
|
dmc.TextInput(placeholder="login",w=250, ml="calc(50% - 125px)", id='uname-box'), |
|
dmc.PasswordInput(id='pwd-box',placeholder="Mot de passe",w=250, ml="calc(50% - 125px)", mt=10), |
|
dmc.Button("Continuer", w=250,variant="gradient", n_clicks=0, id='login-button', mt=20, mb=20), |
|
html.Div(children='', id='output-state') |
|
]), span=4, offset=4, style={'textAlign': 'center', 'marginTop': 'calc(50vh - 120px)','border':'1px solid #495057','border-radius':'10px'}, c='white' |
|
) |
|
] |
|
) |
|
] |
|
)],forceColorScheme="dark" |
|
) |
|
|
|
|
|
success = html.Div([html.Div([html.H2('Login successful.'), |
|
html.Br(), |
|
dcc.Link('Home', href='/')]) |
|
]) |
|
|
|
|
|
failed = html.Div([html.Div([html.H2('Log in Failed. Please try again.'), |
|
html.Br(), |
|
html.Div([index_page]), |
|
dcc.Link('Home', href='/') |
|
]) |
|
]) |
|
|
|
|
|
logout = html.Div([html.Div(html.H2('You have been logged out - Please login')), |
|
html.Br(), |
|
dcc.Link('Home', href='/') |
|
]) |
|
|
|
|
|
@app.callback( |
|
[Output('url_login', 'pathname'), |
|
Output('output-state', 'children')], |
|
[Input('login-button', 'n_clicks')], |
|
[State('uname-box', 'value'), State('pwd-box', 'value')] |
|
) |
|
def login_button_click(n_clicks, username, password): |
|
if n_clicks > 0: |
|
auth = json.loads(os.environ['BCC_AUTH_LOGIN']) |
|
try: |
|
ident = next(d['ident'] for d in auth if d['ident'] == username) |
|
pwd = next(d['pwd'] for d in auth if d['ident'] == username) |
|
resultLogAdmin = bcrypt.checkpw(username.encode('utf-8'), bcrypt.hashpw(ident.encode('utf-8'), bcrypt.gensalt())) |
|
resultPwdAdmin = bcrypt.checkpw(password.encode('utf-8'), bcrypt.hashpw(pwd.encode('utf-8'), bcrypt.gensalt())) |
|
resultRole = next(d['role'] for d in auth if d['ident'] == username) |
|
if resultLogAdmin and resultPwdAdmin: |
|
user = User(username) |
|
login_user(user) |
|
return '/bcc', '' |
|
else: |
|
return '/', 'Login ou Mot de passe incorrect' |
|
except: |
|
return '/', 'Login ou Mot de passe incorrect' |
|
|
|
return dash.no_update, dash.no_update |
|
|
|
|
|
app.layout = dmc.MantineProvider( |
|
[dmc.NotificationProvider(position="top-center"), |
|
html.Div([ |
|
dcc.Location(id='url', refresh=False), |
|
dcc.Location(id='redirect', refresh=True), |
|
dcc.Store(id='login-status', storage_type='session'), |
|
dcc.Store(id="history-store", storage_type="session", data=[]), |
|
dcc.Store(id="model-params-store", storage_type="session", data={"model": "mistralai/Mistral-Small-3.1-24B-Instruct-2503","temperature": 0.7,"max_tokens": 1024,"top_p": 0.9}), |
|
html.Div(id='user-status-div'), |
|
html.Div(id='page-content') |
|
])]) |
|
def layout(**kwargs): |
|
return dmc.MantineProvider( |
|
[ |
|
html.Div([ |
|
dcc.Location(id='url', refresh=False), |
|
dcc.Location(id='redirect', refresh=True), |
|
dcc.Store(id='login-status', storage_type='session'), |
|
dcc.Store(id="history-store", storage_type="session", data=[]), |
|
dcc.Store(id="model-params-store", storage_type="session", data={"model": "mistralai/Mistral-Small-3.1-24B-Instruct-2503","temperature": 0.7,"max_tokens": 1024,"top_p": 0.9}), |
|
html.Div(id='user-status-div'), |
|
html.Div(id='page-content') |
|
]), |
|
],forceColorScheme="dark", span=12, offset=0, c='white') |
|
|
|
app_page = dmc.MantineProvider( |
|
[ |
|
html.Div([ |
|
html.Div( |
|
[ |
|
html.H2("Configuration", className="display-6", style={"font-size": "0.85rem", "font-weight": "bold"}), |
|
html.Hr(), |
|
html.P("Paramètres du modèle LLM", className="lead", style={"font-size": "0.8rem"}), |
|
|
|
html.Div([ |
|
html.Label("Modèle", style={"font-size": "0.75rem"}), |
|
dcc.Dropdown( |
|
id="model-dropdown", |
|
options=[ |
|
{"label": "deepseek R1 8b llama", "value": "deepseek-r1:8b-llama-distill-q4_K_M"}, |
|
{"label": "phi4 14b", "value": "phi4:14b-q8_0"}, |
|
{"label": "gemma3 27b", "value": "gemma3:27b"}, |
|
{"label": "Mistral Small 3.1 24B", "value": "mistralai/Mistral-Small-3.1-24B-Instruct-2503"}, |
|
], |
|
value="mistralai/Mistral-Small-3.1-24B-Instruct-2503", style={"font-size": "0.75rem","color": "rgb(80,106,139)"}, |
|
), |
|
], style={"margin-bottom": "20px"}), |
|
|
|
html.Div([ |
|
html.Label("Température", style={"font-size": "0.75rem"}), |
|
dcc.Slider( |
|
id="temperature-slider", |
|
min=0, |
|
max=1, |
|
step=0.1, |
|
value=0.7, |
|
marks={i/10: str(i/10) for i in range(0, 11)}, |
|
), |
|
], style={"margin-bottom": "20px"}), |
|
|
|
html.Div([ |
|
html.Label("Longueur maximale (tokens)", style={"font-size": "0.75rem"}), |
|
dcc.Input( |
|
id="max-tokens-input", |
|
type="number", |
|
min=100, |
|
max=4096, |
|
step=50, |
|
value=2048, |
|
), |
|
], style={"font-size": "0.75rem","margin-bottom": "20px"}), |
|
|
|
html.Div([ |
|
html.Label("Top P", style={"font-size": "0.75rem"}), |
|
dcc.Slider( |
|
id="top-p-slider", |
|
min=0, |
|
max=1, |
|
step=0.1, |
|
value=0.9, |
|
marks={i/10: str(i/10) for i in range(0, 11)}, |
|
), |
|
], style={"margin-bottom": "20px"}), |
|
html.Div([ |
|
html.Button( |
|
"Appliquer les paramètres", |
|
id="apply-params-button", |
|
className="btn w-100", |
|
style={"margin-bottom":"2rem","border":"1px solid white","background": "linear-gradient(to right, #00F3FF 0%, #7f00b2 100%)", "-webkit-background-clip": "text","-webkit-text-fill-color": "transparent","font-size": "0.75rem"}, |
|
), |
|
dmc.Alert( |
|
title="Configuration du LLM", |
|
id="notification-model", |
|
color="green", |
|
duration=5000, |
|
withCloseButton=True, |
|
hide=True, |
|
style={"z-index":"100","width":"300px","position":"fixed","top":"2px", "left":"calc(50% - 150px)","font-size": "0.75rem","margin-bottom":"1rem"}, |
|
), |
|
dcc.Link('BCC', id="link-bcc", href='/bcc', style={"margin-right":"0.2rem","padding":"0.25rem 0.175rem","background":"linear-gradient(to right, rgb(90, 176, 242) 0%, rgb(90, 176, 242) 100%)","color":"white","font-size": "0.75rem","border-radius":"5px"}), |
|
dcc.Link('BCC-AVID', id="link-bcc-avid", href='/bcc-avid', style={"margin-right":"0.2rem","padding":"0.25rem 0.175rem","background":"linear-gradient(to right, rgb(90, 176, 242) 0%, rgb(90, 176, 242) 100%)","color":"white","font-size": "0.75rem","border-radius":"5px"}), |
|
dbc.Tooltip("Gérer les BCC des maquettes de formation", target="link-bcc"), |
|
dbc.Tooltip("Gérer les BCC AVID", target="link-bcc-avid"), |
|
]), |
|
], |
|
style=SIDEBAR_STYLE, |
|
), |
|
|
|
|
|
dmc.Tabs( |
|
variant="outline",value="first", |
|
children=[ |
|
dmc.TabsList(mx="auto",grow=True,mb="md", style={"margin-top":"-1.5rem"}, |
|
children=[ |
|
dmc.TabsTab("Réécriture des compétences", value="first"), |
|
dmc.TabsTab("Re-génération des BCC", value="second", color="blue"), |
|
] |
|
), |
|
dmc.TabsPanel( |
|
value="first", |
|
children=[ |
|
html.H1("Réécriture des Blocs de Connaissances et Compétences (BCC)", className="mb-4", style={"font-size": "1.5rem", "font-weight": "bold"}), |
|
html.P("Utilisez ce playground pour générer des compétences académiques basées sur des catégories d'enseignement et des situations d'apprentissage.", className="lead mb-4", style={"font-size": "1rem"}), |
|
|
|
|
|
|
|
dbc.Row([ |
|
dbc.Col([ |
|
dmc.Modal(title="Maquette de formation en BCC",id="modal-description-skills", |
|
children=[ |
|
dcc.Loading( |
|
id="loadingSkills", |
|
children=[ |
|
html.Div(id="modal-text-skills", style={"font-size":"0.8em"}), |
|
], |
|
overlay_style={"visibility":"visible", "filter": "blur(2px)"}, type="default" |
|
) |
|
], size="lg" |
|
), |
|
dmc.Modal(id="modal-description-categorisation", |
|
children=[ |
|
dcc.Loading( |
|
id="loadingCategorisation", |
|
children=[ |
|
dcc.Markdown(id="modal-text-categorisation", style={"font-size":"0.8em"}), |
|
], |
|
overlay_style={"visibility":"visible", "filter": "blur(2px)"}, type="default" |
|
) |
|
], size="lg" |
|
), |
|
dmc.Modal(id="modal-description-classification", |
|
children=[ |
|
dcc.Loading( |
|
id="loadingClassification", |
|
children=[ |
|
dcc.Markdown(id="modal-text-classification", style={"font-size":"0.8em"}), |
|
], |
|
overlay_style={"visibility":"visible", "filter": "blur(2px)"}, type="default" |
|
) |
|
], size="lg" |
|
), |
|
dmc.Modal(id="modal-description-situation", |
|
children=[ |
|
dcc.Loading( |
|
id="loadingSituation", |
|
children=[ |
|
dcc.Markdown(id="modal-text-situation", style={"font-size":"0.8em"}), |
|
], |
|
overlay_style={"visibility":"visible", "filter": "blur(2px)"}, type="default" |
|
) |
|
], size="lg" |
|
), |
|
dmc.Drawer( |
|
title="Génération de nouvelles propositions de compétence académique", |
|
children=[dbc.Container( |
|
fluid=False, |
|
children=[ |
|
html.Div(id="BCC-status", className="mb-3"), |
|
dbc.Spinner( |
|
html.Div(id="BCC-output", className="p-3", style={"font-size":"0.75rem"}), |
|
), |
|
], |
|
) |
|
], |
|
id="drawer-BCC", |
|
padding="md", |
|
size="33%", |
|
position="right",opened=False |
|
), |
|
dbc.Row( |
|
[ |
|
dbc.Col(html.Img(src="./assets/jsonfile.png", height="36px", className="ml-3", style={"margin-top": "-0.5rem"}),sm=0.5), |
|
dbc.Col(html.H3("Sélectionnez un fichier", className="mb-3", style={"font-size": "1rem"}),sm=6), |
|
dbc.Col(dmc.Button(leftSection=html.Img(src="./assets/eye.png", height="24px"), id="show-modal-skills",disabled=True, style={"margin-top":"-0.5rem", "margin-left":"-2rem", "background-color": "transparent", "border": "none", "color": "white"}), |
|
align="left",md=2), |
|
], |
|
align="left", |
|
className="g-0" |
|
), |
|
dcc.Dropdown( |
|
id="categorie-dropdown", |
|
options=[ |
|
{"label": re.sub(r'[^a-zA-Z0-9]', '', fileJson['name']).replace("json",""), "value": fileJson['path']} |
|
for fileJson in getGitFilesFromRepo('JSON') |
|
], |
|
|
|
value='./BCC-Application/JSON/L1-Anglais.json', |
|
placeholder="Choisir une maquette de formation avec propositions BCC", |
|
style={"color": "rgb(80,106,139)","font-size": "0.75rem","border":"border 1px solid rgb(67,167,255)!important"}, |
|
), |
|
], md=6), |
|
dbc.Col([ |
|
dbc.Button( |
|
"Générer les propositions de BCC", |
|
id="generate-button", |
|
disabled=True, |
|
style={"margin-top":"2.2rem","background":"linear-gradient(to right, #00F3FF 0%, #7f00b2 100%)","color":"white","font-size": "0.75rem"}, |
|
), |
|
], md=2), |
|
dbc.Col( |
|
dmc.Button(leftSection=html.Img(src="./assets/eye.png", height="24px"), id="show-drawer",style={"margin-left":"-2rem", "margin-top":"2rem", "background-color": "transparent", "border": "none", "color": "white"}), |
|
align="left",md=2), |
|
], className="mb-4"), |
|
|
|
|
|
dbc.Row([ |
|
dbc.Col([ |
|
dbc.Row( |
|
[ |
|
dbc.Col(html.Img(src="./assets/classification.png", height="36px", className="ml-3", style={"margin-top": "-0.7rem"}),sm=0.5), |
|
dbc.Col(html.H3("Catégorisation des enseignements", className="mb-3", style={"font-size": "1rem"}),sm=6), |
|
dbc.Col(dmc.Button(leftSection=html.Img(src="./assets/eye.png", height="24px"), id="show-modal-categorisation",style={"margin-top":"-0.5rem", "margin-left":"-2rem", "background-color": "transparent", "border": "none", "color": "white"}), |
|
align="left",md=2), |
|
], |
|
align="left", |
|
className="g-0" |
|
), |
|
html.H4(id="text-enseignement-dropdown", className="mb-3 text-success", style={"font-size": "0.7rem"}), |
|
dcc.Loading(dbc.Textarea(id="enseignement-dropdown", className="mb-3", style={"height":"200px", "max-height":"250px", "font-size": "0.75rem","color":"white","border":"border 1px solid rgb(67,167,255)!important", "background-color":"transparent"}),), |
|
], md=6), |
|
dbc.Col([ |
|
dbc.Row( |
|
[ |
|
dbc.Col(html.Img(src="./assets/generation.png", height="36px", className="ml-3", style={"margin-top": "-0.7rem"}),sm=0.5), |
|
dbc.Col(html.H3("Classification des enseignements", className="mb-3", style={"font-size": "1rem"}),sm=6), |
|
dbc.Col(dmc.Button(leftSection=html.Img(src="./assets/eye.png", height="24px"), id="show-modal-classification",style={"margin-top":"-0.5rem", "margin-left":"-2rem", "background-color": "transparent", "border": "none", "color": "white"}), |
|
align="left",md=2), |
|
], |
|
align="left", |
|
className="g-0" |
|
), |
|
html.H4("Choisir d'abord une maquette de formation avec propositions BCC", className="mb-3", style={"font-size": "0.7rem"}), |
|
dcc.Loading(dbc.Textarea(id="classification-dropdown", className="mb-3", placeholder="Choisir d'abord une maquette avec propositions BCC", style={"height":"200px", "max-height":"250px", "font-size": "0.75rem","color":"white","border":"border 1px solid rgb(67,167,255)!important", "background-color":"transparent"}),), |
|
], md=6) |
|
]), |
|
dbc.Row([ |
|
dbc.Col([ |
|
dbc.Row( |
|
[ |
|
dbc.Col(html.Img(src="./assets/situation.png", height="36px", className="ml-3", style={"margin-top": "-0.3rem"}),sm=0.5), |
|
dbc.Col(html.H3("Définition des situations d'apprentissage", className="mb-3", style={"font-size": "1rem"}),sm=6), |
|
dbc.Col(dmc.Button(leftSection=html.Img(src="./assets/eye.png", height="24px"), id="show-modal-situation",style={"margin-top":"-0.5rem", "margin-left":"-2rem", "background-color": "transparent", "border": "none", "color": "white"}), |
|
align="left",md=2), |
|
], |
|
align="left", |
|
className="g-0" |
|
), |
|
html.H4("Choisir d'abord une maquette de formation avec propositions BCC", className="mb-3", style={"font-size": "0.7rem"}), |
|
dcc.Loading(dbc.Textarea(id="situation-dropdown", className="mb-3", placeholder="Choisir d'abord une maquette avec propositions BCC", style={"height":"200px", "max-height":"250px", "font-size": "0.75rem","color":"white","border":"border 1px solid rgb(67,167,255)!important", "background-color":"transparent"}),), |
|
], md=6), |
|
dbc.Col([ |
|
dbc.Row( |
|
[ |
|
dbc.Col(html.Img(src="./assets/requete.png", height="36px", className="ml-3", style={"margin-top": "-0.3rem"}),sm=0.5), |
|
dbc.Col(html.H3("Prompt pour la création des BCC", className="mb-3", style={"font-size": "1rem"}),sm=6), |
|
], |
|
align="left", |
|
className="g-0" |
|
), |
|
html.H4("Choisir d'abord une maquette de formation avec propositions BCC", className="mb-3", style={"font-size": "0.7rem"}), |
|
dbc.Textarea(value="""Ta mission est de formuler QUATRE compétences académiques de niveau universitaire qui: |
|
- Synthétisent l'ensemble des enseignements de la catégorie fournie |
|
- S'articulent avec la situation d'apprentissage associée |
|
- Soient précise, mesurable et pertinente pour le domaine d'études |
|
- Comportent entre 15 et 25 mots |
|
|
|
Réponds, absolument en langue française, avec une seule proposition complète à la fois, pour les QUATRE compétences, sans préambule ni explications. |
|
|
|
Pour chacune des 4 catégories, formule une compétence académique qui: |
|
1. Est clairement formulée avec un verbe d'action |
|
2. Précise les ressources mobilisées (savoirs, savoir-faire, savoir-être) |
|
3. Indique le niveau de performance attendu |
|
4. Est évaluable par des critères observables |
|
5. S'inscrit dans le contexte spécifique de l'enseignement et de la situation d'apprentissage |
|
|
|
Utilise les niveaux taxonomiques de Bloom appropriés au niveau d'étude: |
|
- Licence 1-2: se concentrer sur "se rappeler", "comprendre", "appliquer" |
|
- Licence 3/BUT: privilégier "appliquer", "analyser" |
|
- Master: privilégier "analyser", "évaluer", "créer" |
|
|
|
Formule des compétences académiques qui intègrent ces éléments de façon cohérente. |
|
Donne le niveau de la taxonomie de Bloom pour chaque compétence académique entre parenthèses. |
|
Indique en informations complémentaire au format liste à puces, en petites polices de caractère : le verbe d'action, les ressources mobilisées, le niveau de performance attendu, les critères d'évaluation, le niveau taxonomique Bloom. |
|
""",id="requete-dropdown", className="mb-3", placeholder="Choisir d'abord une maquette avec propositions BCC", style={"height":"200px", "max-height":"250px", "font-size": "0.75rem","color":"rgb(90, 176, 242)","border":"border 1px solid rgb(90, 176, 242)!important", "background-color":"rgba(90, 176, 242, 0.2)"}), |
|
], md=6), |
|
], className="mb-4"), |
|
|
|
|
|
dbc.Row([ |
|
dbc.Col([ |
|
html.Div(id="selection-display", className="p-3 border rounded mb-4") |
|
], md=12), |
|
]), |
|
|
|
|
|
dbc.Row([ |
|
dbc.Col([ |
|
dbc.Row( |
|
[ |
|
dbc.Col(html.Img(src="./assets/requete.png", height="36px", className="ml-3", style={"margin-top": "-0.3rem"}),sm=0.5), |
|
dbc.Col(html.H3("Génération de nouvelles propositions de compétence académique", className="mb-3", style={"font-size": "1rem"}),sm=6), |
|
], |
|
align="left", |
|
className="g-0" |
|
), |
|
html.Div(id="generation-status", className="mb-3"), |
|
dbc.Spinner( |
|
html.Div(id="competence-output", className="p-3 border rounded", style={"color":"rgb(90, 242, 156)","border-color":"rgb(90, 242, 156)!important","background-color":"rgba(90, 242, 156, 0.2)"}), |
|
), |
|
], md=12), |
|
]), |
|
|
|
|
|
dbc.Row([ |
|
dbc.Col([ |
|
html.H3("Historique des générations", className="mt-5 mb-3", style={"font-size": "1rem"}), |
|
html.Div(id="history-container", className="border rounded p-3"), |
|
], md=12), |
|
]), |
|
]), |
|
dmc.TabsPanel( |
|
value="second", |
|
children=[ |
|
dbc.Container([ |
|
dbc.Row([ |
|
dbc.Col([ |
|
dbc.Row([html.H1("Re-génération des Blocs de Connaissances et Compétences (BCC) à partir des maquettes de formations brutes", className="mb-4", style={"font-size": "1.5rem", "font-weight": "bold"}), |
|
dbc.Col(html.Img(src="./assets/jsonfile.png", height="36px", className="ml-3", style={"margin-top": "-0.5rem"}),sm=0.5), |
|
dbc.Col(html.H3("Sélectionnez une maquette de formation", className="mb-3", style={"font-size": "1rem"}),sm=10), |
|
dbc.Col(dcc.Dropdown( |
|
id="maquette-dropdown", |
|
options=[ |
|
{"label": re.sub(r'[^a-zA-Z0-9]', '', fileJson['name']).replace("csv",""), "value": fileJson['pandas_url']} |
|
for fileJson in getGitFilesFromRepo('CSV') |
|
], |
|
placeholder="Choisir une maquette de formation avec propositions BCC", |
|
style={"color": "rgb(80,106,139)","font-size": "0.75rem","border":"border 1px solid rgb(67,167,255)!important","margin-bottom":"0.5rem"}, |
|
),sm=6), |
|
]), |
|
dbc.Row( |
|
[ |
|
dbc.Col(html.Img(src="./assets/jsonfile.png", height="36px", className="ml-3", style={"margin-top": "-0.5rem"}),sm=0.5), |
|
dbc.Col(html.H3("Sélectionnez un nombre de nouveaux BCC à générer", className="mb-3", style={"font-size": "1rem"}),sm=10), |
|
], |
|
align="left", |
|
className="g-0" |
|
), |
|
dbc.Row( |
|
[ |
|
dbc.Col(dcc.Dropdown( |
|
id="num-bcc", |
|
options=[ |
|
{"label": "3", "value": "3"}, |
|
{"label": "4", "value": "4"}, |
|
{"label": "5", "value": "5"}, |
|
{"label": "6", "value": "6"}, |
|
{"label": "7", "value": "7"}, |
|
], |
|
value=4, |
|
placeholder="Choisir un nombre de BCC à générer", |
|
style={"color": "rgb(80,106,139)","font-size": "0.75rem","border":"border 1px solid rgb(67,167,255)!important","margin-bottom":"0.5rem"}, |
|
),sm=6), |
|
]), |
|
dbc.Row(dbc.Col(dbc.Button('Créer les nouveaux BCC et les nouvelles situations', id='submit-button', n_clicks=0, style={"background":"linear-gradient(to right, #00F3FF 0%, #7f00b2 100%)","color":"white","font-size": "0.75rem","margin-bottom":"2rem"}),sm=12)) |
|
], width=12) |
|
]), |
|
dbc.Row([ |
|
dbc.Col([ |
|
dbc.Row( |
|
[ |
|
dbc.Col(html.Img(src="./assets/requete.png", height="36px", className="ml-3", style={"margin-top": "-0.3rem"}),sm=0.5), |
|
dbc.Col(html.H3("Re-génération des nouvelles propositions de BCC", className="mb-3", style={"font-size": "1rem"}),sm=6), |
|
], |
|
align="left", |
|
className="g-0" |
|
), |
|
dcc.Loading(html.Div(id='output-response', style={"color":"rgb(90, 242, 156)","border-radius":"3px","border":"1px solid rgb(255,255,255)!important","background-color":"rgba(90, 242, 156, 0.2)","padding":"5px"}),), |
|
|
|
], width=12) |
|
]) |
|
], className="mt-5")], |
|
), |
|
]), |
|
|
|
|
|
html.Footer([ |
|
html.Hr(), |
|
html.P( |
|
"Cette application utilise les données d'ingénierie en pédagogie de l'université Gustave Eiffel et notamment les maquettes de formation et les process dans une démarche d'approche par compétences.", |
|
className="text-muted" |
|
), |
|
], className="mt-5"), |
|
|
|
], style=CONTENT_STYLE)],forceColorScheme="dark") |
|
|
|
app_avid_page = dmc.MantineProvider( |
|
[ |
|
html.Div([ |
|
html.Div( |
|
[ |
|
html.H2("Configuration", className="display-6", style={"font-size": "0.85rem", "font-weight": "bold"}), |
|
html.Hr(), |
|
html.P("Paramètres du modèle LLM", className="lead", style={"font-size": "0.8rem"}), |
|
|
|
html.Div([ |
|
html.Label("Modèle", style={"font-size": "0.75rem"}), |
|
dcc.Dropdown( |
|
id="model-dropdown", |
|
options=[ |
|
{"label": "deepseek R1 8b llama", "value": "deepseek-r1:8b-llama-distill-q4_K_M"}, |
|
{"label": "phi4 14b", "value": "phi4:14b-q8_0"}, |
|
{"label": "gemma3 27b", "value": "gemma3:27b"}, |
|
{"label": "Mistral Small 3.1 24B", "value": "mistralai/Mistral-Small-3.1-24B-Instruct-2503"}, |
|
], |
|
value="mistralai/Mistral-Small-3.1-24B-Instruct-2503", style={"font-size": "0.75rem","color": "rgb(80,106,139)"}, |
|
), |
|
], style={"margin-bottom": "20px"}), |
|
|
|
html.Div([ |
|
html.Label("Température", style={"font-size": "0.75rem"}), |
|
dcc.Slider( |
|
id="temperature-slider", |
|
min=0, |
|
max=1, |
|
step=0.1, |
|
value=0.7, |
|
marks={i/10: str(i/10) for i in range(0, 11)}, |
|
), |
|
], style={"margin-bottom": "20px"}), |
|
|
|
html.Div([ |
|
html.Label("Longueur maximale (tokens)", style={"font-size": "0.75rem"}), |
|
dcc.Input( |
|
id="max-tokens-input", |
|
type="number", |
|
min=100, |
|
max=4096, |
|
step=50, |
|
value=2048, |
|
), |
|
], style={"font-size": "0.75rem","margin-bottom": "20px"}), |
|
|
|
html.Div([ |
|
html.Label("Top P", style={"font-size": "0.75rem"}), |
|
dcc.Slider( |
|
id="top-p-slider", |
|
min=0, |
|
max=1, |
|
step=0.1, |
|
value=0.9, |
|
marks={i/10: str(i/10) for i in range(0, 11)}, |
|
), |
|
], style={"margin-bottom": "20px"}), |
|
|
|
html.Div([ |
|
html.Button( |
|
"Appliquer les paramètres", |
|
id="apply-params-button", |
|
className="btn w-100", |
|
style={"margin-bottom":"2rem","border":"1px solid white","background": "linear-gradient(to right, #00F3FF 0%, #7f00b2 100%)", "-webkit-background-clip": "text","-webkit-text-fill-color": "transparent","font-size": "0.75rem"}, |
|
), |
|
dmc.Alert( |
|
title="Configuration du LLM", |
|
id="notification-model", |
|
color="green", |
|
duration=5000, |
|
withCloseButton=True, |
|
hide=True, |
|
style={"z-index":"100","width":"300px","position":"fixed","top":"2px", "left":"calc(50% - 150px)","font-size": "0.75rem","margin-bottom":"1rem"}, |
|
), |
|
dcc.Link('BCC', id="link-bcc", href='/bcc', style={"margin-right":"0.2rem","padding":"0.25rem 0.175rem","background":"linear-gradient(to right, rgb(90, 176, 242) 0%, rgb(90, 176, 242))","color":"white","font-size": "0.75rem","border-radius":"5px"}), |
|
dcc.Link('BCC-AVID', id="link-bcc-avid", href='/bcc-avid', style={"margin-right":"0.2rem","padding":"0.25rem 0.175rem","background":"linear-gradient(to right, rgb(90, 176, 242) 0%, rgb(90, 176, 242) 100%)","color":"white","font-size": "0.75rem","border-radius":"5px"}), |
|
dbc.Tooltip("Gérer les BCC des maquettes de formation", target="link-bcc"), |
|
dbc.Tooltip("Gérer les BCC AVID", target="link-bcc-avid"), |
|
]), |
|
], |
|
style=SIDEBAR_STYLE, |
|
), |
|
|
|
dmc.Tabs( |
|
variant="outline",value="first", |
|
children=[ |
|
dmc.TabsList(mx="auto",grow=True,mb="md", style={"margin-top":"-1.5rem"}, |
|
children=[ |
|
dmc.TabsTab("Réécriture des compétences", value="first"), |
|
dmc.TabsTab("Re-génération des BCC", value="second", color="blue"), |
|
] |
|
), |
|
dmc.TabsPanel( |
|
value="first", |
|
children=[ |
|
html.H1("Réécriture des Blocs de Connaissances et Compétences (BCC) AVID", className="mb-4", style={"font-size": "1.5rem", "font-weight": "bold"}), |
|
html.P("Utilisez ce playground pour générer des compétences académiques basées sur des catégories d'enseignement et des situations d'apprentissage relatives aux thématiques de l'ODD11.", className="lead mb-4", style={"font-size": "1rem"}), |
|
|
|
|
|
|
|
dbc.Row([ |
|
dbc.Col([ |
|
dmc.Modal(title="Maquette de formation en BCC",id="modal-description-skills", |
|
children=[ |
|
dcc.Loading( |
|
id="loadingSkills", |
|
children=[ |
|
html.Div(id="modal-text-skills", style={"font-size":"0.8em"}), |
|
], |
|
overlay_style={"visibility":"visible", "filter": "blur(2px)"}, type="default" |
|
) |
|
], size="lg" |
|
), |
|
dmc.Modal(id="modal-description-categorisation", |
|
children=[ |
|
dcc.Loading( |
|
id="loadingCategorisation", |
|
children=[ |
|
dcc.Markdown(id="modal-text-categorisation", style={"font-size":"0.8em"}), |
|
], |
|
overlay_style={"visibility":"visible", "filter": "blur(2px)"}, type="default" |
|
) |
|
], size="lg" |
|
), |
|
dmc.Modal(id="modal-description-classification", |
|
children=[ |
|
dcc.Loading( |
|
id="loadingClassification", |
|
children=[ |
|
dcc.Markdown(id="modal-text-classification", style={"font-size":"0.8em"}), |
|
], |
|
overlay_style={"visibility":"visible", "filter": "blur(2px)"}, type="default" |
|
) |
|
], size="lg" |
|
), |
|
dmc.Modal(id="modal-description-situation", |
|
children=[ |
|
dcc.Loading( |
|
id="loadingSituation", |
|
children=[ |
|
dcc.Markdown(id="modal-text-situation", style={"font-size":"0.8em"}), |
|
], |
|
overlay_style={"visibility":"visible", "filter": "blur(2px)"}, type="default" |
|
) |
|
], size="lg" |
|
), |
|
dmc.Drawer( |
|
title="Génération de nouvelles propositions de compétence académique AVID", |
|
children=[dbc.Container( |
|
fluid=False, |
|
children=[ |
|
html.Div(id="BCC-status", className="mb-3"), |
|
dbc.Spinner( |
|
html.Div(id="BCC-output", className="p-3", style={"font-size":"0.75rem"}), |
|
), |
|
], |
|
) |
|
], |
|
id="drawer-BCC", |
|
padding="md", |
|
size="33%", |
|
position="right",opened=False |
|
), |
|
dbc.Row( |
|
[ |
|
dbc.Col(html.Img(src="./assets/jsonfile.png", height="36px", className="ml-3", style={"margin-top": "-0.5rem"}),sm=0.5), |
|
dbc.Col(html.H3("Sélectionnez un fichier", className="mb-3", style={"font-size": "1rem"}),sm=6), |
|
dbc.Col(dmc.Button(leftSection=html.Img(src="./assets/eye.png", height="24px"), id="show-modal-skills",disabled=True, style={"margin-top":"-0.5rem", "margin-left":"-2rem", "background-color": "transparent", "border": "none", "color": "white"}), |
|
align="left",md=2), |
|
], |
|
align="left", |
|
className="g-0" |
|
), |
|
dcc.Dropdown( |
|
id="categorie-dropdown", |
|
options=[ |
|
{"label": re.sub(r'[^a-zA-Z0-9]', '', fileJson['name']).replace("json",""), "value": fileJson['path']} |
|
for fileJson in getGitFilesFromRepo('VD/JSON') |
|
], |
|
placeholder="Choisir une maquette de formation avec propositions BCC AVID", |
|
style={"color": "rgb(80,106,139)","font-size": "0.75rem","border":"border 1px solid rgb(67,167,255)!important"}, |
|
), |
|
], md=6), |
|
dbc.Col([ |
|
dbc.Button( |
|
"Générer les propositions de BCC AVID", |
|
id="generate-button", |
|
disabled=True, |
|
style={"margin-top":"2.2rem","background":"linear-gradient(to right, #00F3FF 0%, #7f00b2 100%)","color":"white","font-size": "0.75rem"}, |
|
), |
|
], md=2), |
|
dbc.Col( |
|
dmc.Button(leftSection=html.Img(src="./assets/eye.png", height="24px"), id="show-drawer",style={"margin-left":"-2rem", "margin-top":"2rem", "background-color": "transparent", "border": "none", "color": "white"}), |
|
align="left",md=2), |
|
], className="mb-4"), |
|
|
|
|
|
dbc.Row([ |
|
dbc.Col([ |
|
dbc.Row( |
|
[ |
|
dbc.Col(html.Img(src="./assets/classification.png", height="36px", className="ml-3", style={"margin-top": "-0.7rem"}),sm=0.5), |
|
dbc.Col(html.H3("Catégorisation des enseignements", className="mb-3", style={"font-size": "1rem"}),sm=6), |
|
dbc.Col(dmc.Button(leftSection=html.Img(src="./assets/eye.png", height="24px"), id="show-modal-categorisation",style={"margin-top":"-0.5rem", "margin-left":"-2rem", "background-color": "transparent", "border": "none", "color": "white"}), |
|
align="left",md=2), |
|
], |
|
align="left", |
|
className="g-0" |
|
), |
|
html.H4(id="text-enseignement-dropdown", className="mb-3 text-success", style={"font-size": "0.7rem"}), |
|
dbc.Textarea(id="enseignement-dropdown", className="mb-3", style={"height":"200px", "max-height":"250px", "font-size": "0.75rem","color":"white","border":"border 1px solid rgb(67,167,255)!important", "background-color":"transparent"}), |
|
], md=6), |
|
dbc.Col([ |
|
dbc.Row( |
|
[ |
|
dbc.Col(html.Img(src="./assets/generation.png", height="36px", className="ml-3", style={"margin-top": "-0.7rem"}),sm=0.5), |
|
dbc.Col(html.H3("Classification des enseignements", className="mb-3", style={"font-size": "1rem"}),sm=6), |
|
dbc.Col(dmc.Button(leftSection=html.Img(src="./assets/eye.png", height="24px"), id="show-modal-classification",style={"margin-top":"-0.5rem", "margin-left":"-2rem", "background-color": "transparent", "border": "none", "color": "white"}), |
|
align="left",md=2), |
|
], |
|
align="left", |
|
className="g-0" |
|
), |
|
html.H4("Choisir d'abord une maquette de formation avec propositions BCC AVID", className="mb-3", style={"font-size": "0.7rem"}), |
|
dbc.Textarea(id="classification-dropdown", className="mb-3", placeholder="Choisir d'abord une maquette avec propositions BCC AVID", style={"height":"200px", "max-height":"250px", "font-size": "0.75rem","color":"white","border":"border 1px solid rgb(67,167,255)!important", "background-color":"transparent"}), |
|
], md=6) |
|
]), |
|
dbc.Row([ |
|
dbc.Col([ |
|
dbc.Row( |
|
[ |
|
dbc.Col(html.Img(src="./assets/situation.png", height="36px", className="ml-3", style={"margin-top": "-0.3rem"}),sm=0.5), |
|
dbc.Col(html.H3("Définition des situations d'apprentissage", className="mb-3", style={"font-size": "1rem"}),sm=6), |
|
dbc.Col(dmc.Button(leftSection=html.Img(src="./assets/eye.png", height="24px"), id="show-modal-situation",style={"margin-top":"-0.5rem", "margin-left":"-2rem", "background-color": "transparent", "border": "none", "color": "white"}), |
|
align="left",md=2), |
|
], |
|
align="left", |
|
className="g-0" |
|
), |
|
html.H4("Choisir d'abord une maquette de formation avec propositions BCC AVID", className="mb-3", style={"font-size": "0.7rem"}), |
|
dbc.Textarea(id="situation-dropdown", className="mb-3", placeholder="Choisir d'abord une maquette avec propositions BCC AVID", style={"height":"200px", "max-height":"250px", "font-size": "0.75rem","color":"white","border":"border 1px solid rgb(67,167,255)!important", "background-color":"transparent"}), |
|
], md=6), |
|
dbc.Col([ |
|
dbc.Row( |
|
[ |
|
dbc.Col(html.Img(src="./assets/requete.png", height="36px", className="ml-3", style={"margin-top": "-0.3rem"}),sm=0.5), |
|
dbc.Col(html.H3("Prompt pour la création des BCC AVID", className="mb-3", style={"font-size": "1rem"}),sm=6), |
|
], |
|
align="left", |
|
className="g-0" |
|
), |
|
html.H4("Choisir d'abord une maquette de formation avec propositions BCC AVID", className="mb-3", style={"font-size": "0.7rem"}), |
|
dbc.Textarea(value="""Pour chacune des 4 catégories, formule une compétence académique qui: |
|
1. Est en lien direct avec la situation d'apprentissage correspondante |
|
2. S'inscrit dans les enjeux de la ville durable (ODD11) |
|
3. Est adaptée au niveau d'étude |
|
4. Est formulée selon le format: "Verbe d'action + objet + contexte + critère de qualité" |
|
5. Est accompagnée d'indicateurs d'évaluation observables |
|
|
|
Réponds, absolument en langue française, avec une seule proposition complète à la fois, pour les QUATRE compétences, sans préambule ni explications. |
|
|
|
Utilise les niveaux taxonomiques de Bloom appropriés au niveau d'étude: |
|
- Licence 1-2: se concentrer sur "se rappeler", "comprendre", "appliquer" |
|
- Licence 3/BUT: privilégier "appliquer", "analyser" |
|
- Master: privilégier "analyser", "évaluer", "créer" |
|
|
|
Formule des compétences académiques qui intègrent ces éléments de façon cohérente. |
|
Donne le niveau de la taxonomie de Bloom pour chaque compétence académique entre parenthèses. |
|
Indique en informations complémentaire au format liste à puces, en petites polices de caractère : le verbe d'action, les ressources mobilisées, le niveau de performance attendu, les critères d'évaluation, le niveau taxonomique Bloom. |
|
""",id="requete-dropdown", className="mb-3", placeholder="Choisir d'abord une maquette avec propositions BCC", style={"height":"200px", "max-height":"250px", "font-size": "0.75rem","color":"rgb(90, 176, 242)","border":"border 1px solid rgb(90, 176, 242)!important", "background-color":"rgba(90, 176, 242, 0.2)"}), |
|
], md=6), |
|
], className="mb-4"), |
|
|
|
|
|
dbc.Row([ |
|
dbc.Col([ |
|
html.Div(id="selection-display", className="p-3 border rounded mb-4") |
|
], md=12), |
|
]), |
|
|
|
|
|
dbc.Row([ |
|
dbc.Col([ |
|
dbc.Row( |
|
[ |
|
dbc.Col(html.Img(src="./assets/requete.png", height="36px", className="ml-3", style={"margin-top": "-0.3rem"}),sm=0.5), |
|
dbc.Col(html.H3("Génération de nouvelles propositions de compétence académique AVID", className="mb-3", style={"font-size": "1rem"}),sm=6), |
|
], |
|
align="left", |
|
className="g-0" |
|
), |
|
html.Div(id="generation-status", className="mb-3"), |
|
dbc.Spinner( |
|
html.Div(id="competence-output", className="p-3 border rounded", style={"color":"rgb(90, 242, 156)","border-color":"rgb(90, 242, 156)!important","background-color":"rgba(90, 242, 156, 0.2)"}), |
|
), |
|
], md=12), |
|
]), |
|
|
|
|
|
dbc.Row([ |
|
dbc.Col([ |
|
html.H3("Historique des générations", className="mt-5 mb-3", style={"font-size": "1rem"}), |
|
html.Div(id="history-container", className="border rounded p-3"), |
|
], md=12), |
|
]), |
|
]), |
|
dmc.TabsPanel( |
|
value="second", |
|
children=[ |
|
dbc.Container([ |
|
dbc.Row([ |
|
dbc.Col([ |
|
dbc.Row([html.H1("Re-génération des Blocs de Connaissances et Compétences (BCC) AVID à partir des maquettes de formations brutes", className="mb-4", style={"font-size": "1.5rem", "font-weight": "bold"}), |
|
dbc.Col(html.Img(src="./assets/jsonfile.png", height="36px", className="ml-3", style={"margin-top": "-0.5rem"}),sm=0.5), |
|
dbc.Col(html.H3("Sélectionnez une maquette de formation", className="mb-3", style={"font-size": "1rem"}),sm=10), |
|
dbc.Col(dcc.Dropdown( |
|
id="maquette-dropdown-avid", |
|
options=[ |
|
{"label": re.sub(r'[^a-zA-Z0-9]', '', fileJson['name']).replace("csv",""), "value": fileJson['pandas_url']} |
|
for fileJson in getGitFilesFromRepo('CSV') |
|
], |
|
placeholder="Choisir une maquette de formation avec propositions BCC", |
|
style={"color": "rgb(80,106,139)","font-size": "0.75rem","border":"border 1px solid rgb(67,167,255)!important","margin-bottom":"0.5rem"}, |
|
),sm=6), |
|
]), |
|
dbc.Row( |
|
[ |
|
dbc.Col(html.Img(src="./assets/jsonfile.png", height="36px", className="ml-3", style={"margin-top": "-0.5rem"}),sm=0.5), |
|
dbc.Col(html.H3("Sélectionnez un nombre de nouveaux BCC à générer", className="mb-3", style={"font-size": "1rem"}),sm=10), |
|
], |
|
align="left", |
|
className="g-0" |
|
), |
|
dbc.Row( |
|
[ |
|
dbc.Col(dcc.Dropdown( |
|
id="num-bcc-avid", |
|
options=[ |
|
{"label": "3", "value": "3"}, |
|
{"label": "4", "value": "4"}, |
|
{"label": "5", "value": "5"}, |
|
{"label": "6", "value": "6"}, |
|
{"label": "7", "value": "7"}, |
|
], |
|
value=4, |
|
placeholder="Choisir un nombre de BCC à générer", |
|
style={"color": "rgb(80,106,139)","font-size": "0.75rem","border":"border 1px solid rgb(67,167,255)!important","margin-bottom":"0.5rem"}, |
|
),sm=6), |
|
]), |
|
dbc.Row(dbc.Col(dbc.Button('Créer les nouveaux BCC et les nouvelles situations AVID', id='submit-button-avid', n_clicks=0, style={"background":"linear-gradient(to right, #00F3FF 0%, #7f00b2 100%)","color":"white","font-size": "0.75rem","margin-bottom":"2rem"}),sm=12)) |
|
], width=12) |
|
]), |
|
dbc.Row([ |
|
dbc.Col([ |
|
dbc.Row( |
|
[ |
|
dbc.Col(html.Img(src="./assets/requete.png", height="36px", className="ml-3", style={"margin-top": "-0.3rem"}),sm=0.5), |
|
dbc.Col(html.H3("Re-génération des nouvelles propositions de BCC AVID", className="mb-3", style={"font-size": "1rem"}),sm=6), |
|
], |
|
align="left", |
|
className="g-0" |
|
), |
|
dcc.Loading(html.Div(id='output-response-avid', style={"color":"rgb(156, 242, 242)","border-radius":"3px","border":"1px solid rgb(255,255,255)!important","background-color":"rgba(156, 242, 242, 0.2)","padding":"5px"}),), |
|
|
|
], width=12) |
|
]) |
|
], className="mt-5")], |
|
), |
|
]), |
|
|
|
|
|
html.Footer([ |
|
html.Hr(), |
|
html.P( |
|
"Cette application utilise les données des recherches en pédagogie des universités de Sherbrooke et de Montréal.", |
|
className="text-muted" |
|
), |
|
], className="mt-5"), |
|
|
|
], style=CONTENT_STYLE)],forceColorScheme="dark") |
|
|
|
|
|
@callback( |
|
Output("notification-model", "hide"), |
|
Input("apply-params-button", "n_clicks"), |
|
prevent_initial_call=True, |
|
) |
|
def alert(n_clicks): |
|
return False |
|
|
|
@callback( |
|
Output("modal-description-skills", "opened"), |
|
Input('show-modal-skills', 'n_clicks'), |
|
State("modal-description-skills", "opened"), |
|
prevent_initial_call=True, |
|
) |
|
def displayModalskills(n_click, opened): |
|
if n_click > 0: |
|
return not opened |
|
else: |
|
return opened |
|
@callback( |
|
Output("modal-description-categorisation", "opened"), |
|
Input('show-modal-categorisation', 'n_clicks'), |
|
State("modal-description-categorisation", "opened"), |
|
prevent_initial_call=True, |
|
) |
|
def displayModalcategorisation(n_click, opened): |
|
if n_click > 0: |
|
return not opened |
|
else: |
|
return opened |
|
@callback( |
|
Output("modal-description-classification", "opened"), |
|
Input('show-modal-classification', 'n_clicks'), |
|
State("modal-description-classification", "opened"), |
|
prevent_initial_call=True, |
|
) |
|
def displayModalclassification(n_click, opened): |
|
if n_click > 0: |
|
return not opened |
|
else: |
|
return opened |
|
@callback( |
|
Output("modal-description-situation", "opened"), |
|
Input('show-modal-situation', 'n_clicks'), |
|
State("modal-description-situation", "opened"), |
|
prevent_initial_call=True, |
|
) |
|
def displayModalsituation(n_click, opened): |
|
if n_click > 0: |
|
return not opened |
|
else: |
|
return opened |
|
@app.callback( |
|
Output("drawer-BCC", "opened"), |
|
Input("generate-button", "n_clicks"), |
|
Input("show-drawer", "n_clicks"), |
|
prevent_initial_call=True, |
|
) |
|
def drawer_demo(n_clicks1, n_clicks2): |
|
return True, True |
|
|
|
@app.callback( |
|
Output("modal-text-skills","children"), |
|
Input("categorie-dropdown", "value"), |
|
State("url", "pathname"), |
|
) |
|
def update_skills_dropdown(categorie_selected, pathname): |
|
"""Mettre à jour les options du dropdown d'enseignements en fonction de la catégorie sélectionnée.""" |
|
if not categorie_selected: |
|
if pathname == "/bcc": |
|
categorie_selected = 'JSON/L1-Anglais.json' |
|
elif pathname == "/bcc-avid": |
|
categorie_selected = 'JSON/L1-Lettres-Modernes.json' |
|
else: |
|
print(categorie_selected) |
|
|
|
url = f"https://api.github.com/repos/{OWNER}/{REPO}/contents/{categorie_selected}" |
|
res = requests.get(url, headers=headers, params=params) |
|
if res.status_code == 200: |
|
jsonData = json.loads(base64.b64decode(res.json()['content'])) |
|
if pathname == "/bcc": |
|
url_path = jsonData.get("current_file", "").replace("./maquettes\\","maquettes/").replace(".csv","_BCC.xlsx") |
|
url_maquette = f"https://api.github.com/repos/{OWNER}/{REPO}/contents/{url_path}" |
|
res = requests.get(url_maquette, headers=headers, params=params) |
|
content = res.json() |
|
if 'content' in content: |
|
decoded_content = base64.b64decode(content['content']) |
|
df = pd.read_excel(io.BytesIO(decoded_content)) |
|
return dbc.Table.from_dataframe(df[["diplome", "RNCP", "Année d'étude", "Semestre", "BCC", "UE", "ECUE"]], striped=True, bordered=True, hover=True, index=False) |
|
elif pathname == "/bcc-avid": |
|
url_path = jsonData.get("current_file", "").replace("maquettes\\","VD/").replace(".csv","_AVID.xlsx") |
|
url_maquette = f"https://api.github.com/repos/{OWNER}/{REPO}/contents/{url_path}" |
|
res = requests.get(url_maquette, headers=headers, params=params) |
|
content = res.json() |
|
if 'content' in content: |
|
decoded_content = base64.b64decode(content['content']) |
|
df = pd.read_excel(io.BytesIO(decoded_content)) |
|
return dbc.Table.from_dataframe(df[["BCC", "UE", "ECUE", "SITUATION_APPRENTISSAGE"]], striped=True, bordered=True, hover=True, index=False) |
|
|
|
@app.callback( |
|
Output("enseignement-dropdown", "placeholder"), |
|
Output("enseignement-dropdown", "value"), |
|
Output("text-enseignement-dropdown","children"), |
|
Output("modal-text-categorisation","children"), |
|
Input("categorie-dropdown", "value"), |
|
State("url", "pathname"), |
|
) |
|
def update_enseignements_dropdown(categorie_selected, pathname): |
|
"""Mettre à jour les options du dropdown d'enseignements en fonction de la catégorie sélectionnée.""" |
|
if not categorie_selected: |
|
default_text = "par défaut : " |
|
if pathname == "/bcc": |
|
categorie_selected = 'JSON/L1-Anglais.json' |
|
elif pathname == "/bcc-avid": |
|
categorie_selected = 'VD/JSON/L1-Lettres-Modernes.json' |
|
else: |
|
default_text = "formation sélectionnée : " |
|
|
|
url = f"https://api.github.com/repos/{OWNER}/{REPO}/contents/{categorie_selected}" |
|
res = requests.get(url, headers=headers, params=params) |
|
if res.status_code == 200: |
|
jsonData = json.loads(base64.b64decode(res.json()['content'])) |
|
modal_text = "**Description des catégories d'enseignements : **\n\n" |
|
for item in jsonData.get("categories", []): |
|
modal_text += f"- **{item['nom']}**:\n\n{item['description']}\n\n" |
|
if pathname == "/bcc": |
|
return "Choisir d'abord une maquette de formation avec proposition BCC", json.dumps(jsonData.get("categories", []), indent = 6, separators =(",", ":"), |
|
sort_keys = True, ensure_ascii=False), "Choisir d'abord une maquette de formation avec propositions BCC : " + default_text + jsonData.get("niveau", ""), modal_text |
|
elif pathname == "/bcc-avid": |
|
return "Choisir d'abord une maquette de formation avec proposition BCC", json.dumps(jsonData.get("categories", []), indent = 6, separators =(",", ":"), |
|
sort_keys = True, ensure_ascii=False), "Choisir d'abord une maquette de formation avec propositions BCC : " + default_text + jsonData.get("niveau_etude", ""), modal_text |
|
|
|
@app.callback( |
|
Output("classification-dropdown", "placeholder"), |
|
Output("classification-dropdown", "value"), |
|
Output("modal-text-classification", "children"), |
|
Input("categorie-dropdown", "value"), |
|
State("url", "pathname"), |
|
) |
|
def update_classification_dropdown(categorie_selected, pathname): |
|
"""Mettre à jour les options du dropdown d'enseignements en fonction de la catégorie sélectionnée.""" |
|
if not categorie_selected: |
|
default_text = "par défaut : " |
|
if pathname == "/bcc": |
|
categorie_selected = 'JSON/L1-Anglais.json' |
|
elif pathname == "/bcc-avid": |
|
categorie_selected = 'VD/JSON/L1-Lettres-Modernes.json' |
|
else: |
|
default_text = "" |
|
|
|
url = f"https://api.github.com/repos/{OWNER}/{REPO}/contents/{categorie_selected}" |
|
res = requests.get(url, headers=headers, params=params) |
|
if res.status_code == 200: |
|
jsonData = json.loads(base64.b64decode(res.json()['content'])) |
|
modal_text = "**Classification des enseignements :**" |
|
if pathname == "/bcc": |
|
textarea_value = jsonData.get("classified_teachings", []) |
|
for key, value in textarea_value.items(): |
|
modal_text += f"\n\n- **{key}**: " |
|
for i in range(0,len(value)): |
|
modal_text += f"{value[i]}\t" |
|
elif pathname == "/bcc-avid": |
|
textarea_value = jsonData.get("dataframe", []) |
|
test = " " |
|
for item in sorted(textarea_value, key=lambda x: x['categorie'] if x['categorie'] else ""): |
|
if test != item['categorie']: |
|
modal_text += f"\n\n- **{item['categorie']}**: " |
|
modal_text += f"{item['enseignements']}\t" |
|
test = item['categorie'] |
|
|
|
if pathname == "/bcc": |
|
return "Choisir d'abord une maquette de formation avec proposition BCC", json.dumps(textarea_value, indent = 6, separators =(",", ":"), |
|
sort_keys = True, ensure_ascii=False),modal_text |
|
elif pathname == "/bcc-avid": |
|
return "Choisir d'abord une maquette de formation avec proposition BCC", json.dumps(textarea_value, indent = 6, separators =(",", ":"), |
|
sort_keys = True, ensure_ascii=False),modal_text |
|
|
|
@app.callback( |
|
Output("situation-dropdown", "placeholder"), |
|
Output("situation-dropdown", "value"), |
|
Output("modal-text-situation", "children"), |
|
Input("categorie-dropdown", "value"), |
|
State("url", "pathname"), |
|
) |
|
def update_situations_dropdown(categorie_selected, pathname): |
|
"""Mettre à jour les options du dropdown d'enseignements en fonction de la catégorie sélectionnée.""" |
|
if not categorie_selected: |
|
default_text = "par défaut : " |
|
if pathname == "/bcc": |
|
categorie_selected = 'JSON/L1-Anglais.json' |
|
elif pathname == "/bcc-avid": |
|
categorie_selected = 'VD/JSON/L1-Lettres-Modernes.json' |
|
else: |
|
default_text = "" |
|
|
|
url = f"https://api.github.com/repos/{OWNER}/{REPO}/contents/{categorie_selected}" |
|
res = requests.get(url, headers=headers, params=params) |
|
try: |
|
if res.status_code == 200: |
|
jsonData = json.loads(base64.b64decode(res.json()['content'])) |
|
modal_text = "**Description des situations d'apprentissage :**" |
|
if pathname == "/bcc": |
|
textarea_value = jsonData.get("learning_situations", []) |
|
for key, value in textarea_value.items(): |
|
modal_text += f"\n\n- **{key}**: {value}" |
|
elif pathname == "/bcc-avid": |
|
textarea_value = jsonData.get("situations_apprentissage", []) |
|
for item in textarea_value: |
|
modal_text += f"\n\n- **Situation d'apprentissage**: {item['situation']}" |
|
if item['objectifs']: |
|
modal_text += f"\n\nObjectifs : " |
|
for objectif in item['objectifs']: |
|
modal_text += f"\n-{objectif}" |
|
modal_text += f"\n\nLien avec les thématiques ODD11 : {item['lien_odd11']}" |
|
|
|
if pathname == "/bcc": |
|
return "Choisir d'abord une maquette de formation avec proposition BCC", json.dumps(textarea_value, indent = 6, separators =(",", ":"), |
|
sort_keys = True, ensure_ascii=False), modal_text |
|
elif pathname == "/bcc-avid": |
|
return "Choisir d'abord une maquette de formation avec proposition BCC", json.dumps(textarea_value, indent = 6, separators =(",", ":"), |
|
sort_keys = True, ensure_ascii=False), modal_text |
|
except: |
|
return "Choisir d'abord une maquette de formation avec proposition BCC", "", "**Aucune situation d'apprentissage définie pour cette maquette de formation.**" |
|
|
|
@app.callback( |
|
Output("selection-display", "children"), |
|
Output("generate-button", "disabled"), |
|
Output("show-modal-skills", "disabled"), |
|
Input("categorie-dropdown", "value"), |
|
Input("enseignement-dropdown", "value"), |
|
Input("situation-dropdown", "value") |
|
) |
|
def update_selection_display(categorie, enseignement, situation_id): |
|
"""Mettre à jour l'affichage des sélections et activer/désactiver le bouton de génération.""" |
|
if not categorie or not enseignement or not situation_id: |
|
return "Veuillez sélectionner un fichier maquette pour afficher les informations intermédiaires afin de générer une compétence.", True, True |
|
|
|
selection_display = html.Div([ |
|
html.H4("Votre sélection:"), |
|
html.P([html.Strong("Maquette de formation avec propositions BCC: "), categorie]), |
|
html.P([html.Strong("Catégorisation des enseignements: "), enseignement]), |
|
html.P([html.Strong("Situations d'apprentissage: "), dcc.Markdown(f"{json.dumps(situation_id, indent = 6, ensure_ascii=False)}")]), |
|
]) |
|
|
|
return selection_display, False, False |
|
|
|
@app.callback( |
|
Output("model-params-store", "data"), |
|
Output("notification-model", "children"), |
|
Input("apply-params-button", "n_clicks"), |
|
State("model-dropdown", "value"), |
|
State("temperature-slider", "value"), |
|
State("max-tokens-input", "value"), |
|
State("top-p-slider", "value"), |
|
prevent_initial_call=True |
|
) |
|
def update_model_params(n_clicks, model, temperature, max_tokens, top_p): |
|
"""Mettre à jour les paramètres du modèle LLM.""" |
|
if not n_clicks: |
|
raise PreventUpdate |
|
|
|
return { |
|
"model": model, |
|
"temperature": temperature, |
|
"max_tokens": max_tokens, |
|
"top_p": top_p |
|
}, f"Les paramètres du modèle : {model}, ont été mis à jour avec succès." |
|
|
|
@app.callback( |
|
Output("BCC-output", "children"), |
|
Output("BCC-status", "children"), |
|
Output("competence-output", "children"), |
|
Output("generation-status", "children"), |
|
Output("history-store", "data"), |
|
Input("requete-dropdown", "value"), |
|
Input("categorie-dropdown", "value"), |
|
Input("generate-button", "n_clicks"), |
|
State("categorie-dropdown", "value"), |
|
State("enseignement-dropdown", "value"), |
|
State("situation-dropdown", "value"), |
|
State("model-params-store", "data"), |
|
State("history-store", "data"), |
|
State("url", "pathname"), |
|
prevent_initial_call=True |
|
) |
|
def generate_competence(requete, categorie_selected, n_clicks, categorie, enseignement, situation_id, model_params, history, pathname): |
|
"""Générer une compétence académique basée sur les sélections et les paramètres du modèle.""" |
|
if not n_clicks: |
|
raise PreventUpdate |
|
|
|
if not categorie or not enseignement or not situation_id or not requete: |
|
return "Veuillez sélectionner tous les éléments requis.", "", history |
|
|
|
|
|
url = f"https://api.github.com/repos/{OWNER}/{REPO}/contents/{categorie_selected}" |
|
res = requests.get(url, headers=headers, params=params) |
|
try: |
|
if res.status_code == 200: |
|
jsonData = json.loads(base64.b64decode(res.json()['content'])) |
|
|
|
|
|
|
|
if pathname == "/bcc": |
|
niveau_etude = jsonData.get("niveau", "") |
|
prompt = """Tu es un expert en sciences de l'éducation, spécialisé dans la formulation de compétences académiques. |
|
|
|
Définition d'une compétence académique est: |
|
1. Un savoir-agir complexe prenant appui sur la mobilisation et la combinaison efficaces de ressources internes et externes |
|
2. Une capacité à utiliser efficacement un ensemble de connaissances, d'aptitudes et d'attitudes dans un contexte déterminé |
|
3. Formulée avec un verbe d'action à l'infinitif suivi d'un complément d'objet direct et d'un contexte |
|
4. Évaluable selon des critères de performance définis |
|
|
|
Exemples de formulation: |
|
- "Analyser des problèmes complexes en mobilisant des approches multidisciplinaires pour proposer des solutions innovantes" |
|
- "Concevoir et mettre en œuvre des projets de recherche en respectant les normes éthiques et méthodologiques du domaine" |
|
- "Interpréter des données scientifiques pour prendre des décisions éclairées dans un contexte d'incertitude" |
|
|
|
Voici les 4 catégories thématiques d'enseignements: |
|
{categories} |
|
|
|
Voici la classification des enseignements dans les 4 catégories thématiques: |
|
{enseignements} |
|
|
|
{prompt} |
|
|
|
Réponds pour un niveau d'étude que tu détermines grâce au titre diplôme suivant : {niveau} |
|
""" |
|
elif pathname == "/bcc-avid": |
|
niveau_etude = jsonData.get("niveau_etude", "") |
|
prompt = """Tu es un expert en ingénierie pédagogique universitaire et en développement durable, spécialisé dans l'ODD11 (villes et communautés durables). |
|
|
|
Je souhaite formuler des compétences académiques liées à la ville durable pour une formation d'un niveau d'étude que tu détermines grâce au titre diplôme suivant : {niveau}. |
|
|
|
Voici les 4 catégories thématiques d'enseignements: |
|
{categories} |
|
|
|
Voici la classification des enseignements dans les 4 catégories thématiques: |
|
{enseignements} |
|
|
|
Voici les situations d'apprentissage déjà créées: |
|
{situations} |
|
|
|
Objectif de développement durable 11 (ODD11): |
|
L'ODD11 vise à "faire en sorte que les villes et les établissements humains soient ouverts à tous, sûrs, résilients et durables". Cela inclut l'accès au logement décent, aux transports durables, l'urbanisation inclusive, la préservation du patrimoine, la réduction des risques de catastrophes, la qualité de l'air, la gestion des déchets et l'accès aux espaces verts. |
|
|
|
Définition d'une compétence académique est: |
|
1. Un savoir-agir complexe prenant appui sur la mobilisation et la combinaison efficaces de ressources internes et externes |
|
2. Une capacité à utiliser efficacement un ensemble de connaissances, d'aptitudes et d'attitudes dans un contexte déterminé |
|
3. Formulée avec un verbe d'action à l'infinitif suivi d'un complément d'objet direct et d'un contexte |
|
4. Évaluable selon des critères de performance définis |
|
""" |
|
|
|
try: |
|
if model_params["model"] == "mistralai/Mistral-Small-3.1-24B-Instruct-2503": |
|
baseURL = os.environ['BASEURL_ALBERT_API_KEY'] |
|
os.environ['ENDPOINT_API_KEY'] = os.environ['ENDPOINT_ALBERT_API_KEY'] |
|
else: |
|
baseURL = os.environ['BASEURL_RENNES_API_KEY'] |
|
os.environ['ENDPOINT_API_KEY'] = os.environ['ENDPOINT_RENNES_API_KEY'] |
|
model = ChatOpenAI(model_name=model_params["model"], base_url=baseURL, temperature=model_params["temperature"],api_key=os.environ['ENDPOINT_API_KEY'], top_p=model_params["top_p"], max_tokens=model_params["max_tokens"]) |
|
|
|
|
|
competences_prompt = PromptTemplate.from_template(prompt) |
|
|
|
|
|
|
|
|
|
chain = competences_prompt | model |
|
|
|
if categorie is None: |
|
categorie = " " |
|
if enseignement is None: |
|
enseignement = " " |
|
if situation_id is None: |
|
situation_id = " " |
|
answer = chain.invoke({ |
|
"niveau": niveau_etude, |
|
"categories": categorie, |
|
"enseignements":enseignement, |
|
"situations": situation_id, |
|
"prompt": requete |
|
}) |
|
if answer.content.strip().find("</think>") != -1: |
|
position = answer.content.strip().index('</think>') |
|
result = answer.content.strip()[position+8:] |
|
else: |
|
result = answer.content.strip() |
|
|
|
|
|
formatted_result = dcc.Markdown(result, className="competence-markdown", style={"color": "white"}) |
|
|
|
|
|
new_history_entry = { |
|
"id": len(history) + 1, |
|
"timestamp": pd.Timestamp.now().strftime("%Y-%m-%d %H:%M:%S"), |
|
"categorie": categorie, |
|
"enseignement": enseignement, |
|
"situation": situation_id, |
|
"prompt": requete, |
|
"niveau": niveau_etude, |
|
"model": model_params["model"], |
|
"temperature": model_params["temperature"], |
|
"competence": result |
|
} |
|
|
|
updated_history = history.copy() |
|
updated_history.append(new_history_entry) |
|
|
|
success_message = html.Div([ |
|
html.I(className="fas fa-check-circle me-2"), |
|
f"Compétences générées avec succès en utilisant {model_params['model']} (T={model_params['temperature']})\n Pour un niveau d'étude correspondant à : {niveau_etude}." |
|
], className="text-success") |
|
|
|
return formatted_result, success_message, formatted_result, success_message, updated_history |
|
|
|
except Exception as e: |
|
error_message = html.Div([ |
|
html.I(className="fas fa-exclamation-triangle me-2"), |
|
f"Erreur lors de la génération: {str(e)}" |
|
], className="text-danger") |
|
return "Une erreur s'est produite lors de la génération des compétences.", error_message, history |
|
except: |
|
error_message = html.Div([ |
|
html.I(className="fas fa-exclamation-triangle me-2"), |
|
"Erreur lors de la récupération des données de la maquette." |
|
], className="text-danger") |
|
return "Une erreur s'est produite lors de la récupération des données de la maquette.", error_message, history |
|
@app.callback( |
|
Output("history-container", "children"), |
|
Input("history-store", "data") |
|
) |
|
def update_history_display(history): |
|
"""Mettre à jour l'affichage de l'historique des générations.""" |
|
if not history: |
|
return html.P("Aucune génération dans l'historique.", className="text-muted") |
|
|
|
history_cards = [] |
|
|
|
for entry in reversed(history): |
|
history_cards.append( |
|
dbc.Card( |
|
dbc.CardBody([ |
|
html.H5(f"Génération #{entry['id']} - {entry['timestamp']}", className="card-title"), |
|
html.P([ |
|
html.Span(f"{entry['categorie']} - {entry['enseignement']} - {entry['situation']}", |
|
className="text-muted"), |
|
html.Br(), |
|
html.Small(f"Modèle: {entry['model']}, Température: {entry['temperature']}") |
|
]), |
|
html.Hr(), |
|
dcc.Markdown(entry['competence'], className="competence-summary") |
|
]), |
|
className="mb-3" |
|
) |
|
) |
|
|
|
return history_cards |
|
|
|
|
|
@app.callback(Output('user-status-div', 'children'), Output('login-status', 'data'), [Input('url', 'pathname')]) |
|
def login_status(url): |
|
''' callback to display login/logout link in the header ''' |
|
if hasattr(current_user, 'is_authenticated') and current_user.is_authenticated \ |
|
and url != '/logout': |
|
return dcc.Link('logout', href='/logout', style={"float":"right","margin":"0.1rem 0.2rem","padding":"0.25rem 0.175rem","background":"linear-gradient(to right, rgb(90, 176, 242) 0%, rgb(90, 176, 242) 100%)","color":"white","font-size": "0.75rem","border-radius":"5px"}), current_user.get_id() |
|
else: |
|
return dcc.Link('', href='/'), 'loggedout' |
|
|
|
|
|
@app.callback(Output('page-content', 'children'), Output('redirect', 'pathname'), |
|
[Input('url', 'pathname')]) |
|
def display_page(pathname): |
|
''' callback to determine layout to return ''' |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
view = None |
|
url = dash.no_update |
|
if pathname == '/success': |
|
if current_user.is_authenticated: |
|
view = app_page |
|
url = '/bcc' |
|
else: |
|
view = failed |
|
elif pathname == '/logout': |
|
if current_user.is_authenticated: |
|
logout_user() |
|
view = logout |
|
url = '/' |
|
else: |
|
view = index_page |
|
url = '/' |
|
elif pathname == '/bcc': |
|
if current_user.is_authenticated: |
|
view = app_page |
|
url = '/bcc' |
|
else: |
|
view = index_page |
|
url = '/' |
|
elif pathname == '/bcc-avid': |
|
if current_user.is_authenticated: |
|
view = app_avid_page |
|
url = '/bcc-avid' |
|
else: |
|
view = index_page |
|
url = '/' |
|
else: |
|
if current_user.is_authenticated: |
|
view = app_page |
|
url = '/bcc' |
|
else: |
|
view = index_page |
|
|
|
return view, url |
|
|
|
@callback( |
|
Output("output-response", "children"), |
|
Input("num-bcc", "value"), |
|
Input("maquette-dropdown", "value"), |
|
Input("submit-button", "n_clicks"), |
|
State("url", "pathname"), |
|
prevent_initial_call=True, |
|
) |
|
def display_status(num, current, n_clicks, pathname): |
|
if not n_clicks: |
|
return no_update |
|
|
|
if not current: |
|
print(f"Erreur: Il n'y a pas de fichier dans le répertoire.") |
|
return no_update |
|
if not num: |
|
print(f"Erreur: Il n'y a pas de nombre de BCC à générer.") |
|
return no_update |
|
|
|
current_url = current |
|
|
|
print(f"Fichier Maquette sélectionné: {current_url}") |
|
agent = init_agent_state(current_url, num, pathname) |
|
try: |
|
df = agent[0] |
|
result = agent[1] |
|
return html.Div(children=[dbc.Table.from_dataframe(df[["diplome", "RNCP", "Année d'étude", "Semestre", "BCC", "UE", "ECUE","exemple_situation_apprentissage"]], striped=True, bordered=True, hover=True, index=False), dcc.Markdown(f"""{result}""", style={"color":"white","font-size":"0.75rem"})]) |
|
except: |
|
return html.Div(dcc.Markdown(f"""{agent}""", style={"color":"white","font-size":"0.75rem"})) |
|
|
|
@callback( |
|
Output("output-response-avid", "children"), |
|
Input("num-bcc-avid", "value"), |
|
Input("maquette-dropdown-avid", "value"), |
|
Input("submit-button-avid", "n_clicks"), |
|
State("url", "pathname"), |
|
prevent_initial_call=True, |
|
) |
|
def display_status(num, current, n_clicks, pathname): |
|
if not n_clicks: |
|
return no_update |
|
|
|
if not current: |
|
print(f"Erreur: Il n'y a pas de fichier dans le répertoire.") |
|
return no_update |
|
if not num: |
|
print(f"Erreur: Il n'y a pas de nombre de BCC à générer.") |
|
return no_update |
|
|
|
current_url = current |
|
|
|
print(f"Fichier Maquette sélectionné: {current_url}") |
|
|
|
agent = init_agent_state(current_url, num, pathname) |
|
try: |
|
df = agent[0] |
|
result = agent[1] |
|
return html.Div(children=[dbc.Table.from_dataframe(df[["diplome", "RNCP", "Année d'étude", "Semestre", "BCC", "UE", "ECUE","exemple_situation_apprentissage"]], striped=True, bordered=True, hover=True, index=False), dcc.Markdown(f"""{result}""", style={"color":"white","font-size":"0.75rem"})]) |
|
except: |
|
return html.Div(dcc.Markdown(f"""{agent}""", style={"color":"white","font-size":"0.75rem"})) |
|
|
|
if __name__ == '__main__': |
|
app.run_server(debug=True) |