Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| from datetime import datetime, date | |
| import copy | |
| import json | |
| import requests | |
| import os | |
| # --- Hugging Face Hub integration --- | |
| try: | |
| from huggingface_hub import HfApi, hf_hub_download | |
| HF_HUB_AVAILABLE = True | |
| except ImportError: | |
| HF_HUB_AVAILABLE = False | |
| HF_REPO_ID = "AIB-Research/bibliPrompt" | |
| HF_JSON_FILENAME = "prompt_templates_data_v3.json" | |
| HF_TOKEN = os.environ.get("HF_TOKEN", None) | |
| # --- OpenAI API integration --- | |
| OPENAI_API_KEY = "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" | |
| # --- Save to Hugging Face Space --- | |
| def save_to_hf_space(json_path, repo_id=HF_REPO_ID, token=HF_TOKEN): | |
| if not HF_HUB_AVAILABLE: | |
| st.warning("huggingface_hub n'est pas installé. Sauvegarde sur HF désactivée.") | |
| return False | |
| try: | |
| api = HfApi() | |
| api.upload_file( | |
| path_or_fileobj=json_path, | |
| path_in_repo=HF_JSON_FILENAME, | |
| repo_id=repo_id, | |
| repo_type="space", | |
| token=token | |
| ) | |
| st.toast("💾 Données sauvegardées sur Hugging Face Space!", icon="🤗") | |
| return True | |
| except Exception as e: | |
| st.warning(f"Erreur lors de la sauvegarde sur Hugging Face: {e}") | |
| return False | |
| # --- Save to Hugging Face Space from memory (no file write) --- | |
| def save_to_hf_space_from_memory(json_string, repo_id=HF_REPO_ID, token=HF_TOKEN): | |
| if not HF_HUB_AVAILABLE: | |
| st.warning("huggingface_hub n'est pas installé. Sauvegarde sur HF désactivée.") | |
| return False | |
| try: | |
| import io | |
| api = HfApi() | |
| api.upload_file( | |
| path_or_fileobj=io.BytesIO(json_string.encode('utf-8')), | |
| path_in_repo=HF_JSON_FILENAME, | |
| repo_id=repo_id, | |
| repo_type="space", | |
| token=token | |
| ) | |
| st.toast("💾 Données sauvegardées sur Hugging Face Space!", icon="🤗") | |
| return True | |
| except Exception as e: | |
| st.warning(f"Erreur lors de la sauvegarde sur Hugging Face: {e}") | |
| return False | |
| # --- Load from Hugging Face Space --- | |
| def load_from_hf_space(repo_id=HF_REPO_ID, token=HF_TOKEN): | |
| if not HF_HUB_AVAILABLE: | |
| st.warning("huggingface_hub n'est pas installé. Chargement depuis HF désactivé.") | |
| return None | |
| try: | |
| local_path = hf_hub_download( | |
| repo_id=repo_id, | |
| filename=HF_JSON_FILENAME, | |
| repo_type="space", | |
| token=token | |
| ) | |
| with open(local_path, "r", encoding="utf-8") as f: | |
| return f.read() | |
| except Exception as e: | |
| st.warning(f"Erreur lors du chargement depuis Hugging Face: {e}") | |
| return None | |
| # --- OpenAI API function --- | |
| def call_openai_api(prompt_text, max_tokens=4000): | |
| """ | |
| Call OpenAI API to generate JSON response from the prompt template | |
| """ | |
| try: | |
| headers = { | |
| "Authorization": f"Bearer {OPENAI_API_KEY}", | |
| "Content-Type": "application/json" | |
| } | |
| data = { | |
| "model": "gpt-4", | |
| "messages": [ | |
| { | |
| "role": "system", | |
| "content": "Vous êtes un expert en conception de prompts (Prompt Engineer) reconnu, spécialisé dans la création de prompts système de haute qualité pour des modèles de langage avancés. Votre mission est de créer des prompts détaillés, structurés et hautement efficaces selon les instructions précises qui vous seront données. Soyez créatif et approfondi dans vos réponses tout en respectant rigoureusement le format JSON demandé." | |
| }, | |
| { | |
| "role": "user", | |
| "content": prompt_text | |
| } | |
| ], | |
| "max_tokens": max_tokens, | |
| "temperature": 0.7 | |
| } | |
| response = requests.post( | |
| "https://api.openai.com/v1/chat/completions", | |
| headers=headers, | |
| json=data, | |
| timeout=60 | |
| ) | |
| if response.status_code == 200: | |
| result = response.json() | |
| if 'choices' in result and len(result['choices']) > 0: | |
| return result['choices'][0]['message']['content'].strip() | |
| else: | |
| return None | |
| else: | |
| st.error(f"Erreur API OpenAI: {response.status_code} - {response.text}") | |
| return None | |
| except requests.exceptions.Timeout: | |
| st.error("⏱️ Timeout lors de l'appel à l'API OpenAI. Veuillez réessayer.") | |
| return None | |
| except Exception as e: | |
| st.error(f"Erreur lors de l'appel à l'API OpenAI: {e}") | |
| return None | |
| def extract_json_from_response(api_response): | |
| """ | |
| Extract JSON content from OpenAI API response | |
| """ | |
| try: | |
| # Look for JSON content between ```json and ``` | |
| if "```json" in api_response: | |
| start = api_response.find("```json") + 7 | |
| end = api_response.find("```", start) | |
| if end > start: | |
| json_str = api_response[start:end].strip() | |
| else: | |
| json_str = api_response[start:].strip() | |
| else: | |
| # Try to find JSON-like content | |
| start = api_response.find("{") | |
| end = api_response.rfind("}") + 1 | |
| if start >= 0 and end > start: | |
| json_str = api_response[start:end] | |
| else: | |
| return None | |
| # Parse and validate JSON | |
| json_data = json.loads(json_str) | |
| return json_data | |
| except json.JSONDecodeError as e: | |
| st.error(f"Erreur lors du parsing du JSON: {e}") | |
| return None | |
| except Exception as e: | |
| st.error(f"Erreur lors de l'extraction du JSON: {e}") | |
| return None | |
| def auto_inject_json_and_redirect(json_data, target_family): | |
| """ | |
| Injecte automatiquement le JSON généré dans la famille spécifiée et redirige vers le nouvel usage | |
| """ | |
| try: | |
| if not isinstance(json_data, dict): | |
| st.error("Le JSON généré n'est pas un dictionnaire valide.") | |
| return False | |
| if target_family not in st.session_state.editable_prompts: | |
| st.error(f"La famille '{target_family}' n'existe plus.") | |
| return False | |
| successful_injections = [] | |
| first_new_uc_name = None | |
| for uc_name, uc_config in json_data.items(): | |
| uc_name_stripped = uc_name.strip() | |
| if not uc_name_stripped: | |
| continue | |
| if uc_name_stripped in st.session_state.editable_prompts[target_family]: | |
| st.warning(f"Le cas d'usage '{uc_name_stripped}' existe déjà dans '{target_family}'. Ignoré.") | |
| continue | |
| # Valider la structure du cas d'usage | |
| if not isinstance(uc_config, dict): | |
| st.warning(f"Configuration invalide pour '{uc_name_stripped}'. Ignoré.") | |
| continue | |
| required_fields = ["template", "variables", "tags", "description"] | |
| if not all(field in uc_config for field in required_fields): | |
| st.warning(f"Champs manquants dans '{uc_name_stripped}'. Ignoré.") | |
| continue | |
| # Injecter le cas d'usage | |
| st.session_state.editable_prompts[target_family][uc_name_stripped] = uc_config | |
| successful_injections.append(uc_name_stripped) | |
| if first_new_uc_name is None: | |
| first_new_uc_name = uc_name_stripped | |
| if successful_injections: | |
| save_editable_prompts_to_local_and_hf() | |
| success_msg = f"✅ {len(successful_injections)} cas d'usage ajouté(s) avec succès dans '{target_family}'" | |
| st.success(success_msg) | |
| st.toast(success_msg, icon="🎉") | |
| # Rediriger vers le nouvel usage | |
| if first_new_uc_name: | |
| st.session_state.view_mode = "generator" | |
| st.session_state.force_select_family_name = target_family | |
| st.session_state.force_select_use_case_name = first_new_uc_name | |
| st.session_state.go_to_config_section = True | |
| # Nettoyer les variables de l'assistant | |
| st.session_state.assistant_api_processing = False | |
| st.session_state.assistant_generated_json = None | |
| st.session_state.generated_meta_prompt_for_llm = "" | |
| return True | |
| else: | |
| st.error("Aucun cas d'usage n'a pu être injecté.") | |
| return False | |
| except Exception as e: | |
| st.error(f"Erreur lors de l'injection automatique: {e}") | |
| return False | |
| # --- PAGE CONFIGURATION (MUST BE THE FIRST STREAMLIT COMMAND) --- | |
| # Fixed deployment issue | |
| st.set_page_config(layout="wide", page_title="🛠️ Le laboratoire des Prompts IA", initial_sidebar_state="collapsed" ) | |
| # --- CUSTOM CSS FOR SIDEBAR TOGGLE TEXT --- | |
| st.markdown(""" | |
| <style> | |
| /* Cible le bouton spécifique que vous avez identifié */ | |
| button[data-testid="stBaseButton-headerNoPadding"]::after { | |
| content: " Menu"; | |
| margin-left: 8px; | |
| font-size: 0.9em; | |
| vertical-align: middle; | |
| color: inherit; | |
| font-weight: normal; | |
| display: inline-flex; | |
| align-items: center; | |
| } | |
| div[data-testid="stCodeBlock"] pre, | |
| pre.st-emotion-cache-1nqbjoj { | |
| max-height: 520px !important; | |
| overflow-y: auto !important; | |
| font-size: 0.875em !important; | |
| display: block !important; | |
| visibility: visible !important; | |
| opacity: 1 !important; | |
| } | |
| div[data-testid="stCodeBlock"] > div:first-child { | |
| max-height: 520px !important; | |
| overflow-y: auto !important; | |
| display: block !important; | |
| visibility: visible !important; | |
| opacity: 1 !important; | |
| } | |
| pre.st-emotion-cache-1nqbjoj > div[style*="background-color: transparent;"] { | |
| height: auto !important; | |
| max-height: 100% !important; | |
| overflow-y: auto !important; | |
| } | |
| button[data-testid="stCodeCopyButton"] { | |
| opacity: 0.85 !important; | |
| visibility: visible !important; | |
| background-color: #f0f2f6 !important; | |
| border: 1px solid #cccccc !important; | |
| border-radius: 4px !important; | |
| padding: 3px 5px !important; | |
| transition: opacity 0.15s ease-in-out, background-color 0.15s ease-in-out; | |
| } | |
| button[data-testid="stCodeCopyButton"]:hover { | |
| opacity: 1 !important; | |
| background-color: #e6e8eb !important; | |
| border-color: #b0b0b0 !important; | |
| } | |
| button[data-testid="stCodeCopyButton"] svg { | |
| transform: scale(1.2); | |
| vertical-align: middle; | |
| } | |
| section[data-testid="stSidebar"] { | |
| width: 31.5rem !important; | |
| min-width: 31.5rem !important; | |
| max-width: 31.5rem !important; | |
| } | |
| section[data-testid="stSidebar"][aria-expanded="false"] { | |
| width: 0rem !important; | |
| min-width: 0rem !important; | |
| max-width: 0rem !important; | |
| overflow: hidden !important; | |
| } | |
| [data-testid="stMainBlockContainer"] { | |
| padding-top: 3rem !important; | |
| } | |
| .css-1d391kg, .css-18e3th9 { | |
| padding-top: 3rem !important; | |
| } | |
| h1[data-testid="stHeading"]:first-of-type { | |
| margin-top: -2rem !important; | |
| padding-top: 0rem !important; | |
| } | |
| h1:contains("Bienvenue dans votre laboratoire") { | |
| margin-top: -2rem !important; | |
| padding-top: 0rem !important; | |
| } | |
| @media (max-width: 768px) { | |
| .main .block-container { | |
| max-width: 100vw !important; | |
| width: 100vw !important; | |
| } | |
| } | |
| div[data-testid="stExpander"] div[data-testid="stCodeBlock"] { | |
| margin-top: 0.1rem !important; | |
| margin-bottom: 0.15rem !important; | |
| padding-top: 0.1rem !important; | |
| padding-bottom: 0.1rem !important; | |
| } | |
| div[data-testid="stExpander"] div[data-testid="stCodeBlock"] pre { | |
| padding-top: 0.2rem !important; | |
| padding-bottom: 0.2rem !important; | |
| line-height: 1.1 !important; | |
| font-size: 0.85em !important; | |
| margin: 0 !important; | |
| } | |
| div[data-testid="stExpander"] { | |
| width: 100% !important; | |
| max-width: 100% !important; | |
| overflow: visible !important; | |
| } | |
| div[data-testid="stExpander"] > div:first-child { | |
| overflow: visible !important; | |
| } | |
| div[data-testid="stExpander"] .streamlit-expanderContent { | |
| width: 100% !important; | |
| max-width: 100% !important; | |
| overflow: visible !important; | |
| position: relative !important; | |
| transform: translateZ(0) !important; | |
| } | |
| .main .block-container { | |
| overflow-x: hidden !important; | |
| overflow-y: auto !important; | |
| } | |
| div[data-testid="stExpander"] form { | |
| max-width: 100% !important; | |
| overflow-x: hidden !important; | |
| } | |
| div[data-testid="stExpander"] div[data-testid="column"] { | |
| min-width: 0 !important; | |
| overflow: hidden !important; | |
| } | |
| </style> | |
| """, unsafe_allow_html=True) | |
| # --- Initial Data Structure & Constants --- | |
| CURRENT_YEAR = datetime.now().year | |
| # Variable de contrôle pour la section de paramétrage - changez à True pour réactiver | |
| SHOW_CONFIG_SECTION = True | |
| GIST_DATA_FILENAME = "prompt_templates_data_v3.json" | |
| LOCAL_DATA_FILENAME = "prompt_templates_data_v3.json" | |
| # --- Function to load prompt templates from files --- | |
| def load_prompt_template(filename): | |
| """Load prompt template from file, with fallback to basic template if file not found.""" | |
| try: | |
| with open(filename, 'r', encoding='utf-8') as f: | |
| return f.read() | |
| except FileNotFoundError: | |
| st.warning(f"Fichier de template '{filename}' non trouvé. Utilisation d'un template de base.") | |
| return "# MISSION\nVous êtes un assistant IA. Veuillez traiter la demande suivante: {problematique}" | |
| except Exception as e: | |
| st.error(f"Erreur lors du chargement du template '{filename}': {e}") | |
| return "# MISSION\nVous êtes un assistant IA. Veuillez traiter la demande suivante: {problematique}" | |
| # Load prompt templates from external files | |
| META_PROMPT_FOR_EXTERNAL_LLM_TEMPLATE = load_prompt_template("AIBprompt_creation_template.md") | |
| META_PROMPT_FOR_LLM_AMELIORATION_TEMPLATE = load_prompt_template("AIBprompt_improvement_template.md") | |
| ASSISTANT_FORM_VARIABLES = [ | |
| {"name": "problematique", "label": "Décrivez le besoin ou la tâche que le prompt cible doit résoudre :", "type": "text_area", "default": "", "height": 100}, | |
| {"name": "doc_source", "label": "Quel(s) types de document(s) sont nécessaire pour la réalisation de votre besoin ? (e.g. PDF, e-mail, texte brut -laisser vide si non pertinent-) :", "type": "text_input", "default": ""}, | |
| {"name": "elements_specifiques_a_extraire", "label": "Quelles sont les informations spécifiques que vous souhaitez identifier / générer ? (e.g. l'ensemble des ID clients, les clauses du contrat) :", "type": "text_area", "default": "", "height": 100}, | |
| {"name": "format_sortie_desire", "label": "Optionnel : sous quel format voulez vous que le prompt produise une réponse ? (e.g. un texte de deux pages, une liste à puces) :", "type": "text_area", "default": "", "height": 75}, | |
| {"name": "public_cible_reponse", "label": "Optionnel : pour quel public cible s'adressera le résultat du prompt ? (e.g. des profils techniques, le grand public) :", "type": "text_input", "default": ""}, | |
| ] | |
| def get_default_dates(): | |
| now_iso = datetime.now().isoformat() | |
| return now_iso, now_iso | |
| INITIAL_PROMPT_TEMPLATES = { | |
| "Propositions commerciales": {}, "Ateliers métiers": {}, "Project Management": {} | |
| } | |
| for family, use_cases in INITIAL_PROMPT_TEMPLATES.items(): # Initial cleanup | |
| if isinstance(use_cases, dict): | |
| for uc_name, uc_config in use_cases.items(): | |
| if "is_favorite" in uc_config: # pragma: no cover | |
| del uc_config["is_favorite"] | |
| # --- Utility Functions (User's original versions, with height fix in _postprocess_after_loading) --- | |
| def parse_default_value(value_str, var_type): | |
| if not value_str: | |
| if var_type == "number_input": return 0.0 | |
| if var_type == "date_input": return datetime.now().date() | |
| return "" | |
| if var_type == "number_input": | |
| try: return float(value_str) | |
| except ValueError: return 0.0 | |
| elif var_type == "date_input": | |
| try: return datetime.strptime(value_str, "%Y-%m-%d").date() | |
| except (ValueError, TypeError): | |
| return value_str if isinstance(value_str, date) else datetime.now().date() | |
| return value_str | |
| def _preprocess_for_saving(data_to_save): | |
| processed_data = copy.deepcopy(data_to_save) | |
| for family_name in list(processed_data.keys()): | |
| use_cases_in_family = processed_data[family_name] | |
| if not isinstance(use_cases_in_family, dict): # pragma: no cover | |
| st.error(f"Données corrompues (famille non-dict): '{family_name}'. Suppression.") | |
| del processed_data[family_name] | |
| continue | |
| for use_case_name in list(use_cases_in_family.keys()): | |
| config = use_cases_in_family[use_case_name] | |
| if not isinstance(config, dict): # pragma: no cover | |
| st.error(f"Données corrompues (cas d'usage non-dict): '{use_case_name}' dans '{family_name}'. Suppression.") | |
| del processed_data[family_name][use_case_name] | |
| continue | |
| if not isinstance(config.get("variables"), list): | |
| config["variables"] = [] | |
| for var_info in config.get("variables", []): | |
| if isinstance(var_info, dict): | |
| if var_info.get("type") == "date_input" and isinstance(var_info.get("default"), date): | |
| var_info["default"] = var_info["default"].strftime("%Y-%m-%d") | |
| if var_info.get("type") == "number_input": | |
| if "default" in var_info and var_info["default"] is not None: | |
| var_info["default"] = float(var_info["default"]) | |
| if "min_value" in var_info and var_info["min_value"] is not None: | |
| var_info["min_value"] = float(var_info["min_value"]) | |
| if "max_value" in var_info and var_info["max_value"] is not None: | |
| var_info["max_value"] = float(var_info["max_value"]) | |
| if "step" in var_info and var_info["step"] is not None: | |
| var_info["step"] = float(var_info["step"]) | |
| else: | |
| var_info["step"] = 1.0 | |
| # Ensure height for text_area is an int if it exists (it should be already from other functions) | |
| if var_info.get("type") == "text_area": | |
| if "height" in var_info and var_info["height"] is not None: | |
| try: | |
| var_info["height"] = int(var_info["height"]) | |
| except (ValueError, TypeError): # pragma: no cover | |
| var_info["height"] = 100 # Should not happen if data is clean | |
| config.setdefault("tags", []) | |
| if "is_favorite" in config: # pragma: no cover | |
| del config["is_favorite"] | |
| config.setdefault("usage_count", 0) | |
| config.setdefault("created_at", datetime.now().isoformat()) | |
| config.setdefault("updated_at", datetime.now().isoformat()) | |
| return processed_data | |
| def _postprocess_after_loading(loaded_data): # User's trusted version + height fix | |
| processed_data = copy.deepcopy(loaded_data) | |
| now_iso = datetime.now().isoformat() | |
| for family_name in list(processed_data.keys()): | |
| use_cases_in_family = processed_data[family_name] | |
| if not isinstance(use_cases_in_family, dict): # pragma: no cover | |
| st.warning(f"Données corrompues (famille non-dict): '{family_name}'. Ignorée.") | |
| del processed_data[family_name] | |
| continue | |
| for use_case_name in list(use_cases_in_family.keys()): | |
| config = use_cases_in_family[use_case_name] | |
| if not isinstance(config, dict): # pragma: no cover | |
| st.warning(f"Données corrompues (cas d'usage non-dict): '{use_case_name}' dans '{family_name}'. Ignoré.") | |
| del processed_data[family_name][use_case_name] | |
| continue | |
| if not isinstance(config.get("variables"), list): | |
| config["variables"] = [] | |
| for var_info in config.get("variables", []): | |
| if isinstance(var_info, dict): | |
| if var_info.get("type") == "date_input" and isinstance(var_info.get("default"), str): | |
| try: | |
| var_info["default"] = datetime.strptime(var_info["default"], "%Y-%m-%d").date() | |
| except ValueError: | |
| var_info["default"] = datetime.now().date() | |
| if var_info.get("type") == "number_input": | |
| if "default" in var_info and var_info["default"] is not None: | |
| var_info["default"] = float(var_info["default"]) | |
| else: | |
| var_info["default"] = 0.0 | |
| if "min_value" in var_info and var_info["min_value"] is not None: | |
| var_info["min_value"] = float(var_info["min_value"]) | |
| if "max_value" in var_info and var_info["max_value"] is not None: | |
| var_info["max_value"] = float(var_info["max_value"]) | |
| if "step" in var_info and var_info["step"] is not None: | |
| var_info["step"] = float(var_info["step"]) | |
| else: | |
| var_info["step"] = 1.0 | |
| # --- ADDED ROBUST HEIGHT VALIDATION --- | |
| if var_info.get("type") == "text_area": | |
| height_val = var_info.get("height") | |
| if height_val is not None: | |
| try: | |
| h = int(height_val) | |
| if h >= 68: | |
| var_info["height"] = h | |
| else: | |
| var_info["height"] = 68 # Set to minimum if too small | |
| # st.warning(f"Hauteur pour '{var_info.get('name', 'N/A')}' ajustée à 68px (minimum).") | |
| except (ValueError, TypeError): | |
| var_info["height"] = 100 # Default if invalid | |
| # If height_val was None, 'height' key might not be in var_info, or it's None. | |
| # The st.text_area widget call will handle None by using its internal default. | |
| # Or we can explicitly set a default: | |
| # else: | |
| # var_info["height"] = 100 # Default if not present | |
| config.setdefault("tags", []) | |
| if "is_favorite" in config: # pragma: no cover | |
| del config["is_favorite"] | |
| config.setdefault("usage_count", 0) | |
| config.setdefault("created_at", now_iso) | |
| config.setdefault("updated_at", now_iso) | |
| if not isinstance(config.get("tags"), list): config["tags"] = [] | |
| return processed_data | |
| # --- NEW: Simplified function to prepare newly injected use case config --- | |
| def _prepare_newly_injected_use_case_config(uc_config_from_json): | |
| prepared_config = copy.deepcopy(uc_config_from_json) | |
| now_iso_created, now_iso_updated = get_default_dates() | |
| prepared_config["created_at"] = now_iso_created | |
| prepared_config["updated_at"] = now_iso_updated | |
| prepared_config["usage_count"] = 0 | |
| if "template" not in prepared_config or not isinstance(prepared_config["template"], str): # pragma: no cover | |
| prepared_config["template"] = "" | |
| st.warning(f"Cas d'usage injecté '{uc_config_from_json.get('name', 'INCONNU')}' sans template valide. Template initialisé à vide.") | |
| # Ensure description field exists | |
| if "description" not in prepared_config or not isinstance(prepared_config["description"], str): | |
| prepared_config["description"] = "" | |
| if not isinstance(prepared_config.get("variables"), list): | |
| prepared_config["variables"] = [] | |
| for var_info in prepared_config.get("variables", []): # Ensure height is valid for text_area | |
| if isinstance(var_info, dict) and var_info.get("type") == "text_area": | |
| height_val = var_info.get("height") | |
| if height_val is not None: | |
| try: | |
| h = int(height_val) | |
| if h >= 68: var_info["height"] = h | |
| else: var_info["height"] = 68 | |
| except (ValueError, TypeError): | |
| var_info["height"] = 100 # Default if invalid type | |
| # If 'height' key is missing, it's fine; widget will use its default. | |
| if not isinstance(prepared_config.get("tags"), list): | |
| prepared_config["tags"] = [] | |
| else: | |
| prepared_config["tags"] = sorted(list(set(str(tag).strip() for tag in prepared_config["tags"] if str(tag).strip()))) | |
| if "is_favorite" in prepared_config: # pragma: no cover | |
| del prepared_config["is_favorite"] | |
| # Ajout pour la gestion des notes | |
| # if "ratings" not in prepared_config or not isinstance(prepared_config["ratings"], list): | |
| # prepared_config["ratings"] = [] | |
| # if "average_rating" not in prepared_config: | |
| # prepared_config["average_rating"] = 0.0 | |
| return prepared_config | |
| # --- Gist Interaction Functions (User's original versions) --- | |
| def get_local_file_content(): | |
| try: | |
| if os.path.exists(LOCAL_DATA_FILENAME): | |
| with open(LOCAL_DATA_FILENAME, 'r', encoding='utf-8') as f: | |
| content = f.read() | |
| return content if content.strip() else "{}" | |
| else: | |
| st.info(f"Fichier '{LOCAL_DATA_FILENAME}' non trouvé. Initialisation.") | |
| return "{}" | |
| except Exception as e: # pragma: no cover | |
| st.error(f"Erreur de lecture du fichier local: {e}") | |
| return None | |
| def save_to_local_file(new_content_json_string): | |
| try: | |
| with open(LOCAL_DATA_FILENAME, 'w', encoding='utf-8') as f: | |
| f.write(new_content_json_string) | |
| return True | |
| except Exception as e: # pragma: no cover | |
| st.error(f"Erreur de sauvegarde du fichier local: {e}") | |
| return False | |
| # --- Unified save/load functions --- | |
| def save_editable_prompts_to_local_and_hf(): | |
| if 'editable_prompts' in st.session_state: | |
| data_to_save = _preprocess_for_saving(st.session_state.editable_prompts) | |
| try: | |
| json_string = json.dumps(data_to_save, indent=4, ensure_ascii=False) | |
| local_ok = save_to_local_file(json_string) | |
| hf_ok = False | |
| # Save to HF Space from memory (no file write to avoid restart) | |
| if HF_HUB_AVAILABLE: | |
| hf_ok = save_to_hf_space_from_memory(json_string) | |
| if local_ok and hf_ok: | |
| st.toast("💾 Données sauvegardées localement et sur Hugging Face!", icon="💾") | |
| elif local_ok: | |
| st.toast("💾 Données sauvegardées localement!", icon="💾") | |
| elif hf_ok: | |
| st.toast("💾 Données sauvegardées sur Hugging Face!", icon="🤗") | |
| else: | |
| st.warning("Sauvegarde échouée.") | |
| except Exception as e: # pragma: no cover | |
| st.error(f"Erreur préparation données pour sauvegarde: {e}") | |
| def save_to_hf_only(): | |
| """Save to HuggingFace only, without touching local file to prevent app restart""" | |
| if 'editable_prompts' in st.session_state: | |
| data_to_save = _preprocess_for_saving(st.session_state.editable_prompts) | |
| try: | |
| json_string = json.dumps(data_to_save, indent=4, ensure_ascii=False) | |
| # Save directly from memory to avoid any file writes | |
| hf_ok = False | |
| if HF_HUB_AVAILABLE: | |
| hf_ok = save_to_hf_space_from_memory(json_string) | |
| if hf_ok: | |
| st.toast("💾 Configuration sauvegardée sur Hugging Face!", icon="🤗") | |
| else: | |
| st.warning("Sauvegarde HuggingFace échouée.") | |
| except Exception as e: | |
| st.error(f"Erreur lors de la sauvegarde: {e}") | |
| def load_editable_prompts_from_local_or_hf(): | |
| # Try HF first, fallback to local | |
| raw_content = None | |
| if HF_HUB_AVAILABLE: | |
| raw_content = load_from_hf_space() | |
| if not raw_content: | |
| raw_content = get_local_file_content() | |
| if raw_content: | |
| try: | |
| loaded_data = json.loads(raw_content) | |
| if not loaded_data or not isinstance(loaded_data, dict): | |
| raise ValueError("Contenu fichier vide ou mal structuré.") | |
| return _postprocess_after_loading(loaded_data) | |
| except (json.JSONDecodeError, TypeError, ValueError) as e: | |
| st.info(f"Erreur chargement fichier ('{str(e)[:50]}...'). Initialisation avec modèles par défaut.") | |
| else: | |
| st.info("Fichier vide ou inaccessible. Initialisation avec modèles par défaut.") | |
| initial_data = copy.deepcopy(INITIAL_PROMPT_TEMPLATES) | |
| if raw_content is None or raw_content == "{}": | |
| data_to_save_init = _preprocess_for_saving(initial_data) | |
| try: | |
| json_string_init = json.dumps(data_to_save_init, indent=4, ensure_ascii=False) | |
| save_to_local_file(json_string_init) | |
| if HF_HUB_AVAILABLE: | |
| save_to_hf_space_from_memory(json_string_init) | |
| st.info("Modèles par défaut sauvegardés pour initialisation.") | |
| except Exception as e: # pragma: no cover | |
| st.error(f"Erreur sauvegarde initiale: {e}") | |
| return initial_data | |
| # --- Session State Initialization --- | |
| if 'editable_prompts' not in st.session_state: | |
| st.session_state.editable_prompts = load_editable_prompts_from_local_or_hf() | |
| if 'view_mode' not in st.session_state: | |
| st.session_state.view_mode = "accueil" # Nouvelle vue par défaut | |
| if 'library_selected_family_for_display' not in st.session_state: | |
| available_families = list(st.session_state.editable_prompts.keys()) | |
| st.session_state.library_selected_family_for_display = available_families[0] if available_families else None | |
| if 'family_selector_edition' not in st.session_state: | |
| available_families = list(st.session_state.editable_prompts.keys()) | |
| st.session_state.family_selector_edition = available_families[0] if available_families else None | |
| if 'use_case_selector_edition' not in st.session_state: st.session_state.use_case_selector_edition = None | |
| if 'editing_variable_info' not in st.session_state: st.session_state.editing_variable_info = None | |
| if 'show_create_new_use_case_form' not in st.session_state: st.session_state.show_create_new_use_case_form = False | |
| if 'force_select_family_name' not in st.session_state: st.session_state.force_select_family_name = None | |
| if 'force_select_use_case_name' not in st.session_state: st.session_state.force_select_use_case_name = None | |
| if 'confirming_delete_details' not in st.session_state: st.session_state.confirming_delete_details = None | |
| if 'confirming_delete_family_name' not in st.session_state: st.session_state.confirming_delete_family_name = None | |
| if 'library_search_term' not in st.session_state: st.session_state.library_search_term = "" | |
| if 'library_selected_tags' not in st.session_state: st.session_state.library_selected_tags = [] | |
| # Track previous filter values for change detection | |
| if 'previous_search_term' not in st.session_state: st.session_state.previous_search_term = "" | |
| if 'previous_selected_tags' not in st.session_state: st.session_state.previous_selected_tags = [] | |
| if 'variable_type_to_create' not in st.session_state: st.session_state.variable_type_to_create = None | |
| if 'active_generated_prompt' not in st.session_state: st.session_state.active_generated_prompt = "" | |
| if 'duplicating_use_case_details' not in st.session_state: st.session_state.duplicating_use_case_details = None | |
| if 'go_to_config_section' not in st.session_state: st.session_state.go_to_config_section = False | |
| # Generator session state variables | |
| if 'generator_selected_family' not in st.session_state: st.session_state.generator_selected_family = None | |
| if 'generator_selected_use_case' not in st.session_state: st.session_state.generator_selected_use_case = None | |
| if 'injection_selected_family' not in st.session_state: | |
| st.session_state.injection_selected_family = None | |
| if 'injection_json_text' not in st.session_state: | |
| st.session_state.injection_json_text = "" | |
| if 'assistant_form_values' not in st.session_state: | |
| st.session_state.assistant_form_values = {var['name']: var['default'] for var in ASSISTANT_FORM_VARIABLES} | |
| if 'generated_meta_prompt_for_llm' not in st.session_state: | |
| st.session_state.generated_meta_prompt_for_llm = "" | |
| # NOUVELLES CLÉS POUR L'ASSISTANT UNIFIÉ | |
| if 'assistant_mode' not in st.session_state: | |
| st.session_state.assistant_mode = "creation" # Modes possibles: "creation", "amelioration" | |
| if 'assistant_existing_prompt_value' not in st.session_state: | |
| st.session_state.assistant_existing_prompt_value = "" | |
| if 'assistant_api_processing' not in st.session_state: | |
| st.session_state.assistant_api_processing = False | |
| if 'assistant_generated_json' not in st.session_state: | |
| st.session_state.assistant_generated_json = None | |
| if 'assistant_selected_family' not in st.session_state: | |
| st.session_state.assistant_selected_family = None | |
| # --- Sidebar Navigation with Tabs --- | |
| st.sidebar.header("Menu Principal") | |
| tab_bibliotheque, tab_edition_generation, tab_injection = st.sidebar.tabs([ | |
| "📚 Bibliothèque", | |
| "✍️ Édition", | |
| "💡 Assistant" | |
| ]) | |
| # --- Tab: Bibliothèque (Sidebar content) --- | |
| with tab_bibliotheque: | |
| st.subheader("Explorer la Bibliothèque de Prompts") | |
| search_col, filter_tag_col = st.columns(2) | |
| with search_col: | |
| st.session_state.library_search_term = st.text_input( | |
| "🔍 Rechercher par mot-clé:", | |
| value=st.session_state.get("library_search_term", ""), | |
| placeholder="Nom, template, variable..." | |
| ) | |
| all_tags_list = sorted(list(set(tag for family in st.session_state.editable_prompts.values() for uc in family.values() for tag in uc.get("tags", [])))) | |
| with filter_tag_col: | |
| st.session_state.library_selected_tags = st.multiselect( | |
| "🏷️ Filtrer par Tags:", | |
| options=all_tags_list, | |
| default=st.session_state.get("library_selected_tags", []) | |
| ) | |
| # Detect filter changes and auto-redirect to global search results | |
| current_search_term = st.session_state.get("library_search_term", "").strip() | |
| current_selected_tags = st.session_state.get("library_selected_tags", []) | |
| # Check if filters have changed | |
| search_changed = current_search_term != st.session_state.get("previous_search_term", "") | |
| tags_changed = current_selected_tags != st.session_state.get("previous_selected_tags", []) | |
| # If filters changed and we have active filters, redirect to global search | |
| if (search_changed or tags_changed) and (current_search_term or current_selected_tags): | |
| # Update previous values | |
| st.session_state.previous_search_term = current_search_term | |
| st.session_state.previous_selected_tags = current_selected_tags.copy() | |
| # Redirect to global search page | |
| if st.session_state.view_mode != "select_family_for_library": | |
| st.session_state.view_mode = "select_family_for_library" | |
| st.rerun() | |
| # Update previous values even when filters are cleared | |
| elif not current_search_term and not current_selected_tags: | |
| st.session_state.previous_search_term = current_search_term | |
| st.session_state.previous_selected_tags = current_selected_tags.copy() | |
| st.markdown("---") | |
| if not st.session_state.editable_prompts or not any(st.session_state.editable_prompts.values()): | |
| st.info("La bibliothèque est vide. Ajoutez des prompts via l'onglet 'Édition'.") | |
| else: | |
| sorted_families_bib = sorted(list(st.session_state.editable_prompts.keys())) | |
| if not st.session_state.get('library_selected_family_for_display') or \ | |
| st.session_state.library_selected_family_for_display not in sorted_families_bib: | |
| st.session_state.library_selected_family_for_display = sorted_families_bib[0] if sorted_families_bib else None | |
| st.write("Sélectionner un métier à afficher :") | |
| for family_name_bib in sorted_families_bib: | |
| button_key = f"lib_family_btn_{family_name_bib.replace(' ', '_').replace('&', '_')}" | |
| is_selected_family = (st.session_state.library_selected_family_for_display == family_name_bib) | |
| if st.button( | |
| family_name_bib, | |
| key=button_key, | |
| use_container_width=True, | |
| type="primary" if is_selected_family else "secondary" | |
| ): | |
| if st.session_state.library_selected_family_for_display != family_name_bib: | |
| st.session_state.library_selected_family_for_display = family_name_bib | |
| st.session_state.view_mode = "library" | |
| st.rerun() | |
| st.markdown("---") | |
| # --- Tab: Édition (Sidebar content) --- | |
| with tab_edition_generation: | |
| st.subheader("Explorateur de Prompts") | |
| available_families = list(st.session_state.editable_prompts.keys()) | |
| default_family_idx_edit = 0 | |
| current_family_for_edit = st.session_state.get('family_selector_edition') | |
| if st.session_state.force_select_family_name and st.session_state.force_select_family_name in available_families: | |
| current_family_for_edit = st.session_state.force_select_family_name | |
| st.session_state.family_selector_edition = current_family_for_edit | |
| elif current_family_for_edit and current_family_for_edit in available_families: | |
| pass | |
| elif available_families: | |
| current_family_for_edit = available_families[0] | |
| st.session_state.family_selector_edition = current_family_for_edit | |
| else: | |
| current_family_for_edit = None | |
| st.session_state.family_selector_edition = None | |
| if current_family_for_edit and current_family_for_edit in available_families: | |
| default_family_idx_edit = available_families.index(current_family_for_edit) | |
| elif available_families: | |
| default_family_idx_edit = 0 | |
| current_family_for_edit = available_families[0] | |
| st.session_state.family_selector_edition = current_family_for_edit | |
| else: | |
| default_family_idx_edit = 0 | |
| if not available_families: | |
| st.info("Aucune famille de métier de cas d'usage. Créez-en une via les options ci-dessous.") | |
| else: | |
| prev_family_selection_edit = st.session_state.get('family_selector_edition') | |
| selected_family_ui_edit = st.selectbox( | |
| "Métier :", | |
| options=available_families, | |
| index=default_family_idx_edit, | |
| key='family_selectbox_widget_edit', | |
| help="Sélectionnez une métier pour voir ses cas d'usage." | |
| ) | |
| if st.session_state.family_selector_edition != selected_family_ui_edit : | |
| st.session_state.family_selector_edition = selected_family_ui_edit | |
| if prev_family_selection_edit != selected_family_ui_edit: | |
| st.session_state.use_case_selector_edition = None | |
| st.session_state.force_select_use_case_name = None | |
| st.session_state.view_mode = "generator" | |
| st.session_state.active_generated_prompt = "" | |
| st.session_state.variable_type_to_create = None | |
| st.session_state.editing_variable_info = None | |
| st.rerun() | |
| current_selected_family_for_edit_logic = st.session_state.get('family_selector_edition') | |
| use_cases_in_current_family_edit_options = [] | |
| if current_selected_family_for_edit_logic and current_selected_family_for_edit_logic in st.session_state.editable_prompts: | |
| use_cases_in_current_family_edit_options = sorted(list(st.session_state.editable_prompts[current_selected_family_for_edit_logic].keys())) | |
| if use_cases_in_current_family_edit_options: | |
| default_uc_idx_edit = 0 | |
| current_uc_for_edit = st.session_state.get('use_case_selector_edition') | |
| if st.session_state.force_select_use_case_name and st.session_state.force_select_use_case_name in use_cases_in_current_family_edit_options: | |
| current_uc_for_edit = st.session_state.force_select_use_case_name | |
| elif current_uc_for_edit and current_uc_for_edit in use_cases_in_current_family_edit_options: | |
| pass | |
| elif use_cases_in_current_family_edit_options: | |
| current_uc_for_edit = use_cases_in_current_family_edit_options[0] | |
| st.session_state.use_case_selector_edition = current_uc_for_edit | |
| if current_uc_for_edit and current_uc_for_edit in use_cases_in_current_family_edit_options: | |
| default_uc_idx_edit = use_cases_in_current_family_edit_options.index(current_uc_for_edit) | |
| prev_uc_selection_edit = st.session_state.get('use_case_selector_edition') | |
| selected_use_case_ui_edit = st.radio( | |
| "Cas d'usage :", | |
| options=use_cases_in_current_family_edit_options, | |
| index=default_uc_idx_edit, | |
| key='use_case_radio_widget_edit', | |
| help="Sélectionnez un cas d'usage pour générer un prompt ou le paramétrer." | |
| ) | |
| if st.session_state.use_case_selector_edition != selected_use_case_ui_edit: | |
| st.session_state.use_case_selector_edition = selected_use_case_ui_edit | |
| if prev_uc_selection_edit != selected_use_case_ui_edit: | |
| st.session_state.view_mode = "generator" | |
| st.session_state.active_generated_prompt = "" | |
| st.session_state.variable_type_to_create = None | |
| st.session_state.editing_variable_info = None | |
| st.rerun() | |
| elif current_selected_family_for_edit_logic: | |
| st.info(f"Aucun cas d'usage dans '{current_selected_family_for_edit_logic}'. Créez-en un.") | |
| st.session_state.use_case_selector_edition = None | |
| if st.session_state.force_select_family_name: st.session_state.force_select_family_name = None | |
| if st.session_state.force_select_use_case_name: st.session_state.force_select_use_case_name = None | |
| st.markdown("---") | |
| with st.expander("🗂️ Gérer les familles de prompts par métier", expanded=False): | |
| with st.form("new_family_form_sidebar", clear_on_submit=True): | |
| new_family_name = st.text_input("Nom du nouveau métier:", key="new_fam_name_sidebar") | |
| submitted_new_family = st.form_submit_button("➕ Créer métier") | |
| if submitted_new_family and new_family_name.strip(): | |
| if new_family_name.strip() in st.session_state.editable_prompts: | |
| st.error(f"Le métier '{new_family_name.strip()}' existe déjà.") | |
| else: | |
| st.session_state.editable_prompts[new_family_name.strip()] = {} | |
| save_editable_prompts_to_local_and_hf() | |
| st.success(f"Métier '{new_family_name.strip()}' créée.") | |
| st.session_state.force_select_family_name = new_family_name.strip() | |
| st.session_state.use_case_selector_edition = None | |
| st.session_state.view_mode = "generator" | |
| st.rerun() | |
| elif submitted_new_family: | |
| st.error("Le nom du métier ne peut pas être vide.") | |
| if available_families and current_selected_family_for_edit_logic : | |
| st.markdown("---") | |
| with st.form("rename_family_form_sidebar"): | |
| st.write(f"Renommer le métier : **{current_selected_family_for_edit_logic}**") | |
| renamed_family_name_input = st.text_input("Nouveau nom :", value=current_selected_family_for_edit_logic, key="ren_fam_name_sidebar") | |
| submitted_rename_family = st.form_submit_button("✏️ Renommer") | |
| if submitted_rename_family and renamed_family_name_input.strip(): | |
| renamed_family_name = renamed_family_name_input.strip() | |
| if renamed_family_name == current_selected_family_for_edit_logic: | |
| st.info("Le nouveau nom est identique à l'ancien.") | |
| elif renamed_family_name in st.session_state.editable_prompts: | |
| st.error(f"Un métier nommé '{renamed_family_name}' existe déjà.") | |
| else: | |
| st.session_state.editable_prompts[renamed_family_name] = st.session_state.editable_prompts.pop(current_selected_family_for_edit_logic) | |
| save_editable_prompts_to_local_and_hf() | |
| st.success(f"Métier '{current_selected_family_for_edit_logic}' renommé en '{renamed_family_name}'.") | |
| st.session_state.force_select_family_name = renamed_family_name | |
| if st.session_state.library_selected_family_for_display == current_selected_family_for_edit_logic: | |
| st.session_state.library_selected_family_for_display = renamed_family_name | |
| st.session_state.view_mode = "generator" | |
| st.rerun() | |
| elif submitted_rename_family: | |
| st.error("Le nouveau nom du métier ne peut pas être vide.") | |
| st.markdown("---") | |
| st.write(f"Supprimer le métier : **{current_selected_family_for_edit_logic}**") | |
| if st.session_state.confirming_delete_family_name == current_selected_family_for_edit_logic: | |
| st.warning(f"Supprimer '{current_selected_family_for_edit_logic}' et tous ses cas d'usage ? Action irréversible.") | |
| _text_confirm_delete = f"Oui, supprimer définitivement '{current_selected_family_for_edit_logic}'" | |
| if st.button(_text_confirm_delete, type="primary", key=f"confirm_del_fam_sb_{current_selected_family_for_edit_logic}", use_container_width=True): | |
| deleted_fam_name = current_selected_family_for_edit_logic | |
| del st.session_state.editable_prompts[current_selected_family_for_edit_logic] | |
| save_editable_prompts_to_local_and_hf() | |
| st.success(f"Métier '{deleted_fam_name}' supprimée.") | |
| st.session_state.confirming_delete_family_name = None | |
| st.session_state.family_selector_edition = None | |
| st.session_state.use_case_selector_edition = None | |
| if st.session_state.library_selected_family_for_display == deleted_fam_name: | |
| st.session_state.library_selected_family_for_display = None | |
| st.session_state.view_mode = "library" | |
| st.rerun() | |
| if st.button("Non, annuler la suppression", key=f"cancel_del_fam_sb_{current_selected_family_for_edit_logic}", use_container_width=True): | |
| st.session_state.confirming_delete_family_name = None | |
| st.session_state.view_mode = "generator" | |
| st.rerun() | |
| else: | |
| if st.button(f"🗑️ Supprimer le métier Sélectionnée", key=f"del_fam_btn_sb_{current_selected_family_for_edit_logic}"): | |
| st.session_state.confirming_delete_family_name = current_selected_family_for_edit_logic | |
| st.session_state.view_mode = "generator" | |
| st.rerun() | |
| elif not available_families: | |
| st.caption("Créez un métier pour pouvoir le gérer.") | |
| else: | |
| st.caption("Sélectionnez un métier (ci-dessus) pour le gérer.") | |
| st.markdown("---") | |
| with st.expander("➕ Créer un Cas d'Usage", expanded=st.session_state.get('show_create_new_use_case_form', False)): | |
| if not available_families: | |
| st.caption("Veuillez d'abord créer une famille de métier pour y ajouter des cas d'usage.") | |
| else: | |
| if st.button("Afficher/Masquer Formulaire de Création de Cas d'Usage", key="toggle_create_uc_form_in_exp"): | |
| st.session_state.show_create_new_use_case_form = not st.session_state.get('show_create_new_use_case_form', False) | |
| st.rerun() | |
| if st.session_state.get('show_create_new_use_case_form', False): | |
| with st.form("new_use_case_form_in_exp", clear_on_submit=True): | |
| default_create_family_idx_tab = 0 | |
| if current_selected_family_for_edit_logic and current_selected_family_for_edit_logic in available_families: | |
| default_create_family_idx_tab = available_families.index(current_selected_family_for_edit_logic) | |
| uc_parent_family = st.selectbox( | |
| "Métier parent du nouveau cas d'usage:", | |
| options=available_families, | |
| index=default_create_family_idx_tab, | |
| key="new_uc_parent_fam_in_exp" | |
| ) | |
| uc_name_input = st.text_input("Nom du Nouveau Cas d'Usage:", key="new_uc_name_in_exp") | |
| uc_description_input = st.text_area("Description du cas d'usage:", height=100, key="new_uc_desc_in_exp", value="") | |
| uc_template_input = st.text_area("Template Initial du Cas d'Usage:", height=150, key="new_uc_template_in_exp", value="Nouveau prompt...") | |
| submitted_new_uc = st.form_submit_button("Créer Cas d'Usage") | |
| if submitted_new_uc: | |
| parent_family_val = uc_parent_family | |
| uc_name_val = uc_name_input.strip() | |
| uc_template_val = uc_template_input | |
| uc_description_val = uc_description_input.strip() | |
| if not uc_name_val: | |
| st.error("Le nom du cas d'usage ne peut pas être vide.") | |
| elif uc_name_val in st.session_state.editable_prompts.get(parent_family_val, {}): | |
| st.error(f"Le cas d'usage '{uc_name_val}' existe déjà dans le métier '{parent_family_val}'.") | |
| else: | |
| now_iso_create, now_iso_update = get_default_dates() | |
| st.session_state.editable_prompts[parent_family_val][uc_name_val] = { | |
| "description": uc_description_val, | |
| "template": uc_template_val or "Nouveau prompt...", | |
| "variables": [], "tags": [], | |
| "usage_count": 0, "created_at": now_iso_create, "updated_at": now_iso_update | |
| } | |
| save_editable_prompts_to_local_and_hf() | |
| st.success(f"Cas d'usage '{uc_name_val}' créé avec succès dans '{parent_family_val}'.") | |
| st.session_state.show_create_new_use_case_form = False | |
| st.session_state.force_select_family_name = parent_family_val | |
| st.session_state.force_select_use_case_name = uc_name_val | |
| st.session_state.view_mode = "generator" | |
| st.session_state.active_generated_prompt = "" | |
| st.rerun() | |
| # --- Tab: Injection (Sidebar content) --- | |
| with tab_injection: | |
| st.subheader("Assistant & Injection") | |
| st.markdown("Utilisez l'assistant pour préparer un prompt système ou injectez des cas d'usage en format JSON.") | |
| # MODIFICATION DU BOUTON EXISTANT | |
| if st.button("✨ Assistant Prompt Système", key="start_assistant_unified_btn", use_container_width=True): # Nom du bouton mis à jour | |
| st.session_state.view_mode = "assistant_creation" | |
| # Réinitialiser au mode "creation" par défaut et vider les champs des deux modes potentiels | |
| st.session_state.assistant_mode = "creation" | |
| st.session_state.assistant_form_values = {var['name']: var['default'] for var in ASSISTANT_FORM_VARIABLES} | |
| st.session_state.assistant_existing_prompt_value = "" | |
| st.session_state.generated_meta_prompt_for_llm = "" # Le méta-prompt généré est commun | |
| st.rerun() | |
| if st.button("💉 Injecter JSON Manuellement", key="start_manual_injection_btn", use_container_width=True): | |
| st.session_state.view_mode = "inject_manual" | |
| st.session_state.injection_selected_family = None | |
| st.session_state.injection_json_text = "" | |
| st.session_state.generated_meta_prompt_for_llm = "" # Aussi réinitialiser ici | |
| st.rerun() | |
| # --- Main Display Area --- | |
| # Handle force selection after injection | |
| if st.session_state.get('force_select_family_name'): | |
| st.session_state.family_selector_edition = st.session_state.force_select_family_name | |
| st.session_state.force_select_family_name = None | |
| if st.session_state.get('force_select_use_case_name'): | |
| st.session_state.use_case_selector_edition = st.session_state.force_select_use_case_name | |
| st.session_state.force_select_use_case_name = None | |
| library_family_to_display = st.session_state.get('library_selected_family_for_display') | |
| # NOUVELLE SECTION POUR LA PAGE D'ACCUEIL | |
| if st.session_state.view_mode == "accueil": | |
| st.header("Bienvenue dans votre laboratoire des prompts IA ! 💡") | |
| st.caption(f"Créé par le pôle Data / IA") | |
| st.markdown(""" | |
| Vous êtes au bon endroit pour maîtriser l'art de "parler" aux Intelligences Artificielles (IA) et obtenir d'elles exactement ce dont vous avez besoin ! | |
| **Qu'est-ce qu'un "prompt" ?** | |
| Imaginez donner des instructions à un assistant virtuel intelligent, mais qui a besoin de consignes claires. Un "prompt", c'est simplement cette instruction, cette question ou cette consigne que vous formulez à l'IA. | |
| Plus votre instruction est bien pensée, plus l'IA vous fournira une réponse utile et pertinente. | |
| **Que pouvez-vous faire avec cette application ?** | |
| Cet outil est conçu pour vous simplifier la vie, que vous soyez novice ou plus expérimenté : | |
| * **Découvrir et utiliser des modèles d'instructions prêts à l'emploi** : Explorez une collection de "prompts" déjà conçus pour diverses tâches (comme rédiger un email, résumer un document, analyser une situation, etc.). Vous pourrez les utiliser tels quels ou les adapter facilement. | |
| * **Créer vos propres instructions sur mesure** : Vous avez une idée précise en tête ? Notre assistant vous guide pas à pas pour construire le "prompt" parfait, même si vous n'avez aucune connaissance technique. L'objectif est de transformer votre besoin en une instruction claire pour l'IA. | |
| * **Organiser et améliorer vos instructions** : Conservez vos meilleurs "prompts", modifiez-les et perfectionnez-les au fil du temps. | |
| En bref, cet outil vous aide à formuler les meilleures demandes possibles aux IA pour qu'elles deviennent de véritables alliées dans votre travail ou vos projets. | |
| """) | |
| cols_accueil = st.columns(2) | |
| with cols_accueil[0]: | |
| if st.button("📚 Je souhaite utiliser / modifier un prompt existant", use_container_width=True, type="primary"): | |
| st.session_state.view_mode = "select_family_for_library" | |
| st.rerun() | |
| with cols_accueil[1]: | |
| if st.button("✨ Je souhaite créer un prompt à partir de mon besoin", use_container_width=True, type="primary"): | |
| st.session_state.view_mode = "assistant_creation" | |
| # Réinitialiser les valeurs du formulaire de l'assistant et le prompt généré | |
| st.session_state.assistant_form_values = {var['name']: var['default'] for var in ASSISTANT_FORM_VARIABLES} | |
| st.session_state.generated_meta_prompt_for_llm = "" | |
| st.rerun() | |
| elif st.session_state.view_mode == "select_family_for_library": | |
| if st.button("⬅️ Retour à l'accueil", key="back_to_accueil_from_select_family"): | |
| st.session_state.view_mode = "accueil" | |
| st.rerun() | |
| # Check if global filters are active | |
| search_term_lib = st.session_state.get("library_search_term", "").strip().lower() | |
| selected_tags_lib = st.session_state.get("library_selected_tags", []) | |
| has_active_filters = bool(search_term_lib or selected_tags_lib) | |
| if has_active_filters: | |
| st.header("📚 Résultats de recherche dans tous les métiers") | |
| if search_term_lib and selected_tags_lib: | |
| st.markdown(f"Recherche: **{search_term_lib}** | Tags: **{', '.join(selected_tags_lib)}**") | |
| elif search_term_lib: | |
| st.markdown(f"Recherche: **{search_term_lib}**") | |
| elif selected_tags_lib: | |
| st.markdown(f"Tags: **{', '.join(selected_tags_lib)}**") | |
| st.markdown("---") | |
| # Global filtering across all families | |
| global_filtered_results = {} | |
| for family_name, use_cases in st.session_state.editable_prompts.items(): | |
| family_filtered_use_cases = {} | |
| for uc_name, uc_config in use_cases.items(): | |
| match_search = True | |
| if search_term_lib: | |
| match_search = (search_term_lib in uc_name.lower() or | |
| search_term_lib in uc_config.get("template", "").lower() or | |
| any(search_term_lib in var.get("name","").lower() or search_term_lib in var.get("label","").lower() | |
| for var in uc_config.get("variables", [])) or | |
| any(search_term_lib in tag.lower() for tag in uc_config.get("tags", []))) | |
| match_tags = True | |
| if selected_tags_lib: | |
| match_tags = all(tag in uc_config.get("tags", []) for tag in selected_tags_lib) | |
| if match_search and match_tags: | |
| family_filtered_use_cases[uc_name] = uc_config | |
| if family_filtered_use_cases: | |
| global_filtered_results[family_name] = family_filtered_use_cases | |
| if not global_filtered_results: | |
| st.info("Aucun prompt ne correspond à vos critères de recherche dans tous les métiers.") | |
| else: | |
| # Display results grouped by family | |
| for family_name, filtered_use_cases in sorted(global_filtered_results.items()): | |
| st.subheader(f"🔹 {family_name}") | |
| sorted_use_cases = sorted(filtered_use_cases.keys()) | |
| for uc_name in sorted_use_cases: | |
| uc_config = filtered_use_cases[uc_name] | |
| exp_title = f"{uc_name}" | |
| if uc_config.get("usage_count", 0) > 0: | |
| exp_title += f" (Utilisé {uc_config.get('usage_count')} fois)" | |
| with st.expander(exp_title, expanded=False): | |
| # Display tags in the same format as standard library view | |
| tags_display = uc_config.get("tags", []) | |
| if tags_display: | |
| st.markdown(f"**Tags :** {', '.join([f'`{tag}`' for tag in tags_display])}") | |
| # Display creation and modification dates | |
| created_at_str = uc_config.get('created_at', get_default_dates()[0]) | |
| updated_at_str = uc_config.get('updated_at', get_default_dates()[1]) | |
| st.caption(f"Créé le : {datetime.fromisoformat(created_at_str).strftime('%d/%m/%Y %H:%M')} | Modifié le : {datetime.fromisoformat(updated_at_str).strftime('%d/%m/%Y %H:%M')}") | |
| # Three buttons in columns - same format as standard library view | |
| col_btn_lib1, col_btn_lib2, col_btn_lib3 = st.columns(3) | |
| with col_btn_lib1: | |
| if st.button(f"✍️ Utiliser ce prompt", key=f"global_lib_use_{family_name.replace(' ', '_')}_{uc_name.replace(' ', '_')}", use_container_width=True): | |
| st.session_state.view_mode = "generator" | |
| st.session_state.generator_selected_family = family_name | |
| st.session_state.generator_selected_use_case = uc_name | |
| st.session_state.active_generated_prompt = "" | |
| st.rerun() | |
| with col_btn_lib2: | |
| if st.button(f"📋 Dupliquer ce prompt", key=f"global_lib_duplicate_{family_name.replace(' ', '_')}_{uc_name.replace(' ', '_')}", use_container_width=True): | |
| st.session_state.duplicating_use_case_details = { | |
| "family": family_name, | |
| "use_case": uc_name | |
| } | |
| st.rerun() | |
| with col_btn_lib3: | |
| if st.button(f"🗑️ Supprimer ce prompt", key=f"global_lib_delete_{family_name.replace(' ', '_')}_{uc_name.replace(' ', '_')}", use_container_width=True): | |
| st.session_state.confirming_delete_details = { | |
| "family": family_name, | |
| "use_case": uc_name | |
| } | |
| st.rerun() | |
| st.markdown("---") | |
| # Clear filters option | |
| if st.button("🗑️ Effacer les filtres", type="secondary"): | |
| st.session_state.library_search_term = "" | |
| st.session_state.library_selected_tags = [] | |
| st.rerun() | |
| else: | |
| st.header("📚 Explorer les prompts par métier") | |
| st.markdown("Cliquez sur le nom d'un métier pour afficher les prompts associés.") | |
| st.markdown("---") | |
| available_families = list(st.session_state.editable_prompts.keys()) | |
| if not available_families: | |
| st.info("Aucun métier de prompts n'a été créé pour le moment.") | |
| st.markdown("Vous pouvez en créer via l'onglet **Édition** dans le menu latéral (accessible via l'icône Menu en haut à gauche).") | |
| st.markdown("---") | |
| else: | |
| sorted_families = sorted(available_families) | |
| # Vous pouvez ajuster le nombre de colonnes si vous avez beaucoup de familles | |
| num_cols = 3 | |
| cols = st.columns(num_cols) | |
| for i, family_name in enumerate(sorted_families): | |
| with cols[i % num_cols]: | |
| if st.button(f"{family_name}", key=f"select_family_for_lib_btn_{family_name}", use_container_width=True, help=f"Voir les prompts du métier '{family_name}'"): | |
| st.session_state.library_selected_family_for_display = family_name | |
| st.session_state.view_mode = "library" # Redirige vers la bibliothèque avec la famille sélectionnée | |
| st.rerun() | |
| st.markdown("---") | |
| elif st.session_state.view_mode == "library": | |
| if st.button("⬅️ Retour à la sélection des métiers", key="back_to_select_family_from_library"): | |
| st.session_state.view_mode = "select_family_for_library" | |
| st.rerun() | |
| if not library_family_to_display: | |
| st.info("Veuillez sélectionner un métier dans la barre latérale (onglet Bibliothèque) pour afficher les prompts.") | |
| available_families_main_display = list(st.session_state.editable_prompts.keys()) | |
| if available_families_main_display: | |
| st.session_state.library_selected_family_for_display = available_families_main_display[0] | |
| st.rerun() | |
| elif not any(st.session_state.editable_prompts.values()): | |
| st.warning("Aucun métier de cas d'usage n'est configurée. Créez-en via l'onglet 'Édition'.") | |
| elif library_family_to_display in st.session_state.editable_prompts: | |
| st.header(f"Bibliothèque - métier : {library_family_to_display}") | |
| use_cases_in_family_display = st.session_state.editable_prompts[library_family_to_display] | |
| filtered_use_cases = {} | |
| search_term_lib = st.session_state.get("library_search_term", "").strip().lower() | |
| selected_tags_lib = st.session_state.get("library_selected_tags", []) | |
| if use_cases_in_family_display: | |
| for uc_name, uc_config in use_cases_in_family_display.items(): | |
| match_search = True | |
| if search_term_lib: | |
| match_search = (search_term_lib in uc_name.lower() or | |
| search_term_lib in uc_config.get("template", "").lower() or | |
| any(search_term_lib in var.get("name","").lower() or search_term_lib in var.get("label","").lower() | |
| for var in uc_config.get("variables", [])) or | |
| any(search_term_lib in tag.lower() for tag in uc_config.get("tags", []))) | |
| match_tags = True | |
| if selected_tags_lib: match_tags = all(tag in uc_config.get("tags", []) for tag in selected_tags_lib) | |
| if match_search and match_tags: filtered_use_cases[uc_name] = uc_config | |
| if not filtered_use_cases: | |
| if not use_cases_in_family_display: st.info(f"Le métier '{library_family_to_display}' ne contient actuellement aucun prompt.") | |
| else: st.info("Aucun prompt ne correspond à vos critères de recherche/filtre dans cette métier.") | |
| else: | |
| # Gestion de la duplication de cas d'usage | |
| if st.session_state.duplicating_use_case_details and \ | |
| st.session_state.duplicating_use_case_details["family"] == library_family_to_display: | |
| original_uc_name_for_dup = st.session_state.duplicating_use_case_details["use_case"] | |
| original_family_name_for_dup = st.session_state.duplicating_use_case_details["family"] | |
| st.markdown(f"### 📋 Dupliquer '{original_uc_name_for_dup}' (depuis: {original_family_name_for_dup})") | |
| form_key_duplicate = f"form_duplicate_lib_{original_family_name_for_dup.replace(' ','_')}_{original_uc_name_for_dup.replace(' ','_')}" | |
| with st.form(key=form_key_duplicate): | |
| available_families_list = list(st.session_state.editable_prompts.keys()) | |
| try: | |
| default_family_idx = available_families_list.index(original_family_name_for_dup) | |
| except ValueError: | |
| default_family_idx = 0 | |
| selected_target_family_for_duplicate = st.selectbox( | |
| "Choisir la famille de destination pour la copie :", | |
| options=available_families_list, | |
| index=default_family_idx, | |
| key=f"target_family_dup_select_{form_key_duplicate}" | |
| ) | |
| suggested_new_name_base = f"{original_uc_name_for_dup} (copie)" | |
| suggested_new_name = suggested_new_name_base | |
| temp_copy_count = 1 | |
| while suggested_new_name in st.session_state.editable_prompts.get(selected_target_family_for_duplicate, {}): | |
| suggested_new_name = f"{suggested_new_name_base} {temp_copy_count}" | |
| temp_copy_count += 1 | |
| new_duplicated_uc_name_input = st.text_input( | |
| "Nouveau nom pour le cas d'usage dupliqué:", | |
| value=suggested_new_name, | |
| key=f"new_dup_name_input_{form_key_duplicate}" | |
| ) | |
| submitted_duplicate_form = st.form_submit_button("✅ Confirmer la Duplication", use_container_width=True) | |
| if submitted_duplicate_form: | |
| new_uc_name_val_from_form = new_duplicated_uc_name_input.strip() | |
| target_family_on_submit = selected_target_family_for_duplicate | |
| if not new_uc_name_val_from_form: | |
| st.error("Le nom du nouveau cas d'usage ne peut pas être vide.") | |
| elif new_uc_name_val_from_form in st.session_state.editable_prompts.get(target_family_on_submit, {}): | |
| st.error(f"Un cas d'usage nommé '{new_uc_name_val_from_form}' existe déjà dans la famille '{target_family_on_submit}'.") | |
| else: | |
| current_prompt_config = st.session_state.editable_prompts[original_family_name_for_dup][original_uc_name_for_dup] | |
| st.session_state.editable_prompts[target_family_on_submit][new_uc_name_val_from_form] = copy.deepcopy(current_prompt_config) | |
| now_iso_dup_create, now_iso_dup_update = get_default_dates() | |
| st.session_state.editable_prompts[target_family_on_submit][new_uc_name_val_from_form]["created_at"] = now_iso_dup_create | |
| st.session_state.editable_prompts[target_family_on_submit][new_uc_name_val_from_form]["updated_at"] = now_iso_dup_update | |
| st.session_state.editable_prompts[target_family_on_submit][new_uc_name_val_from_form]["usage_count"] = 0 | |
| save_editable_prompts_to_local_and_hf() | |
| st.success(f"Cas d'usage '{original_uc_name_for_dup}' dupliqué en '{new_uc_name_val_from_form}' dans la famille '{target_family_on_submit}'.") | |
| st.session_state.duplicating_use_case_details = None | |
| if target_family_on_submit != library_family_to_display: | |
| st.session_state.library_selected_family_for_display = target_family_on_submit | |
| st.rerun() | |
| cancel_key_duplicate = f"cancel_dup_process_lib_{original_family_name_for_dup.replace(' ','_')}_{original_uc_name_for_dup.replace(' ','_')}" | |
| if st.button("❌ Annuler la Duplication", key=cancel_key_duplicate, use_container_width=True): | |
| st.session_state.duplicating_use_case_details = None | |
| st.rerun() | |
| st.markdown("---") | |
| # Gestion de la suppression de cas d'usage | |
| if st.session_state.confirming_delete_details and \ | |
| st.session_state.confirming_delete_details["family"] == library_family_to_display: | |
| details = st.session_state.confirming_delete_details | |
| st.warning(f"⚠️ Supprimer '{details['use_case']}' de '{details['family']}' ? Action irréversible.") | |
| c1_del_uc, c2_del_uc, _ = st.columns([1,1,3]) | |
| if c1_del_uc.button(f"Oui, supprimer '{details['use_case']}'", key=f"del_yes_lib_{details['family']}_{details['use_case']}", type="primary"): | |
| deleted_uc_name_for_msg = details['use_case'] | |
| deleted_uc_fam_for_msg = details['family'] | |
| del st.session_state.editable_prompts[details["family"]][details["use_case"]] | |
| save_editable_prompts_to_local_and_hf() | |
| st.success(f"'{deleted_uc_name_for_msg}' supprimé de '{deleted_uc_fam_for_msg}'.") | |
| st.session_state.confirming_delete_details = None | |
| st.rerun() | |
| if c2_del_uc.button("Non, annuler", key=f"del_no_lib_{details['family']}_{details['use_case']}"): | |
| st.session_state.confirming_delete_details = None | |
| st.rerun() | |
| st.markdown("---") | |
| sorted_use_cases_display = sorted(list(filtered_use_cases.keys())) | |
| for use_case_name_display in sorted_use_cases_display: | |
| prompt_config_display = filtered_use_cases[use_case_name_display] | |
| template_display = prompt_config_display.get("template", "_Template non défini._") | |
| exp_title = f"{use_case_name_display}" | |
| if prompt_config_display.get("usage_count", 0) > 0: exp_title += f" (Utilisé {prompt_config_display.get('usage_count')} fois)" | |
| with st.expander(exp_title, expanded=False): | |
| tags_display = prompt_config_display.get("tags", []) | |
| if tags_display: st.markdown(f"**Tags :** {', '.join([f'`{tag}`' for tag in tags_display])}") | |
| created_at_str = prompt_config_display.get('created_at', get_default_dates()[0]) | |
| updated_at_str = prompt_config_display.get('updated_at', get_default_dates()[1]) | |
| st.caption(f"Créé le : {datetime.fromisoformat(created_at_str).strftime('%d/%m/%Y %H:%M')} | Modifié le : {datetime.fromisoformat(updated_at_str).strftime('%d/%m/%Y %H:%M')}") | |
| col_btn_lib1, col_btn_lib2, col_btn_lib3 = st.columns(3) | |
| with col_btn_lib1: | |
| if st.button(f"✍️ Utiliser ce prompt", key=f"main_lib_use_{library_family_to_display.replace(' ', '_')}_{use_case_name_display.replace(' ', '_')}", use_container_width=True): | |
| st.session_state.view_mode = "generator"; st.session_state.generator_selected_family = library_family_to_display; st.session_state.generator_selected_use_case = use_case_name_display; st.session_state.active_generated_prompt = ""; st.rerun() | |
| with col_btn_lib2: | |
| if st.button(f"📋 Dupliquer ce prompt", key=f"main_lib_duplicate_{library_family_to_display.replace(' ', '_')}_{use_case_name_display.replace(' ', '_')}", use_container_width=True): | |
| st.session_state.duplicating_use_case_details = { | |
| "family": library_family_to_display, | |
| "use_case": use_case_name_display | |
| } | |
| st.rerun() | |
| with col_btn_lib3: | |
| if st.button(f"🗑️ Supprimer ce prompt", key=f"main_lib_delete_{library_family_to_display.replace(' ', '_')}_{use_case_name_display.replace(' ', '_')}", use_container_width=True): | |
| st.session_state.confirming_delete_details = { | |
| "family": library_family_to_display, | |
| "use_case": use_case_name_display | |
| } | |
| st.rerun() | |
| else: | |
| st.info("Aucun métier n'est actuellement sélectionnée dans la bibliothèque ou le métier sélectionné n'existe plus.") | |
| available_families_check = list(st.session_state.editable_prompts.keys()) | |
| if not available_families_check : st.warning("La bibliothèque est entièrement vide. Veuillez créer des métiers et des prompts.") | |
| elif st.session_state.view_mode == "generator": | |
| generator_family = st.session_state.get('generator_selected_family') | |
| generator_use_case = st.session_state.get('generator_selected_use_case') | |
| # Back button | |
| if st.button(f"⬅️ Retour à la bibliothèque ({generator_family or 'Métier'})", key="back_to_library_from_generator"): | |
| if generator_family: | |
| st.session_state.library_selected_family_for_display = generator_family | |
| st.session_state.view_mode = "library" | |
| st.rerun() | |
| # Validation | |
| if not generator_family or not generator_use_case: | |
| st.info("Sélection de prompt invalide. Retournez à la bibliothèque pour choisir un prompt.") | |
| elif generator_family not in st.session_state.editable_prompts or generator_use_case not in st.session_state.editable_prompts[generator_family]: | |
| st.warning("Le prompt sélectionné n'existe plus. Retournez à la bibliothèque pour en choisir un autre.") | |
| else: | |
| # Main content | |
| current_prompt_config = st.session_state.editable_prompts[generator_family][generator_use_case] | |
| # Header section - simplified | |
| st.header(f"🚀 {generator_use_case}") | |
| st.write(f"**Métier:** {generator_family}") | |
| description = current_prompt_config.get("description", "").strip() | |
| if description: | |
| st.info(description) | |
| st.markdown("---") | |
| # Form section - completely rebuilt with simple layout | |
| st.subheader("📝 Configuration des Variables") | |
| variables_for_form = current_prompt_config.get("variables", []) | |
| if not variables_for_form: | |
| st.warning("Ce cas d'usage n'a pas de variables configurées.") | |
| else: | |
| with st.form(key=f"simple_gen_form_{generator_family}_{generator_use_case}"): | |
| form_values = {} | |
| # Simple vertical layout for all variables | |
| for var_info in variables_for_form: | |
| var_name = var_info.get("name", "") | |
| var_label = var_info.get("label", var_name) | |
| var_type = var_info.get("type", "text_input") | |
| var_default = var_info.get("default", "") | |
| widget_key = f"simple_{generator_family}_{generator_use_case}_{var_name}" | |
| if var_type == "text_input": | |
| form_values[var_name] = st.text_input(var_label, value=str(var_default), key=widget_key) | |
| elif var_type == "text_area": | |
| form_values[var_name] = st.text_area(var_label, value=str(var_default), key=widget_key) | |
| elif var_type == "selectbox": | |
| options = var_info.get("options", []) | |
| if options: | |
| default_idx = 0 | |
| if var_default in options: | |
| default_idx = options.index(var_default) | |
| form_values[var_name] = st.selectbox(var_label, options=options, index=default_idx, key=widget_key) | |
| elif var_type == "number_input": | |
| default_val = float(var_default) if var_default and str(var_default).replace('.','').isdigit() else 0.0 | |
| form_values[var_name] = st.number_input(var_label, value=default_val, key=widget_key) | |
| elif var_type == "date_input": | |
| from datetime import date | |
| default_date = var_default if isinstance(var_default, date) else date.today() | |
| form_values[var_name] = st.date_input(var_label, value=default_date, key=widget_key) | |
| # Generate button | |
| if st.form_submit_button("🚀 Générer le Prompt", use_container_width=True): | |
| try: | |
| template = current_prompt_config.get("template", "") | |
| generated_content = template | |
| # Simple variable replacement | |
| for var_name, var_value in form_values.items(): | |
| if var_value is not None: | |
| if isinstance(var_value, date): | |
| var_str = var_value.strftime("%d/%m/%Y") | |
| else: | |
| var_str = str(var_value) | |
| generated_content = generated_content.replace(f"{{{var_name}}}", var_str) | |
| # Store result | |
| st.session_state.active_generated_prompt = f"Sujet : {generator_use_case}\n\n{generated_content}" | |
| # Update usage count (in memory only - no save to prevent restart) | |
| current_prompt_config["usage_count"] = current_prompt_config.get("usage_count", 0) + 1 | |
| current_prompt_config["updated_at"] = datetime.now().isoformat() | |
| # Removed save_editable_prompts_to_local_and_hf() to prevent app restart | |
| st.success("✅ Prompt généré avec succès!") | |
| except Exception as e: | |
| st.error(f"Erreur lors de la génération: {e}") | |
| st.markdown("---") | |
| # Results section - simple code display with native copy button | |
| if st.session_state.get("active_generated_prompt"): | |
| st.subheader("📋 Prompt Généré") | |
| # Simple code block with native copy functionality | |
| st.code(st.session_state.active_generated_prompt, language=None) | |
| st.caption("💡 Utilisez l'icône de copie en haut à droite du bloc pour copier le prompt") | |
| st.markdown("---") | |
| # Configuration section - simplified | |
| if SHOW_CONFIG_SECTION: | |
| with st.expander("⚙️ Configuration Avancée"): | |
| st.subheader("Template") | |
| new_template = st.text_area( | |
| "Template du prompt:", | |
| value=current_prompt_config.get('template', ''), | |
| height=150, | |
| key=f"config_template_{generator_family}_{generator_use_case}" | |
| ) | |
| new_description = st.text_area( | |
| "Description:", | |
| value=current_prompt_config.get('description', ''), | |
| height=100, | |
| key=f"config_desc_{generator_family}_{generator_use_case}" | |
| ) | |
| if st.button("💾 Sauvegarder Configuration", key=f"save_config_{generator_family}_{generator_use_case}"): | |
| current_prompt_config['template'] = new_template | |
| current_prompt_config['description'] = new_description | |
| current_prompt_config["updated_at"] = datetime.now().isoformat() | |
| save_to_hf_only() | |
| st.success("Configuration sauvegardée!") | |
| st.markdown("---") | |
| # Simple variable display | |
| st.subheader("Variables disponibles") | |
| variables = current_prompt_config.get('variables', []) | |
| if variables: | |
| for var in variables: | |
| st.write(f"• **{{{var.get('name', 'N/A')}}}** - {var.get('label', 'N/A')} ({var.get('type', 'N/A')})") | |
| else: | |
| st.info("Aucune variable définie") | |
| st.markdown("---") | |
| # Simple tags section | |
| st.subheader("Tags") | |
| current_tags = ", ".join(current_prompt_config.get("tags", [])) | |
| new_tags = st.text_input( | |
| "Tags (séparés par virgules):", | |
| value=current_tags, | |
| key=f"config_tags_{generator_family}_{generator_use_case}" | |
| ) | |
| if st.button("💾 Sauvegarder Tags", key=f"save_tags_{generator_family}_{generator_use_case}"): | |
| tag_list = [tag.strip() for tag in new_tags.split(',') if tag.strip()] | |
| current_prompt_config["tags"] = sorted(list(set(tag_list))) | |
| current_prompt_config["updated_at"] = datetime.now().isoformat() | |
| save_to_hf_only() | |
| st.success("Tags sauvegardés!") | |
| elif st.session_state.view_mode == "inject_manual": | |
| if st.button("⬅️ Retour à l'accueil", key="back_to_accueil_from_inject"): | |
| st.session_state.view_mode = "accueil" | |
| st.rerun() | |
| st.header("💉 Injection Manuelle de Cas d'Usage JSON") | |
| st.markdown("""Collez ici un ou plusieurs cas d'usage au format JSON. Le JSON doit être un dictionnaire où chaque clé est le nom du nouveau cas d'usage, et la valeur est sa configuration.""") | |
| st.caption("Exemple de structure pour un cas d'usage :") | |
| json_example_string = """{ | |
| "Nom de Mon Nouveau Cas d'Usage": { | |
| "description": "Ce prompt vous aide à réaliser une tâche spécifique. N'oubliez pas d'ajouter le document nécessaire à votre conversation avec l'IA.", | |
| "template": "Ceci est le {variable_exemple} pour mon prompt.", | |
| "variables": [ | |
| { | |
| "name": "variable_exemple", | |
| "label": "Variable d'Exemple", | |
| "type": "text_input", | |
| "default": "texte par défaut" | |
| } | |
| ], | |
| "tags": ["nouveau", "exemple"] | |
| } | |
| }""" | |
| st.code(json_example_string, language="json") | |
| available_families_for_injection = list(st.session_state.editable_prompts.keys()) | |
| if not available_families_for_injection: | |
| st.warning("Aucun métier n'existe. Veuillez d'abord créer un métier via l'onglet 'Édition'.") | |
| else: | |
| selected_family_for_injection = st.selectbox("Choisissez le métier de destination pour l'injection :", options=[""] + available_families_for_injection, index=0, key="injection_family_selector") | |
| st.session_state.injection_selected_family = selected_family_for_injection if selected_family_for_injection else None | |
| if st.session_state.injection_selected_family: | |
| st.subheader(f"Injecter dans le métier : {st.session_state.injection_selected_family}") | |
| st.session_state.injection_json_text = st.text_area("Collez le JSON des cas d'usage ici :", value=st.session_state.get("injection_json_text", ""), height=300, key="injection_json_input") | |
| if st.button("➕ Injecter les Cas d'Usage", key="submit_injection_btn"): | |
| if not st.session_state.injection_json_text.strip(): | |
| st.error("La zone de texte JSON est vide.") | |
| else: | |
| try: | |
| injected_data = json.loads(st.session_state.injection_json_text) | |
| if not isinstance(injected_data, dict): | |
| st.error("Le JSON fourni doit être un dictionnaire (objet JSON).") | |
| else: | |
| target_family_name = st.session_state.injection_selected_family | |
| if target_family_name not in st.session_state.editable_prompts: | |
| st.error(f"Le métier de destination '{target_family_name}' n'existe plus ou n'a pas été correctement sélectionnée.") | |
| else: | |
| family_prompts = st.session_state.editable_prompts[target_family_name] | |
| successful_injections = [] | |
| failed_injections = [] | |
| first_new_uc_name = None | |
| for uc_name, uc_config_json in injected_data.items(): | |
| uc_name_stripped = uc_name.strip() | |
| if not uc_name_stripped: | |
| failed_injections.append(f"Nom de cas d'usage vide ignoré.") | |
| continue | |
| if not isinstance(uc_config_json, dict) or "template" not in uc_config_json: | |
| failed_injections.append(f"'{uc_name_stripped}': Configuration invalide ou template manquant.") | |
| continue | |
| if uc_name_stripped in family_prompts: | |
| st.warning(f"Le cas d'usage '{uc_name_stripped}' existe déjà dans le métier '{target_family_name}'. Il a été ignoré.") | |
| failed_injections.append(f"'{uc_name_stripped}': Existe déjà, ignoré.") | |
| continue | |
| prepared_uc_config = _prepare_newly_injected_use_case_config(uc_config_json) | |
| if not prepared_uc_config.get("template"): | |
| failed_injections.append(f"'{uc_name_stripped}': Template invalide après traitement.") | |
| continue | |
| family_prompts[uc_name_stripped] = prepared_uc_config | |
| successful_injections.append(uc_name_stripped) | |
| if first_new_uc_name is None: | |
| first_new_uc_name = uc_name_stripped | |
| if successful_injections: | |
| save_editable_prompts_to_local_and_hf() | |
| st.success(f"{len(successful_injections)} cas d'usage injectés avec succès dans '{target_family_name}': {', '.join(successful_injections)}") | |
| st.session_state.injection_json_text = "" | |
| if first_new_uc_name: | |
| st.session_state.view_mode = "generator" | |
| st.session_state.force_select_family_name = target_family_name | |
| st.session_state.force_select_use_case_name = first_new_uc_name | |
| st.session_state.go_to_config_section = True | |
| st.session_state.active_generated_prompt = "" # <--- AJOUTEZ CETTE LIGNE ICI | |
| st.rerun() | |
| if failed_injections: | |
| for fail_msg in failed_injections: | |
| st.error(f"Échec d'injection : {fail_msg}") | |
| if not successful_injections and not failed_injections: | |
| st.info("Aucun cas d'usage n'a été trouvé dans le JSON fourni ou tous étaient vides/invalides.") | |
| except json.JSONDecodeError as e: | |
| st.error(f"Erreur de parsing JSON : {e}") | |
| except Exception as e: | |
| st.error(f"Une erreur inattendue est survenue lors de l'injection : {e}") # pragma: no cover | |
| else: | |
| st.info("Veuillez sélectionner un métier de destination pour commencer l'injection.") | |
| elif st.session_state.view_mode == "assistant_creation": # Cette vue gère maintenant les deux modes | |
| if st.button("⬅️ Retour à l'accueil", key="back_to_accueil_from_assistant_unified"): | |
| st.session_state.view_mode = "accueil" | |
| # Nettoyer les variables de l'assistant | |
| st.session_state.assistant_api_processing = False | |
| st.session_state.assistant_generated_json = None | |
| st.session_state.assistant_selected_family = None | |
| st.session_state.generated_meta_prompt_for_llm = "" | |
| st.rerun() | |
| st.header("✨ Assistant Prompt Système") | |
| # S'assurer que assistant_mode a une valeur initiale valide si elle n'est pas déjà définie | |
| if 'assistant_mode' not in st.session_state: | |
| st.session_state.assistant_mode = "creation" | |
| mode_options_labels = { | |
| "creation": "🆕 Créer un nouveau prompt système", | |
| "amelioration": "🚀 Améliorer un prompt existant" | |
| } | |
| # Utiliser l'index pour que st.radio se souvienne de la sélection via st.session_state.assistant_mode | |
| current_mode_index = 0 if st.session_state.assistant_mode == "creation" else 1 | |
| selected_mode_key = st.radio( | |
| "Que souhaitez-vous faire ?", | |
| options=list(mode_options_labels.keys()), | |
| format_func=lambda key: mode_options_labels[key], | |
| index=current_mode_index, | |
| key="assistant_mode_radio_selector" # Clé unique pour le widget radio | |
| ) | |
| # Si le mode sélectionné via le radio a changé, mettre à jour st.session_state et rerun pour rafraîchir le formulaire | |
| if selected_mode_key != st.session_state.assistant_mode: | |
| st.session_state.assistant_mode = selected_mode_key | |
| st.session_state.generated_meta_prompt_for_llm = "" # Vider le prompt généré car le mode a changé | |
| # Nettoyer les variables de traitement automatique | |
| st.session_state.assistant_api_processing = False | |
| st.session_state.assistant_generated_json = None | |
| st.session_state.assistant_selected_family = None | |
| # Optionnel: vider les valeurs des formulaires lors du changement de mode pour éviter confusion | |
| # st.session_state.assistant_form_values = {var['name']: var['default'] for var in ASSISTANT_FORM_VARIABLES} | |
| # st.session_state.assistant_existing_prompt_value = "" | |
| st.rerun() | |
| if st.session_state.assistant_mode == "creation": | |
| st.markdown("Décrivez votre besoin pour créer automatiquement un cas d'usage. Choisissez **'Générer automatiquement'** pour une création complète via ChatGPT, ou **'Générer l'instruction (manuel)'** pour obtenir les instructions à coller dans votre LLM.") | |
| with st.form(key="assistant_creation_form_std"): | |
| # Sélection de la famille de métier | |
| available_families = list(st.session_state.editable_prompts.keys()) | |
| if not available_families: | |
| st.error("Aucune famille de métier disponible. Créez-en une d'abord dans l'onglet 'Édition'.") | |
| st.stop() | |
| # Déterminer l'index par défaut pour la famille | |
| default_family_index = 0 | |
| if st.session_state.assistant_selected_family and st.session_state.assistant_selected_family in available_families: | |
| default_family_index = available_families.index(st.session_state.assistant_selected_family) | |
| selected_family = st.selectbox( | |
| "🏢 Sélectionnez la famille de métier où ajouter le cas d'usage :", | |
| options=available_families, | |
| index=default_family_index, | |
| key="assistant_family_selector", | |
| help="Le nouveau cas d'usage sera ajouté à cette famille de métier" | |
| ) | |
| st.markdown("---") | |
| # Initialiser current_form_input_values avec les valeurs de session_state ou les valeurs par défaut | |
| # pour que les champs du formulaire soient pré-remplis correctement. | |
| temp_form_values = {} | |
| for var_info in ASSISTANT_FORM_VARIABLES: | |
| field_key = f"assistant_form_{var_info['name']}" | |
| # Utilise la valeur de session_state pour ce champ ou la valeur par défaut si non trouvée | |
| value_for_widget = st.session_state.assistant_form_values.get(var_info['name'], var_info['default']) | |
| if var_info["type"] == "text_input": | |
| temp_form_values[var_info["name"]] = st.text_input( | |
| var_info["label"], value=value_for_widget, key=field_key | |
| ) | |
| elif var_info["type"] == "text_area": | |
| temp_form_values[var_info["name"]] = st.text_area( | |
| var_info["label"], value=value_for_widget, height=var_info.get("height", 100), key=field_key | |
| ) | |
| elif var_info["type"] == "number_input": # Assurez-vous que ce cas est géré si vous l'avez | |
| try: | |
| num_value_for_widget = float(value_for_widget if value_for_widget else var_info["default"]) | |
| except (ValueError, TypeError): | |
| num_value_for_widget = float(var_info["default"]) | |
| temp_form_values[var_info["name"]] = st.number_input( | |
| var_info["label"], | |
| value=num_value_for_widget, | |
| min_value=float(var_info.get("min_value")) if var_info.get("min_value") is not None else None, | |
| max_value=float(var_info.get("max_value")) if var_info.get("max_value") is not None else None, | |
| step=float(var_info.get("step", 1.0)), | |
| key=field_key, | |
| format="%g" # ou un autre format si nécessaire | |
| ) | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| submitted_assistant_form_auto = st.form_submit_button("🪄 Générer automatiquement", use_container_width=True, type="primary") | |
| with col2: | |
| submitted_assistant_form_manual = st.form_submit_button("📝 Générer l'instruction (manuel)", use_container_width=True) | |
| if submitted_assistant_form_auto or submitted_assistant_form_manual: | |
| st.session_state.assistant_form_values = temp_form_values.copy() # Sauvegarde les valeurs actuelles du formulaire | |
| st.session_state.assistant_selected_family = selected_family # Sauvegarde la famille sélectionnée | |
| try: | |
| # Vérifier si tous les champs requis pour ce template sont remplis (si nécessaire) | |
| populated_meta_prompt = META_PROMPT_FOR_EXTERNAL_LLM_TEMPLATE.format(**st.session_state.assistant_form_values) | |
| st.session_state.generated_meta_prompt_for_llm = populated_meta_prompt | |
| if submitted_assistant_form_auto: | |
| # Automatique: Appeler l'API OpenAI directement | |
| st.session_state.assistant_api_processing = True | |
| st.session_state.assistant_generated_json = None | |
| st.success("🪄 Génération automatique en cours...") | |
| st.rerun() | |
| else: | |
| # Manuel: Afficher l'instruction comme avant | |
| st.success("📝 Instruction de création générée !") | |
| except KeyError as e: | |
| st.error(f"Erreur lors de la construction de l'instruction. Clé de formatage manquante : {e}.") | |
| st.session_state.generated_meta_prompt_for_llm = "" | |
| except Exception as e: | |
| st.error(f"Une erreur inattendue est survenue : {e}") | |
| st.session_state.generated_meta_prompt_for_llm = "" | |
| elif st.session_state.assistant_mode == "amelioration": | |
| st.markdown("Collez votre prompt existant. L'assistant générera une instruction pour votre LLM afin de transformer votre prompt en un cas d'usage structuré et améliorable pour cette application.") | |
| with st.form(key="assistant_amelioration_form_unified"): | |
| # Utilise la valeur de session_state pour ce champ | |
| prompt_existant_input_val = st.text_area( | |
| "Collez votre prompt existant ici :", | |
| value=st.session_state.assistant_existing_prompt_value, | |
| height=300, | |
| key="assistant_form_prompt_existant_unified" | |
| ) | |
| submitted_assistant_amelioration_form = st.form_submit_button("📝 Générer l'instruction d'amélioration") | |
| if submitted_assistant_amelioration_form: | |
| st.session_state.assistant_existing_prompt_value = prompt_existant_input_val # Sauvegarde la valeur soumise | |
| if not prompt_existant_input_val.strip(): | |
| st.error("Veuillez coller un prompt existant dans la zone de texte.") | |
| st.session_state.generated_meta_prompt_for_llm = "" | |
| else: | |
| try: | |
| populated_meta_prompt_amelioration = META_PROMPT_FOR_LLM_AMELIORATION_TEMPLATE.format( | |
| prompt_existant=prompt_existant_input_val # Utiliser la valeur actuelle du champ | |
| ) | |
| st.session_state.generated_meta_prompt_for_llm = populated_meta_prompt_amelioration | |
| st.success("Instruction d'amélioration générée !") | |
| except KeyError as e: | |
| st.error(f"Erreur lors de la construction de l'instruction. Clé de formatage manquante : {e}.") | |
| st.session_state.generated_meta_prompt_for_llm = "" | |
| except Exception as e: | |
| st.error(f"Une erreur inattendue est survenue : {e}") | |
| st.session_state.generated_meta_prompt_for_llm = "" | |
| # --- Traitement automatique via API OpenAI --- | |
| if st.session_state.assistant_api_processing and st.session_state.generated_meta_prompt_for_llm: | |
| # MODE DEBUG : Afficher le prompt exact envoyé à l'API | |
| with st.expander("🔍 DEBUG : Prompt envoyé à ChatGPT", expanded=False): | |
| st.write("**Variables du formulaire:**") | |
| st.json(st.session_state.assistant_form_values) | |
| st.write("**Prompt formaté envoyé à l'API:**") | |
| st.code(st.session_state.generated_meta_prompt_for_llm, language='markdown') | |
| with st.spinner("🪄 Génération automatique en cours via ChatGPT..."): | |
| api_response = call_openai_api(st.session_state.generated_meta_prompt_for_llm) | |
| if api_response: | |
| extracted_json = extract_json_from_response(api_response) | |
| if extracted_json: | |
| # Injection automatique directe | |
| if auto_inject_json_and_redirect(extracted_json, st.session_state.assistant_selected_family): | |
| # Succès: la fonction gère la redirection | |
| st.rerun() | |
| else: | |
| # Échec de l'injection: afficher le JSON pour intervention manuelle | |
| st.session_state.assistant_generated_json = extracted_json | |
| st.session_state.assistant_api_processing = False | |
| st.error("❌ Erreur lors de l'injection automatique. Vous pouvez injecter manuellement ci-dessous.") | |
| else: | |
| st.session_state.assistant_api_processing = False | |
| st.error("❌ Erreur: Impossible d'extraire le JSON de la réponse. Essayez le mode manuel.") | |
| else: | |
| st.session_state.assistant_api_processing = False | |
| st.error("❌ Erreur lors de l'appel à l'API. Essayez le mode manuel.") | |
| # --- Affichage du JSON généré automatiquement --- | |
| if st.session_state.assistant_generated_json: | |
| st.subheader("🎉 JSON généré automatiquement :") | |
| st.json(st.session_state.assistant_generated_json) | |
| # Bouton pour injecter directement | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| if st.button("💉 Injecter ce JSON", key="inject_auto_json_btn", use_container_width=True, type="primary"): | |
| st.session_state.view_mode = "inject_manual" | |
| st.session_state.injection_selected_family = None | |
| st.session_state.injection_json_text = json.dumps(st.session_state.assistant_generated_json, indent=2, ensure_ascii=False) | |
| st.toast("JSON automatiquement collé dans l'injecteur !", icon="🎉") | |
| st.rerun() | |
| with col2: | |
| if st.button("🔄 Générer à nouveau", key="regenerate_auto_json_btn", use_container_width=True): | |
| st.session_state.assistant_api_processing = True | |
| st.session_state.assistant_generated_json = None | |
| st.rerun() | |
| st.markdown("---") | |
| # Affichage commun du méta-prompt généré (qu'il vienne de la création ou de l'amélioration) | |
| # Seulement si pas de JSON automatique généré | |
| if st.session_state.generated_meta_prompt_for_llm and not st.session_state.assistant_generated_json: | |
| st.subheader("📋 Instruction Générée (à coller dans votre LLM) :") | |
| st.code(st.session_state.generated_meta_prompt_for_llm, language='markdown', line_numbers=True) | |
| st.caption("<span style='color:gray; font-size:0.9em;'>Utilisez l'icône en haut à droite du bloc de code pour copier l'instruction.</span>", unsafe_allow_html=True) | |
| st.markdown("---") | |
| st.info("Une fois que votre LLM externe a généré le JSON basé sur cette instruction, copiez ce JSON et utilisez le bouton \"💉 Injecter JSON Manuellement\" (disponible aussi dans l'onglet Assistant du menu) pour l'ajouter à votre atelier.") | |
| if st.button("💉 Injecter JSON Manuellement", key="prepare_inject_from_assistant_unified_btn", use_container_width=True, type="primary"): | |
| st.session_state.view_mode = "inject_manual" | |
| st.session_state.injection_selected_family = None | |
| st.session_state.injection_json_text = "" | |
| st.toast("Collez le JSON généré par le LLM et sélectionnez un métier de destination.", icon="💡") | |
| st.rerun() | |
| if not any(st.session_state.editable_prompts.values()): # pragma: no cover | |
| st.warning("Aucun groupement de cas d'usage métier n'est configurée. Veuillez en créer une via l'onglet 'Édition' ou vérifier votre Gist.") | |
| elif st.session_state.view_mode not in ["library", "generator", "inject_manual", "assistant_creation"]: # pragma: no cover | |
| st.session_state.view_mode = "library" if list(st.session_state.editable_prompts.keys()) else "generator" | |
| st.rerun() | |
| # --- Sidebar Footer --- | |
| st.sidebar.markdown("---") | |
| st.sidebar.info(f"Générateur v3.3.6 - © {CURRENT_YEAR} AIBuilders (démo)") |