feat: Création de la branche 'coolo' à partir de main pour PR.
Browse files- a6ea61c8-951a-413a-ba9d-7365d83fbd4d/gitforge/coolo/README.md +5 -0
- a6ea61c8-951a-413a-ba9d-7365d83fbd4d/gitforge/coolo/data_processing.py +366 -0
- a6ea61c8-951a-413a-ba9d-7365d83fbd4d/gitforge/coolo/main.py +1261 -0
- a6ea61c8-951a-413a-ba9d-7365d83fbd4d/gitforge/coolo/report_excel_exporter.py +121 -0
- a6ea61c8-951a-413a-ba9d-7365d83fbd4d/gitforge/coolo/report_generator.py +461 -0
- a6ea61c8-951a-413a-ba9d-7365d83fbd4d/gitforge/coolo/report_pdf_exporter.py +203 -0
- a6ea61c8-951a-413a-ba9d-7365d83fbd4d/gitforge/coolo/translations.py +142 -0
- a6ea61c8-951a-413a-ba9d-7365d83fbd4d/gitforge/coolo/translations_ai_report.py +68 -0
- a6ea61c8-951a-413a-ba9d-7365d83fbd4d/gitforge/coolo/translations_base.py +222 -0
- a6ea61c8-951a-413a-ba9d-7365d83fbd4d/gitforge/coolo/translations_data_processing.py +73 -0
- a6ea61c8-951a-413a-ba9d-7365d83fbd4d/gitforge/coolo/translations_report_content.py +85 -0
a6ea61c8-951a-413a-ba9d-7365d83fbd4d/gitforge/coolo/README.md
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Dépôt gitforge
|
| 2 |
+
|
| 3 |
+
Bienvenue sur votre dépôt GitForge, hébergé sur Mailix.
|
| 4 |
+
|
| 5 |
+
Commencez par ajouter ou créer des fichiers.
|
a6ea61c8-951a-413a-ba9d-7365d83fbd4d/gitforge/coolo/data_processing.py
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
+
import streamlit as st
|
| 4 |
+
import io
|
| 5 |
+
import json
|
| 6 |
+
import hashlib
|
| 7 |
+
import os
|
| 8 |
+
import matplotlib.pyplot as plt
|
| 9 |
+
import seaborn as sns
|
| 10 |
+
import tempfile
|
| 11 |
+
from sklearn.preprocessing import LabelEncoder, StandardScaler, MinMaxScaler
|
| 12 |
+
from sklearn.impute import KNNImputer
|
| 13 |
+
from collections import Counter
|
| 14 |
+
from wordcloud import WordCloud
|
| 15 |
+
import spacy
|
| 16 |
+
import matplotlib.colors as mcolors
|
| 17 |
+
import plotly.express as px
|
| 18 |
+
from sklearn.cluster import KMeans
|
| 19 |
+
from sklearn.ensemble import IsolationForest
|
| 20 |
+
|
| 21 |
+
from translations import txt, set_language, slugify
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _get_themes_file_path():
|
| 25 |
+
"""
|
| 26 |
+
Retourne le chemin du fichier JSON pour les thèmes.
|
| 27 |
+
"""
|
| 28 |
+
# Utilise un répertoire temporaire ou le répertoire de l'application Streamlit
|
| 29 |
+
return os.path.join(tempfile.gettempdir(), 'app_themes.json')
|
| 30 |
+
|
| 31 |
+
def save_theme_preferences(theme_name, theme_data):
|
| 32 |
+
"""
|
| 33 |
+
Sauvegarde un thème nommé dans un fichier JSON.
|
| 34 |
+
"""
|
| 35 |
+
themes_path = _get_themes_file_path()
|
| 36 |
+
try:
|
| 37 |
+
if os.path.exists(themes_path):
|
| 38 |
+
with open(themes_path, 'r', encoding='utf-8') as f:
|
| 39 |
+
saved_themes = json.load(f)
|
| 40 |
+
else:
|
| 41 |
+
saved_themes = {}
|
| 42 |
+
|
| 43 |
+
saved_themes[theme_name] = theme_data
|
| 44 |
+
|
| 45 |
+
with open(themes_path, 'w', encoding='utf-8') as f:
|
| 46 |
+
json.dump(saved_themes, f, ensure_ascii=False, indent=4)
|
| 47 |
+
|
| 48 |
+
return True, txt("theme_saved_success")
|
| 49 |
+
except Exception as e:
|
| 50 |
+
return False, f"{txt('error_saving_theme')} : {e}"
|
| 51 |
+
|
| 52 |
+
def get_saved_themes():
|
| 53 |
+
"""
|
| 54 |
+
Récupère les thèmes sauvegardés depuis le fichier JSON.
|
| 55 |
+
"""
|
| 56 |
+
themes_path = _get_themes_file_path()
|
| 57 |
+
try:
|
| 58 |
+
if os.path.exists(themes_path):
|
| 59 |
+
with open(themes_path, 'r', encoding='utf-8') as f:
|
| 60 |
+
return json.load(f)
|
| 61 |
+
return {}
|
| 62 |
+
except Exception:
|
| 63 |
+
return {}
|
| 64 |
+
|
| 65 |
+
def delete_theme_preferences(theme_name):
|
| 66 |
+
"""
|
| 67 |
+
Supprime un thème nommé du fichier JSON.
|
| 68 |
+
"""
|
| 69 |
+
themes_path = _get_themes_file_path()
|
| 70 |
+
try:
|
| 71 |
+
if os.path.exists(themes_path):
|
| 72 |
+
with open(themes_path, 'r', encoding='utf-8') as f:
|
| 73 |
+
saved_themes = json.load(f)
|
| 74 |
+
|
| 75 |
+
if theme_name in saved_themes:
|
| 76 |
+
del saved_themes[theme_name]
|
| 77 |
+
with open(themes_path, 'w', encoding='utf-8') as f:
|
| 78 |
+
json.dump(saved_themes, f, ensure_ascii=False, indent=4)
|
| 79 |
+
return True, txt("theme_deleted_success")
|
| 80 |
+
return False, txt("theme_not_found")
|
| 81 |
+
except Exception as e:
|
| 82 |
+
return False, f"{txt('error_deleting_theme')} : {e}"
|
| 83 |
+
|
| 84 |
+
def update_theme(theme_data):
|
| 85 |
+
"""
|
| 86 |
+
Applique le thème sélectionné en mettant à jour le fichier de configuration de Streamlit.
|
| 87 |
+
"""
|
| 88 |
+
st.session_state['theme'] = theme_data
|
| 89 |
+
# Note: Streamlit doit être relancé pour que le thème s'applique complètement
|
| 90 |
+
st.rerun()
|
| 91 |
+
|
| 92 |
+
def read_data_file(file_path, delimiter=','):
|
| 93 |
+
"""
|
| 94 |
+
Reads a file from a given path and returns a pandas DataFrame.
|
| 95 |
+
Supports CSV, TXT, JSON, and Excel formats.
|
| 96 |
+
"""
|
| 97 |
+
try:
|
| 98 |
+
file_extension = os.path.splitext(file_path)[1].lower()
|
| 99 |
+
if file_extension in ['.csv', '.txt']:
|
| 100 |
+
# Essayer différentes encodages si le premier échoue
|
| 101 |
+
try:
|
| 102 |
+
df = pd.read_csv(file_path, delimiter=delimiter, encoding='utf-8')
|
| 103 |
+
except UnicodeDecodeError:
|
| 104 |
+
df = pd.read_csv(file_path, delimiter=delimiter, encoding='latin1')
|
| 105 |
+
elif file_extension == '.json':
|
| 106 |
+
df = pd.read_json(file_path)
|
| 107 |
+
elif file_extension in ['.xls', '.xlsx']:
|
| 108 |
+
df = pd.read_excel(file_path)
|
| 109 |
+
elif file_extension == '.parquet': # Ajout de support pour Parquet
|
| 110 |
+
df = pd.read_parquet(file_path)
|
| 111 |
+
elif file_extension == '.orc': # Ajout de support pour ORC
|
| 112 |
+
df = pd.read_orc(file_path)
|
| 113 |
+
elif file_extension == '.feather': # Ajout de support pour Feather
|
| 114 |
+
df = pd.read_feather(file_path)
|
| 115 |
+
elif file_extension == '.dta': # Ajout de support pour Stata
|
| 116 |
+
df = pd.read_stata(file_path)
|
| 117 |
+
elif file_extension == '.sas7bdat': # Ajout de support pour SAS
|
| 118 |
+
df = pd.read_sas(file_path)
|
| 119 |
+
else:
|
| 120 |
+
return None, txt("unsupported_file_type")
|
| 121 |
+
return df, txt("file_read_success")
|
| 122 |
+
except Exception as e:
|
| 123 |
+
return None, f"{txt('error_reading_file')} : {e}"
|
| 124 |
+
|
| 125 |
+
def get_data_overview(df):
|
| 126 |
+
"""
|
| 127 |
+
Aperçu général du DataFrame.
|
| 128 |
+
"""
|
| 129 |
+
return {
|
| 130 |
+
"rows": df.shape[0],
|
| 131 |
+
"cols": df.shape[1],
|
| 132 |
+
"column_types": df.dtypes.to_dict()
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
def get_missing_values_summary(df):
|
| 136 |
+
"""
|
| 137 |
+
Résumé des valeurs manquantes.
|
| 138 |
+
"""
|
| 139 |
+
missing_data = df.isnull().sum()
|
| 140 |
+
missing_data = missing_data[missing_data > 0].sort_values(ascending=False)
|
| 141 |
+
missing_percent = (missing_data / len(df)) * 100
|
| 142 |
+
missing_summary = pd.DataFrame({'Total': missing_data, 'Pourcentage': missing_percent})
|
| 143 |
+
return missing_summary
|
| 144 |
+
|
| 145 |
+
def generate_multicolor_plots(df):
|
| 146 |
+
"""
|
| 147 |
+
Génère 6 visualisations multicolores pour l'analyse des données.
|
| 148 |
+
"""
|
| 149 |
+
st.subheader(txt("auto_generated_visualizations_title"))
|
| 150 |
+
|
| 151 |
+
numeric_cols = df.select_dtypes(include=np.number).columns.tolist()
|
| 152 |
+
categorical_cols = df.select_dtypes(include=['object', 'category']).columns.tolist()
|
| 153 |
+
|
| 154 |
+
# Définir une palette de couleurs dynamique
|
| 155 |
+
colors = px.colors.qualitative.Plotly # Utiliser une palette Plotly
|
| 156 |
+
|
| 157 |
+
# 1. Histogramme de distribution pour une colonne numérique clé (ex: Prix ou première numérique)
|
| 158 |
+
if numeric_cols:
|
| 159 |
+
col = 'Prix' if 'Prix' in numeric_cols else numeric_cols[0]
|
| 160 |
+
fig = px.histogram(df, x=col, title=txt("dist_of").format(col=col), color_discrete_sequence=[colors[0]])
|
| 161 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 162 |
+
|
| 163 |
+
# 2. Bar plot pour la fréquence d'une colonne catégorielle clé (ex: Type_Propriete ou première catégorielle)
|
| 164 |
+
if categorical_cols:
|
| 165 |
+
col = 'Type_Propriete' if 'Type_Propriete' in categorical_cols else categorical_cols[0]
|
| 166 |
+
if not df[col].empty:
|
| 167 |
+
value_counts_df = df[col].value_counts().reset_index(name='count')
|
| 168 |
+
fig = px.bar(value_counts_df, x=value_counts_df.columns[0], y='count', title=txt("freq_of").format(col=col),
|
| 169 |
+
color='count', color_continuous_scale=px.colors.sequential.Viridis)
|
| 170 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 171 |
+
|
| 172 |
+
# 3. Scatter plot entre deux colonnes numériques (ex: Surface_m2 vs Prix)
|
| 173 |
+
if 'Surface_m2' in numeric_cols and 'Prix' in numeric_cols:
|
| 174 |
+
fig = px.scatter(df, x='Surface_m2', y='Prix', title=txt("scatter_surface_price"),
|
| 175 |
+
color='Type_Propriete' if 'Type_Propriete' in categorical_cols else None,
|
| 176 |
+
color_discrete_sequence=colors)
|
| 177 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 178 |
+
elif len(numeric_cols) >= 2:
|
| 179 |
+
fig = px.scatter(df, x=numeric_cols[0], y=numeric_cols[1], title=txt("scatter_generic").format(col1=numeric_cols[0], col2=numeric_cols[1]),
|
| 180 |
+
color=df.columns[0] if df.columns[0] in categorical_cols else None, # Utilise une colonne catégorielle pour la couleur si disponible
|
| 181 |
+
color_discrete_sequence=colors)
|
| 182 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 183 |
+
|
| 184 |
+
# 4. Box plot pour une colonne numérique par catégorie (ex: Prix par Localisation)
|
| 185 |
+
if 'Prix' in numeric_cols and 'Localisation' in categorical_cols:
|
| 186 |
+
fig = px.box(df, x='Localisation', y='Prix', title=txt("box_price_by_location"), color_discrete_sequence=colors)
|
| 187 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 188 |
+
elif numeric_cols and categorical_cols:
|
| 189 |
+
fig = px.box(df, x=categorical_cols[0], y=numeric_cols[0], title=txt("box_generic").format(num_col=numeric_cols[0], cat_col=categorical_cols[0]), color_discrete_sequence=colors)
|
| 190 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 191 |
+
|
| 192 |
+
# 5. Matrice de corrélation
|
| 193 |
+
num_df_for_corr = df.select_dtypes(include=np.number)
|
| 194 |
+
if num_df_for_corr.shape[1] > 1:
|
| 195 |
+
corr_matrix = num_df_for_corr.corr()
|
| 196 |
+
fig = px.imshow(corr_matrix, text_auto=True, aspect="auto",
|
| 197 |
+
color_continuous_scale=px.colors.sequential.RdBu,
|
| 198 |
+
title=txt("correlation_matrix_title"))
|
| 199 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 200 |
+
|
| 201 |
+
# 6. Sunburst chart pour la hiérarchie catégorielle ou simple pie chart
|
| 202 |
+
if len(categorical_cols) >= 2:
|
| 203 |
+
# Créer une hiérarchie fictive pour l'exemple si possible
|
| 204 |
+
path = [categorical_cols[0], categorical_cols[1]]
|
| 205 |
+
fig = px.sunburst(df, path=path, title=txt("sunburst_hierarchical"),
|
| 206 |
+
color_discrete_sequence=colors)
|
| 207 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 208 |
+
elif categorical_cols:
|
| 209 |
+
col = categorical_cols[0]
|
| 210 |
+
fig = px.pie(df, names=col, title=txt("pie_chart_of").format(col=col),
|
| 211 |
+
color_discrete_sequence=colors)
|
| 212 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def generate_data_quality_visualizations(df):
|
| 216 |
+
"""
|
| 217 |
+
Génère des visualisations pour l'analyse de la qualité des données.
|
| 218 |
+
Cette fonction est désormais un wrapper pour generate_multicolor_plots et wordcloud.
|
| 219 |
+
"""
|
| 220 |
+
generate_multicolor_plots(df) # Appelle la nouvelle fonction pour les 6 graphiques
|
| 221 |
+
|
| 222 |
+
st.subheader(txt("word_cloud_title"))
|
| 223 |
+
text_cols = df.select_dtypes(include=['object']).columns
|
| 224 |
+
if len(text_cols) > 0:
|
| 225 |
+
st.info(txt("word_cloud_info"))
|
| 226 |
+
selected_text_col = st.selectbox(txt("select_text_column"), text_cols)
|
| 227 |
+
text = " ".join(review for review in df[selected_text_col].astype(str).dropna())
|
| 228 |
+
if text:
|
| 229 |
+
wordcloud = WordCloud(
|
| 230 |
+
width=800,
|
| 231 |
+
height=400,
|
| 232 |
+
background_color='white'
|
| 233 |
+
).generate(text)
|
| 234 |
+
|
| 235 |
+
fig, ax = plt.subplots()
|
| 236 |
+
ax.imshow(wordcloud, interpolation='bilinear')
|
| 237 |
+
ax.axis('off')
|
| 238 |
+
st.pyplot(fig)
|
| 239 |
+
else:
|
| 240 |
+
st.warning(txt("no_text_data_for_wordcloud"))
|
| 241 |
+
else:
|
| 242 |
+
st.write(txt("no_text_columns"))
|
| 243 |
+
|
| 244 |
+
def generate_ai_report_visualizations(df, shap_values_data, X_test_data):
|
| 245 |
+
"""
|
| 246 |
+
Generates SHAP visualizations for the AI report section.
|
| 247 |
+
"""
|
| 248 |
+
if shap_values_data is not None and X_test_data is not None:
|
| 249 |
+
try:
|
| 250 |
+
st.markdown("### Importance des Caractéristiques (SHAP)")
|
| 251 |
+
st.info("Les valeurs SHAP sont calculées pour expliquer l'impact de chaque caractéristique sur la prédiction du modèle. Un graphique récapitulatif est généré pour montrer l'importance globale et la direction de l'impact.")
|
| 252 |
+
|
| 253 |
+
# Convert SHAP values and X_test_data to the correct format for the plot
|
| 254 |
+
shap_values = shap_values_data
|
| 255 |
+
# Assurez-vous d'avoir les noms de colonnes réels si possible, sinon utilisez des génériques
|
| 256 |
+
if isinstance(X_test_data, pd.DataFrame):
|
| 257 |
+
X_test_display = X_test_data
|
| 258 |
+
else:
|
| 259 |
+
X_test_display = pd.DataFrame(X_test_data, columns=[f'col_{i}' for i in range(X_test_data.shape[1])])
|
| 260 |
+
|
| 261 |
+
# SHAP Summary Plot
|
| 262 |
+
fig, ax = plt.subplots()
|
| 263 |
+
shap.summary_plot(shap_values, X_test_display, show=False)
|
| 264 |
+
st.pyplot(fig)
|
| 265 |
+
except Exception as e:
|
| 266 |
+
st.error(f"Erreur lors de la génération du graphique SHAP : {e}")
|
| 267 |
+
|
| 268 |
+
def get_theme_preferences(theme_name):
|
| 269 |
+
"""
|
| 270 |
+
Récupère un thème spécifique.
|
| 271 |
+
"""
|
| 272 |
+
themes_path = _get_themes_file_path()
|
| 273 |
+
try:
|
| 274 |
+
if os.path.exists(themes_path):
|
| 275 |
+
with open(themes_path, 'r', encoding='utf-8') as f:
|
| 276 |
+
saved_themes = json.load(f)
|
| 277 |
+
return saved_themes.get(theme_name, {})
|
| 278 |
+
return {}
|
| 279 |
+
except Exception:
|
| 280 |
+
return {}
|
| 281 |
+
|
| 282 |
+
def impute_missing_values(df, method="mean"):
|
| 283 |
+
"""
|
| 284 |
+
Impute les valeurs manquantes.
|
| 285 |
+
"""
|
| 286 |
+
df_copy = df.copy()
|
| 287 |
+
num_cols = df_copy.select_dtypes(include=np.number).columns
|
| 288 |
+
if method == "mean":
|
| 289 |
+
df_copy[num_cols] = df_copy[num_cols].fillna(df_copy[num_cols].mean())
|
| 290 |
+
elif method == "median":
|
| 291 |
+
df_copy[num_cols] = df_copy[num_cols].fillna(df_copy[num_cols].median())
|
| 292 |
+
elif method == "knn":
|
| 293 |
+
imputer = KNNImputer(n_neighbors=5)
|
| 294 |
+
df_copy[num_cols] = imputer.fit_transform(df_copy[num_cols])
|
| 295 |
+
return df_copy
|
| 296 |
+
|
| 297 |
+
def scale_features(df, method="standard"):
|
| 298 |
+
"""
|
| 299 |
+
Met à l'échelle les caractéristiques numériques.
|
| 300 |
+
"""
|
| 301 |
+
df_copy = df.copy()
|
| 302 |
+
num_cols = df_copy.select_dtypes(include=np.number).columns
|
| 303 |
+
if method == "standard":
|
| 304 |
+
scaler = StandardScaler()
|
| 305 |
+
elif method == "minmax":
|
| 306 |
+
scaler = MinMaxScaler()
|
| 307 |
+
df_copy[num_cols] = scaler.fit_transform(df_copy[num_cols])
|
| 308 |
+
return df_copy
|
| 309 |
+
|
| 310 |
+
def create_polynomial_features(df, degree):
|
| 311 |
+
"""
|
| 312 |
+
Crée des caractéristiques polynômiales.
|
| 313 |
+
"""
|
| 314 |
+
# Placeholder pour l'exemple
|
| 315 |
+
return df
|
| 316 |
+
|
| 317 |
+
def create_interaction_term(df, col1, col2):
|
| 318 |
+
"""
|
| 319 |
+
Crée un terme d'interaction.
|
| 320 |
+
"""
|
| 321 |
+
new_col_name = f"{col1}_{col2}_interaction"
|
| 322 |
+
df[new_col_name] = df[col1] * df[col2]
|
| 323 |
+
return df
|
| 324 |
+
|
| 325 |
+
def extract_datetime_features(df, col, features):
|
| 326 |
+
"""
|
| 327 |
+
Extrait des caractéristiques de date/heure.
|
| 328 |
+
"""
|
| 329 |
+
df[col] = pd.to_datetime(df[col])
|
| 330 |
+
for feature in features:
|
| 331 |
+
if feature == "year":
|
| 332 |
+
df[f'{col}_year'] = df[col].dt.year
|
| 333 |
+
elif feature == "month":
|
| 334 |
+
df[f'{col}_month'] = df[col].dt.month
|
| 335 |
+
elif feature == "day":
|
| 336 |
+
df[f'{col}_day'] = df[col].dt.day
|
| 337 |
+
# Add more features as needed
|
| 338 |
+
return df
|
| 339 |
+
|
| 340 |
+
def apply_aggregation(df, groupby_col, target_col, agg_method):
|
| 341 |
+
"""
|
| 342 |
+
Applique une agrégation.
|
| 343 |
+
"""
|
| 344 |
+
agg_df = df.groupby(groupby_col)[target_col].agg(agg_method)
|
| 345 |
+
return agg_df
|
| 346 |
+
|
| 347 |
+
def detect_outliers_isolation_forest(df, contamination=0.05):
|
| 348 |
+
"""
|
| 349 |
+
Détecte les valeurs aberrantes avec Isolation Forest.
|
| 350 |
+
"""
|
| 351 |
+
num_df = df.select_dtypes(include=np.number)
|
| 352 |
+
model = IsolationForest(contamination=contamination, random_state=42)
|
| 353 |
+
df['outlier_score'] = model.fit_predict(num_df)
|
| 354 |
+
return df
|
| 355 |
+
|
| 356 |
+
def perform_kmeans_clustering(df, n_clusters=3):
|
| 357 |
+
"""
|
| 358 |
+
Effectue un clustering K-Means sur les données numériques.
|
| 359 |
+
"""
|
| 360 |
+
num_df = df.select_dtypes(include=np.number).dropna()
|
| 361 |
+
if num_df.shape[0] > n_clusters:
|
| 362 |
+
kmeans = KMeans(n_clusters=n_clusters, random_state=42, n_init=10) # Ajout de n_init
|
| 363 |
+
df['cluster'] = kmeans.fit_predict(num_df)
|
| 364 |
+
else:
|
| 365 |
+
df['cluster'] = np.nan
|
| 366 |
+
return df
|
a6ea61c8-951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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import io
|
| 5 |
+
import base64
|
| 6 |
+
import json
|
| 7 |
+
import time
|
| 8 |
+
import os
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
import hashlib
|
| 11 |
+
import unicodedata
|
| 12 |
+
import string
|
| 13 |
+
import tempfile
|
| 14 |
+
import matplotlib.pyplot as plt
|
| 15 |
+
import seaborn as sns
|
| 16 |
+
import re
|
| 17 |
+
from collections import Counter
|
| 18 |
+
import shap
|
| 19 |
+
from sklearn.model_selection import train_test_split
|
| 20 |
+
from sklearn.metrics import mean_squared_error, accuracy_score, r2_score
|
| 21 |
+
from lightgbm import LGBMClassifier, LGBMRegressor
|
| 22 |
+
from sklearn.preprocessing import LabelEncoder, StandardScaler, MinMaxScaler
|
| 23 |
+
from sklearn.impute import KNNImputer
|
| 24 |
+
from wordcloud import WordCloud
|
| 25 |
+
import spacy
|
| 26 |
+
import plotly.express as px
|
| 27 |
+
from sklearn.ensemble import IsolationForest
|
| 28 |
+
from sklearn.cluster import KMeans
|
| 29 |
+
|
| 30 |
+
# Importation des dictionnaires de traduction spécifiques
|
| 31 |
+
from translations_base import fr_translations_base, load_users, save_users
|
| 32 |
+
from translations_data_processing import fr_translations_data_processing
|
| 33 |
+
from translations_ai_report import fr_translations_ai_report
|
| 34 |
+
from translations_report_content import fr_translations_report_content
|
| 35 |
+
from report_pdf_exporter import PdfExporter
|
| 36 |
+
from report_excel_exporter import ExcelExporter
|
| 37 |
+
from report_generator import ReportContent, AIRecommender
|
| 38 |
+
from data_processing import (
|
| 39 |
+
read_data_file, get_data_overview, get_missing_values_summary,
|
| 40 |
+
generate_data_quality_visualizations, generate_ai_report_visualizations,
|
| 41 |
+
get_saved_themes, save_theme_preferences, get_theme_preferences,
|
| 42 |
+
delete_theme_preferences, update_theme, impute_missing_values,
|
| 43 |
+
scale_features, create_polynomial_features, create_interaction_term,
|
| 44 |
+
extract_datetime_features, apply_aggregation, detect_outliers_isolation_forest,
|
| 45 |
+
perform_kmeans_clustering, generate_multicolor_plots
|
| 46 |
+
)
|
| 47 |
+
from translations import txt, set_language, translations # translations reste pour le dictionnaire complet
|
| 48 |
+
|
| 49 |
+
# --- Initialisation de st.session_state pour éviter AttributeError ---
|
| 50 |
+
if 'df' not in st.session_state:
|
| 51 |
+
st.session_state.df = None
|
| 52 |
+
if 'model' not in st.session_state:
|
| 53 |
+
st.session_state.model = None
|
| 54 |
+
if 'shap_values_data' not in st.session_state:
|
| 55 |
+
st.session_state.shap_values_data = None
|
| 56 |
+
if 'X_test_data' not in st.session_state:
|
| 57 |
+
st.session_state.X_test_data = None
|
| 58 |
+
if 'y_test_data' not in st.session_state:
|
| 59 |
+
st.session_state.y_test_data = None
|
| 60 |
+
if 'target_column' not in st.session_state:
|
| 61 |
+
st.session_state.target_column = None
|
| 62 |
+
if 'model_type' not in st.session_state:
|
| 63 |
+
st.session_state.model_type = None
|
| 64 |
+
if 'current_section' not in st.session_state:
|
| 65 |
+
st.session_state.current_section = "home" # Nouvelle section d'accueil
|
| 66 |
+
if 'last_module_choice' not in st.session_state:
|
| 67 |
+
st.session_state.last_module_choice = "home"
|
| 68 |
+
if 'theme' not in st.session_state:
|
| 69 |
+
st.session_state.theme = "Light" # Thème par défaut
|
| 70 |
+
if 'user_id' not in st.session_state:
|
| 71 |
+
st.session_state.user_id = None
|
| 72 |
+
if 'is_logged_in' not in st.session_state:
|
| 73 |
+
st.session_state.is_logged_in = False
|
| 74 |
+
if 'username' not in st.session_state:
|
| 75 |
+
st.session_state.username = None
|
| 76 |
+
if 'demo_mode' not in st.session_state:
|
| 77 |
+
st.session_state.demo_mode = False
|
| 78 |
+
if 'show_static_page' not in st.session_state: # Initialisation manquante
|
| 79 |
+
st.session_state.show_static_page = False
|
| 80 |
+
if 'active_discussion_id' not in st.session_state:
|
| 81 |
+
st.session_state.active_discussion_id = None
|
| 82 |
+
if 'active_discussion_name' not in st.session_state:
|
| 83 |
+
st.session_state.active_discussion_name = "Nouvelle Discussion"
|
| 84 |
+
if 'generate_visuals_clicked' not in st.session_state:
|
| 85 |
+
st.session_state.generate_visuals_clicked = False # Pour contrôler l'affichage des graphiques et boutons de rapport
|
| 86 |
+
if 'show_database_form' not in st.session_state:
|
| 87 |
+
st.session_state.show_database_form = False
|
| 88 |
+
if 'is_database_connected' not in st.session_state:
|
| 89 |
+
st.session_state.is_database_connected = False
|
| 90 |
+
if 'database_user' not in st.session_state:
|
| 91 |
+
st.session_state.database_user = None
|
| 92 |
+
if 'database_files' not in st.session_state:
|
| 93 |
+
st.session_state.database_files = {} # Stores file data as {filename: base64_content}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
# --- Fonctions de gestion de l'état de l'application ---
|
| 97 |
+
def set_section(section_name):
|
| 98 |
+
st.session_state.current_section = section_name
|
| 99 |
+
st.session_state.last_module_choice = section_name
|
| 100 |
+
st.session_state.show_static_page = False
|
| 101 |
+
st.session_state.show_database_form = False # Hide database form when changing section
|
| 102 |
+
|
| 103 |
+
def static_page(page_key):
|
| 104 |
+
st.session_state.show_static_page = True
|
| 105 |
+
st.session_state.last_module_choice = page_key # Mettre à jour pour afficher le bon titre et contenu
|
| 106 |
+
st.session_state.show_database_form = False # Hide database form when showing static page
|
| 107 |
+
|
| 108 |
+
def get_page_hash(page_name):
|
| 109 |
+
return hashlib.md5(page_name.encode('utf-8')).hexdigest()
|
| 110 |
+
|
| 111 |
+
def update_discussion_state():
|
| 112 |
+
"""Sauvegarde l'état actuel de la discussion pour l'utilisateur connecté."""
|
| 113 |
+
if st.session_state.is_logged_in and st.session_state.username and st.session_state.active_discussion_id:
|
| 114 |
+
users_data = load_users()
|
| 115 |
+
if st.session_state.username not in users_data:
|
| 116 |
+
users_data[st.session_state.username] = {'profile': {}, 'discussions': {}}
|
| 117 |
+
|
| 118 |
+
discussion_state = {
|
| 119 |
+
'df': st.session_state.df.to_json() if st.session_state.df is not None else None,
|
| 120 |
+
'model': base64.b64encode(io.dumps(st.session_state.model)).decode('utf-8') if st.session_state.model else None,
|
| 121 |
+
'shap_values_data': base64.b64encode(io.dumps(st.session_state.shap_values_data)).decode('utf-8') if st.session_state.shap_values_data else None,
|
| 122 |
+
'X_test_data': st.session_state.X_test_data.to_json() if st.session_state.X_test_data is not None else None,
|
| 123 |
+
'y_test_data': st.session_state.y_test_data.to_json() if st.session_state.y_test_data is not None else None,
|
| 124 |
+
'target_column': st.session_state.target_column,
|
| 125 |
+
'model_type': st.session_state.model_type,
|
| 126 |
+
'current_section': st.session_state.current_section,
|
| 127 |
+
'last_module_choice': st.session_state.last_module_choice,
|
| 128 |
+
'generate_visuals_clicked': st.session_state.generate_visuals_clicked,
|
| 129 |
+
'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 130 |
+
}
|
| 131 |
+
users_data[st.session_state.username]['discussions'][st.session_state.active_discussion_id] = discussion_state
|
| 132 |
+
save_users(users_data)
|
| 133 |
+
#st.sidebar.success(f"Discussion '{st.session_state.active_discussion_name}' sauvegardée.")
|
| 134 |
+
|
| 135 |
+
def load_discussion_state(discussion_id):
|
| 136 |
+
"""Charge l'état d'une discussion spécifique pour l'utilisateur connecté."""
|
| 137 |
+
users_data = load_users()
|
| 138 |
+
discussions = users_data.get(st.session_state.username, {}).get('discussions', {})
|
| 139 |
+
|
| 140 |
+
if discussion_id in discussions:
|
| 141 |
+
state = discussions[discussion_id]
|
| 142 |
+
if state['df']:
|
| 143 |
+
st.session_state.df = pd.read_json(state['df'])
|
| 144 |
+
else:
|
| 145 |
+
st.session_state.df = None
|
| 146 |
+
# Pour le modèle et SHAP, un processus de désérialisation plus complexe serait nécessaire.
|
| 147 |
+
# Pour l'instant, je les laisse à None ou gère comme des chaînes si c'est suffisant pour le besoin.
|
| 148 |
+
st.session_state.model = None # Ou désérialiser si le format est compatible
|
| 149 |
+
st.session_state.shap_values_data = None # Idem
|
| 150 |
+
if state['X_test_data']:
|
| 151 |
+
st.session_state.X_test_data = pd.read_json(state['X_test_data'])
|
| 152 |
+
else:
|
| 153 |
+
st.session_state.X_test_data = None
|
| 154 |
+
if state['y_test_data']:
|
| 155 |
+
st.session_state.y_test_data = pd.read_json(state['y_test_data'], typ='series')
|
| 156 |
+
else:
|
| 157 |
+
st.session_state.y_test_data = None
|
| 158 |
+
|
| 159 |
+
st.session_state.target_column = state['target_column']
|
| 160 |
+
st.session_state.model_type = state['model_type']
|
| 161 |
+
st.session_state.current_section = state['current_section']
|
| 162 |
+
st.session_state.last_module_choice = state['last_module_choice']
|
| 163 |
+
st.session_state.generate_visuals_clicked = state.get('generate_visuals_clicked', False)
|
| 164 |
+
|
| 165 |
+
# Mettre à jour l'ID et le nom de la discussion active
|
| 166 |
+
st.session_state.active_discussion_id = discussion_id
|
| 167 |
+
# Trouver le nom correspondant à l'ID
|
| 168 |
+
for name, disc_id in users_data[st.session_state.username]['discussions_meta'].items():
|
| 169 |
+
if disc_id == discussion_id:
|
| 170 |
+
st.session_state.active_discussion_name = name
|
| 171 |
+
break
|
| 172 |
+
|
| 173 |
+
st.sidebar.success(f"Discussion '{st.session_state.active_discussion_name}' chargée.")
|
| 174 |
+
st.session_state.show_static_page = False # Assurez-vous de quitter la page statique
|
| 175 |
+
st.rerun()
|
| 176 |
+
else:
|
| 177 |
+
st.sidebar.error("Discussion non trouvée.")
|
| 178 |
+
|
| 179 |
+
def create_new_discussion(discussion_name):
|
| 180 |
+
"""Crée une nouvelle discussion et la rend active."""
|
| 181 |
+
if not st.session_state.is_logged_in:
|
| 182 |
+
st.sidebar.warning("Veuillez vous connecter pour créer une nouvelle discussion.")
|
| 183 |
+
return
|
| 184 |
+
|
| 185 |
+
users_data = load_users()
|
| 186 |
+
user_data = users_data.get(st.session_state.username, {})
|
| 187 |
+
|
| 188 |
+
# Initialiser 'discussions_meta' si elle n'existe pas
|
| 189 |
+
if 'discussions_meta' not in user_data:
|
| 190 |
+
user_data['discussions_meta'] = {}
|
| 191 |
+
|
| 192 |
+
# Vérifier si le nom de discussion existe déjà
|
| 193 |
+
if discussion_name in user_data['discussions_meta']:
|
| 194 |
+
st.sidebar.error(txt("discussion_name_exists"))
|
| 195 |
+
return
|
| 196 |
+
|
| 197 |
+
new_discussion_id = hashlib.md5(f"{st.session_state.username}_{discussion_name}_{datetime.now()}".encode('utf-8')).hexdigest()
|
| 198 |
+
|
| 199 |
+
# Enregistrer le nom et l'ID dans discussions_meta
|
| 200 |
+
user_data['discussions_meta'][discussion_name] = new_discussion_id
|
| 201 |
+
|
| 202 |
+
# Créer un état initial vide pour la nouvelle discussion
|
| 203 |
+
user_data['discussions'][new_discussion_id] = {
|
| 204 |
+
'df': None,
|
| 205 |
+
'model': None,
|
| 206 |
+
'shap_values_data': None,
|
| 207 |
+
'X_test_data': None,
|
| 208 |
+
'y_test_data': None,
|
| 209 |
+
'target_column': None,
|
| 210 |
+
'model_type': None,
|
| 211 |
+
'current_section': "home",
|
| 212 |
+
'last_module_choice': "home",
|
| 213 |
+
'generate_visuals_clicked': False,
|
| 214 |
+
'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
users_data[st.session_state.username] = user_data # Mettre à jour les données de l'utilisateur
|
| 218 |
+
save_users(users_data)
|
| 219 |
+
|
| 220 |
+
st.session_state.active_discussion_id = new_discussion_id
|
| 221 |
+
st.session_state.active_discussion_name = discussion_name
|
| 222 |
+
|
| 223 |
+
# Réinitialiser l'état de l'application pour la nouvelle discussion
|
| 224 |
+
st.session_state.df = None
|
| 225 |
+
st.session_state.model = None
|
| 226 |
+
st.session_state.shap_values_data = None
|
| 227 |
+
st.session_state.X_test_data = None
|
| 228 |
+
st.session_state.y_test_data = None
|
| 229 |
+
st.session_state.target_column = None
|
| 230 |
+
st.session_state.model_type = None
|
| 231 |
+
st.session_state.current_section = "home"
|
| 232 |
+
st.session_state.last_module_choice = "home"
|
| 233 |
+
st.session_state.show_static_page = False
|
| 234 |
+
st.session_state.generate_visuals_clicked = False
|
| 235 |
+
|
| 236 |
+
st.sidebar.success(txt("discussion_created_success").format(discussion_name=discussion_name))
|
| 237 |
+
st.rerun()
|
| 238 |
+
|
| 239 |
+
def delete_discussion(discussion_id, discussion_name):
|
| 240 |
+
"""Supprime une discussion."""
|
| 241 |
+
if not st.session_state.is_logged_in:
|
| 242 |
+
st.sidebar.warning("Veuillez vous connecter pour supprimer une discussion.")
|
| 243 |
+
return
|
| 244 |
+
|
| 245 |
+
users_data = load_users()
|
| 246 |
+
user_data = users_data.get(st.session_state.username, {})
|
| 247 |
+
|
| 248 |
+
if 'discussions' in user_data and discussion_id in user_data['discussions']:
|
| 249 |
+
del user_data['discussions'][discussion_id]
|
| 250 |
+
|
| 251 |
+
# Supprimer aussi de discussions_meta
|
| 252 |
+
if 'discussions_meta' in user_data:
|
| 253 |
+
for name, did in list(user_data['discussions_meta'].items()): # Utiliser list() pour itérer et modifier
|
| 254 |
+
if did == discussion_id:
|
| 255 |
+
del user_data['discussions_meta'][name]
|
| 256 |
+
break
|
| 257 |
+
|
| 258 |
+
users_data[st.session_state.username] = user_data
|
| 259 |
+
save_users(users_data)
|
| 260 |
+
|
| 261 |
+
# Si la discussion supprimée était la discussion active, réinitialiser
|
| 262 |
+
if st.session_state.active_discussion_id == discussion_id:
|
| 263 |
+
st.session_state.active_discussion_id = None
|
| 264 |
+
st.session_state.active_discussion_name = "Nouvelle Discussion"
|
| 265 |
+
st.session_state.df = None
|
| 266 |
+
st.session_state.model = None
|
| 267 |
+
st.session_state.shap_values_data = None
|
| 268 |
+
st.session_state.X_test_data = None
|
| 269 |
+
st.session_state.y_test_data = None
|
| 270 |
+
st.session_state.target_column = None
|
| 271 |
+
st.session_state.model_type = None
|
| 272 |
+
st.session_state.current_section = "home"
|
| 273 |
+
st.session_state.last_module_choice = "home"
|
| 274 |
+
st.session_state.show_static_page = False
|
| 275 |
+
st.session_state.generate_visuals_clicked = False
|
| 276 |
+
|
| 277 |
+
st.sidebar.success(txt("discussion_deleted_success").format(discussion_name=discussion_name))
|
| 278 |
+
st.rerun()
|
| 279 |
+
else:
|
| 280 |
+
st.sidebar.error("Discussion non trouvée pour la suppression.")
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def check_password(username, password):
|
| 284 |
+
users_data = load_users()
|
| 285 |
+
user_data = users_data.get(username)
|
| 286 |
+
if user_data:
|
| 287 |
+
if hashlib.sha256(password.encode('utf-8')).hexdigest() == user_data['password']:
|
| 288 |
+
return True, user_data['user_id']
|
| 289 |
+
return False, None
|
| 290 |
+
|
| 291 |
+
def create_account(username, password, profile_type):
|
| 292 |
+
users_data = load_users()
|
| 293 |
+
if username in users_data:
|
| 294 |
+
return False, "Ce nom d'utilisateur existe déjà."
|
| 295 |
+
|
| 296 |
+
# Password strength validation
|
| 297 |
+
if not (8 <= len(password) <= 15 and
|
| 298 |
+
any(c.isdigit() for c in password) and
|
| 299 |
+
any(c.isalpha() for c in password) and
|
| 300 |
+
any(c in string.punctuation for c in password)):
|
| 301 |
+
return False, txt("enter_password_strong_requirements")
|
| 302 |
+
|
| 303 |
+
hashed_password = hashlib.sha256(password.encode('utf-8')).hexdigest()
|
| 304 |
+
new_user_id = hashlib.md5(username.encode('utf-8')).hexdigest()
|
| 305 |
+
|
| 306 |
+
users_data[username] = {
|
| 307 |
+
'password': hashed_password,
|
| 308 |
+
'user_id': new_user_id,
|
| 309 |
+
'profile': {'type': profile_type}, # Sauvegarde du type de profil
|
| 310 |
+
'discussions': {}, # Pour les discussions de l'utilisateur
|
| 311 |
+
'discussions_meta': {}, # Pour stocker les noms de discussion et leurs IDs
|
| 312 |
+
'database_files': {} # Initialize database files for the user
|
| 313 |
+
}
|
| 314 |
+
save_users(users_data)
|
| 315 |
+
return True, "Compte créé avec succès !"
|
| 316 |
+
|
| 317 |
+
def login_form():
|
| 318 |
+
st.subheader(txt("login_title"))
|
| 319 |
+
st.markdown(txt("login_intro"))
|
| 320 |
+
|
| 321 |
+
username = st.text_input(f"{txt('username_label')} 👤", key="login_username")
|
| 322 |
+
password = st.text_input(f"{txt('password_label')} 🔒", type="password", key="login_password")
|
| 323 |
+
|
| 324 |
+
# Pour la création de compte, demander le type de profil
|
| 325 |
+
is_create_account_mode = st.checkbox(txt("create_account_button"), key="create_account_checkbox")
|
| 326 |
+
profile_type = None
|
| 327 |
+
if is_create_account_mode:
|
| 328 |
+
st.markdown(txt("create_profile_explanation"))
|
| 329 |
+
profile_options = [
|
| 330 |
+
txt("profile_agent_immobilier"),
|
| 331 |
+
txt("profile_investisseur"),
|
| 332 |
+
txt("profile_expert_data"),
|
| 333 |
+
txt("profile_autre")
|
| 334 |
+
]
|
| 335 |
+
profile_type = st.selectbox(txt("profile_type_label"), options=profile_options, key="profile_type_selector")
|
| 336 |
+
|
| 337 |
+
col1, col2 = st.columns(2)
|
| 338 |
+
with col1:
|
| 339 |
+
if st.button(txt("login_button"), key="login_btn"):
|
| 340 |
+
if username and password:
|
| 341 |
+
is_valid, user_id = check_password(username, password)
|
| 342 |
+
if is_valid:
|
| 343 |
+
st.session_state.is_logged_in = True
|
| 344 |
+
st.session_state.username = username
|
| 345 |
+
st.session_state.user_id = user_id
|
| 346 |
+
st.session_state.demo_mode = False
|
| 347 |
+
st.success(txt("login_success"))
|
| 348 |
+
|
| 349 |
+
# Load database files for the logged-in user
|
| 350 |
+
users_data = load_users()
|
| 351 |
+
st.session_state.database_files = users_data.get(username, {}).get('database_files', {})
|
| 352 |
+
|
| 353 |
+
# Charger la dernière discussion ou créer une par défaut
|
| 354 |
+
user_discussions_meta = users_data.get(username, {}).get('discussions_meta', {})
|
| 355 |
+
if user_discussions_meta:
|
| 356 |
+
# Charger la dernière discussion par timestamp si implémenté, ou la première trouvée
|
| 357 |
+
first_discussion_name = list(user_discussions_meta.keys())[0]
|
| 358 |
+
first_discussion_id = user_discussions_meta[first_discussion_name]
|
| 359 |
+
load_discussion_state(first_discussion_id) # Cela va aussi mettre à jour active_discussion_name
|
| 360 |
+
else:
|
| 361 |
+
# Créer une discussion par défaut pour le nouvel utilisateur
|
| 362 |
+
default_discussion_name = "Première discussion"
|
| 363 |
+
create_new_discussion(default_discussion_name)
|
| 364 |
+
st.rerun()
|
| 365 |
+
else:
|
| 366 |
+
st.error(txt("login_error"))
|
| 367 |
+
else:
|
| 368 |
+
st.warning(txt("login_fields_prompt"))
|
| 369 |
+
with col2:
|
| 370 |
+
if is_create_account_mode and st.button(txt("create_account_button"), key="create_new_account_btn"):
|
| 371 |
+
if username and password and profile_type:
|
| 372 |
+
success, message = create_account(username, password, profile_type)
|
| 373 |
+
if success:
|
| 374 |
+
st.success(message)
|
| 375 |
+
st.info(txt("profile_saved_success"))
|
| 376 |
+
# After account creation, the user will need to log in.
|
| 377 |
+
else:
|
| 378 |
+
st.error(message)
|
| 379 |
+
else:
|
| 380 |
+
st.warning(txt("create_account_fields_prompt"))
|
| 381 |
+
|
| 382 |
+
if st.button(txt("explore_demo_button"), key="demo_mode_btn", use_container_width=True):
|
| 383 |
+
st.session_state.is_logged_in = False
|
| 384 |
+
st.session_state.username = "Mode Démo"
|
| 385 |
+
st.session_state.user_id = "demo_user"
|
| 386 |
+
st.session_state.demo_mode = True
|
| 387 |
+
st.session_state.df = pd.DataFrame(translations['fr']['demo_data'])
|
| 388 |
+
st.session_state.active_discussion_id = "demo_discussion" # Fictitious ID
|
| 389 |
+
st.session_state.active_discussion_name = "Données de Démonstration"
|
| 390 |
+
st.session_state.database_files = {} # No database files in demo mode
|
| 391 |
+
st.success(txt("demo_mode_activated"))
|
| 392 |
+
set_section("data_diagnostic_title")
|
| 393 |
+
st.rerun()
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def save_user_data(df_to_save, filename="current_data.csv"):
|
| 397 |
+
# This function is now less used directly for files,
|
| 398 |
+
# because "discussions" manage the complete state.
|
| 399 |
+
# However, it can be adapted to save specific files if needed.
|
| 400 |
+
if st.session_state.is_logged_in and st.session_state.user_id and not st.session_state.demo_mode:
|
| 401 |
+
# The file saving logic is now integrated into discussions
|
| 402 |
+
# The df is saved in the discussion state.
|
| 403 |
+
st.info("Le DataFrame est sauvegardé dans la discussion active.")
|
| 404 |
+
update_discussion_state() # Save current state
|
| 405 |
+
elif st.session_state.demo_mode:
|
| 406 |
+
st.info(txt("save_not_available_demo"))
|
| 407 |
+
else:
|
| 408 |
+
st.warning(txt("login_required_save"))
|
| 409 |
+
|
| 410 |
+
def load_user_data_from_list(discussion_id, discussion_name):
|
| 411 |
+
load_discussion_state(discussion_id)
|
| 412 |
+
|
| 413 |
+
def database_login_form():
|
| 414 |
+
"""
|
| 415 |
+
Formulaire de connexion/création de compte pour la base de données.
|
| 416 |
+
Utilise les mêmes comptes que l'application principale.
|
| 417 |
+
"""
|
| 418 |
+
st.subheader(txt("login_to_database"))
|
| 419 |
+
db_username = st.text_input(f"{txt('username_label')} 👤", key="db_login_username")
|
| 420 |
+
db_password = st.text_input(f"{txt('password_label')} 🔒", type="password", key="db_login_password")
|
| 421 |
+
|
| 422 |
+
if st.button(txt("login_button"), key="db_login_btn"):
|
| 423 |
+
if db_username and db_password:
|
| 424 |
+
is_valid, user_id = check_password(db_username, db_password)
|
| 425 |
+
if is_valid:
|
| 426 |
+
st.session_state.is_database_connected = True
|
| 427 |
+
st.session_state.database_user = db_username
|
| 428 |
+
# Load database files for the logged-in user
|
| 429 |
+
users_data = load_users()
|
| 430 |
+
st.session_state.database_files = users_data.get(db_username, {}).get('database_files', {})
|
| 431 |
+
st.success(txt("login_success"))
|
| 432 |
+
st.rerun()
|
| 433 |
+
else:
|
| 434 |
+
st.error(txt("login_error"))
|
| 435 |
+
else:
|
| 436 |
+
st.warning(txt("login_fields_prompt"))
|
| 437 |
+
|
| 438 |
+
if st.button(txt("create_account_button"), key="db_create_account_btn"):
|
| 439 |
+
# Redirect to the main login form for account creation if not already logged in
|
| 440 |
+
st.session_state.show_database_form = False # Hide DB form to show main login
|
| 441 |
+
st.session_state.is_logged_in = False # Force showing main login form
|
| 442 |
+
st.rerun() # This will display the main login form where account creation is handled
|
| 443 |
+
st.warning("Veuillez créer un compte via le formulaire de connexion principal.")
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def database_management_interface():
|
| 447 |
+
"""
|
| 448 |
+
Interface pour gérer les fichiers dans la base de données.
|
| 449 |
+
"""
|
| 450 |
+
st.header(txt("database_section"))
|
| 451 |
+
st.info(txt("database_intro"))
|
| 452 |
+
|
| 453 |
+
# Fonctionnalité 1: Importer un ou plusieurs fichiers
|
| 454 |
+
st.subheader(txt("import_files_to_db_title"))
|
| 455 |
+
uploaded_db_files = st.file_uploader(
|
| 456 |
+
txt("upload_db_files_label"),
|
| 457 |
+
type=["csv", "txt", "json", "xls", "xlsx", "parquet", "orc", "feather", "dta", "sas7bdat"],
|
| 458 |
+
accept_multiple_files=True,
|
| 459 |
+
key="db_file_uploader"
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
if uploaded_db_files:
|
| 463 |
+
if len(uploaded_db_files) > 10:
|
| 464 |
+
st.warning("Vous ne pouvez télécharger que 10 fichiers maximum à la fois.")
|
| 465 |
+
uploaded_db_files = uploaded_db_files[:10]
|
| 466 |
+
|
| 467 |
+
action_choice = st.radio(
|
| 468 |
+
"Que souhaitez-vous faire avec le(s) fichier(s) téléchargé(s) ?",
|
| 469 |
+
[txt("file_storage_option"), txt("advanced_analysis_option")],
|
| 470 |
+
key="db_action_choice"
|
| 471 |
+
)
|
| 472 |
+
|
| 473 |
+
if action_choice == txt("file_storage_option"):
|
| 474 |
+
if st.button("Stocker les fichiers", key="store_db_files_btn"):
|
| 475 |
+
if uploaded_db_files:
|
| 476 |
+
users_data = load_users()
|
| 477 |
+
user_db_files = users_data.get(st.session_state.database_user, {}).get('database_files', {})
|
| 478 |
+
|
| 479 |
+
stored_count = 0
|
| 480 |
+
for uploaded_file in uploaded_db_files:
|
| 481 |
+
file_contents = uploaded_file.getvalue()
|
| 482 |
+
encoded_content = base64.b64encode(file_contents).decode('utf-8')
|
| 483 |
+
user_db_files[uploaded_file.name] = {
|
| 484 |
+
'content': encoded_content,
|
| 485 |
+
'type': uploaded_file.type,
|
| 486 |
+
'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 487 |
+
}
|
| 488 |
+
stored_count += 1
|
| 489 |
+
|
| 490 |
+
users_data[st.session_state.database_user]['database_files'] = user_db_files
|
| 491 |
+
save_users(users_data)
|
| 492 |
+
st.session_state.database_files = user_db_files # Update session state
|
| 493 |
+
st.success(txt("files_saved_to_db").format(count=stored_count))
|
| 494 |
+
st.rerun()
|
| 495 |
+
else:
|
| 496 |
+
st.warning(txt("no_files_uploaded_for_db"))
|
| 497 |
+
|
| 498 |
+
elif action_choice == txt("advanced_analysis_option"):
|
| 499 |
+
if len(uploaded_db_files) == 1:
|
| 500 |
+
selected_file_for_analysis = uploaded_db_files[0]
|
| 501 |
+
if st.button(txt("analyze_selected_file_button"), key="analyze_uploaded_file_btn"):
|
| 502 |
+
# Process the single file for advanced analysis
|
| 503 |
+
file_contents = selected_file_for_analysis.getvalue()
|
| 504 |
+
|
| 505 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(selected_file_for_analysis.name)[1]) as tmp_file:
|
| 506 |
+
tmp_file.write(file_contents)
|
| 507 |
+
tmp_file_path = tmp_file.name
|
| 508 |
+
|
| 509 |
+
df, message = read_data_file(tmp_file_path)
|
| 510 |
+
os.unlink(tmp_file_path) # Clean up temp file
|
| 511 |
+
|
| 512 |
+
if df is not None:
|
| 513 |
+
st.session_state.df = df
|
| 514 |
+
st.session_state.current_section = "data_diagnostic_title"
|
| 515 |
+
st.success(txt("analysis_triggered_for_file").format(filename=selected_file_for_analysis.name))
|
| 516 |
+
st.rerun()
|
| 517 |
+
else:
|
| 518 |
+
st.error(f"{txt('error_reading_file')} : {message}")
|
| 519 |
+
else:
|
| 520 |
+
st.warning(txt("please_select_one_file_for_analysis"))
|
| 521 |
+
|
| 522 |
+
# Fonctionnalité 2: Afficher les fichiers stockés et lancer une analyse sur un fichier existant
|
| 523 |
+
st.markdown("---")
|
| 524 |
+
st.subheader(txt("stored_files_title"))
|
| 525 |
+
if st.session_state.database_files:
|
| 526 |
+
file_names = list(st.session_state.database_files.keys())
|
| 527 |
+
selected_stored_file = st.selectbox(
|
| 528 |
+
txt("select_stored_file_for_analysis"),
|
| 529 |
+
options=file_names,
|
| 530 |
+
key="selected_stored_file"
|
| 531 |
+
)
|
| 532 |
+
|
| 533 |
+
col_view, col_analyze, col_delete = st.columns(3)
|
| 534 |
+
|
| 535 |
+
with col_view:
|
| 536 |
+
if st.button(txt("view_file_content_button"), key="view_stored_file_btn"):
|
| 537 |
+
file_data = st.session_state.database_files[selected_stored_file]
|
| 538 |
+
decoded_content = base64.b64decode(file_data['content'])
|
| 539 |
+
|
| 540 |
+
# Display content based on file type
|
| 541 |
+
if 'csv' in file_data['type'] or 'text' in file_data['type']:
|
| 542 |
+
st.text_area(f"Contenu de {selected_stored_file}", decoded_content.decode('utf-8'), height=300)
|
| 543 |
+
elif 'json' in file_data['type']:
|
| 544 |
+
st.json(json.loads(decoded_content.decode('utf-8')))
|
| 545 |
+
else:
|
| 546 |
+
st.write("Aperçu non disponible pour ce type de fichier. Téléchargez pour voir.")
|
| 547 |
+
st.download_button(
|
| 548 |
+
label=f"Télécharger {selected_stored_file}",
|
| 549 |
+
data=decoded_content,
|
| 550 |
+
file_name=selected_stored_file,
|
| 551 |
+
mime=file_data['type'],
|
| 552 |
+
key=f"download_stored_{selected_stored_file}"
|
| 553 |
+
)
|
| 554 |
+
|
| 555 |
+
with col_analyze:
|
| 556 |
+
if st.button(txt("analyze_selected_file_button"), key="analyze_stored_file_btn"):
|
| 557 |
+
file_data = st.session_state.database_files[selected_stored_file]
|
| 558 |
+
decoded_content = base64.b64decode(file_data['content'])
|
| 559 |
+
|
| 560 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(selected_stored_file)[1]) as tmp_file:
|
| 561 |
+
tmp_file.write(decoded_content)
|
| 562 |
+
tmp_file_path = tmp_file.name
|
| 563 |
+
|
| 564 |
+
df, message = read_data_file(tmp_file_path)
|
| 565 |
+
os.unlink(tmp_file_path)
|
| 566 |
+
|
| 567 |
+
if df is not None:
|
| 568 |
+
st.session_state.df = df
|
| 569 |
+
st.session_state.current_section = "data_diagnostic_title"
|
| 570 |
+
st.success(txt("analysis_triggered_for_file").format(filename=selected_stored_file))
|
| 571 |
+
st.rerun()
|
| 572 |
+
else:
|
| 573 |
+
st.error(f"{txt('error_reading_file')} : {message}")
|
| 574 |
+
|
| 575 |
+
with col_delete:
|
| 576 |
+
if st.button(txt("delete_file_button"), key="delete_stored_file_btn"):
|
| 577 |
+
users_data = load_users()
|
| 578 |
+
if st.session_state.database_user in users_data and 'database_files' in users_data[st.session_state.database_user]:
|
| 579 |
+
del users_data[st.session_state.database_user]['database_files'][selected_stored_file]
|
| 580 |
+
save_users(users_data)
|
| 581 |
+
st.session_state.database_files = users_data[st.session_state.database_user]['database_files']
|
| 582 |
+
st.success(txt("file_deleted_success").format(filename=selected_stored_file))
|
| 583 |
+
st.rerun()
|
| 584 |
+
else:
|
| 585 |
+
st.info(txt("no_stored_files"))
|
| 586 |
+
|
| 587 |
+
# Fonctionnalité 3: Renommer un fichier (simple exemple)
|
| 588 |
+
st.markdown("---")
|
| 589 |
+
st.subheader("Renommer un fichier")
|
| 590 |
+
if st.session_state.database_files:
|
| 591 |
+
old_file_name = st.selectbox("Sélectionnez le fichier à renommer", options=list(st.session_state.database_files.keys()), key="rename_old_file")
|
| 592 |
+
new_file_name = st.text_input("Nouveau nom du fichier", key="rename_new_file")
|
| 593 |
+
if st.button("Renommer", key="rename_file_btn"):
|
| 594 |
+
if new_file_name and new_file_name != old_file_name:
|
| 595 |
+
users_data = load_users()
|
| 596 |
+
if st.session_state.database_user in users_data and 'database_files' in users_data[st.session_state.database_user]:
|
| 597 |
+
file_data = users_data[st.session_state.database_user]['database_files'].pop(old_file_name)
|
| 598 |
+
users_data[st.session_state.database_user]['database_files'][new_file_name] = file_data
|
| 599 |
+
save_users(users_data)
|
| 600 |
+
st.session_state.database_files = users_data[st.session_state.database_user]['database_files']
|
| 601 |
+
st.success(f"Fichier '{old_file_name}' renommé en '{new_file_name}'.")
|
| 602 |
+
st.rerun()
|
| 603 |
+
else:
|
| 604 |
+
st.warning("Veuillez entrer un nouveau nom de fichier valide.")
|
| 605 |
+
|
| 606 |
+
# Fonctionnalité 4: Télécharger un fichier
|
| 607 |
+
st.markdown("---")
|
| 608 |
+
st.subheader("Télécharger un fichier")
|
| 609 |
+
if st.session_state.database_files:
|
| 610 |
+
file_to_download = st.selectbox("Sélectionnez le fichier à télécharger", options=list(st.session_state.database_files.keys()), key="download_file_select")
|
| 611 |
+
if st.button("Télécharger", key="download_file_btn"):
|
| 612 |
+
file_data = st.session_state.database_files[file_to_download]
|
| 613 |
+
decoded_content = base64.b64decode(file_data['content'])
|
| 614 |
+
st.download_button(
|
| 615 |
+
label=f"Télécharger {file_to_download}",
|
| 616 |
+
data=decoded_content,
|
| 617 |
+
file_name=file_to_download,
|
| 618 |
+
mime=file_data['type'],
|
| 619 |
+
key=f"download_actual_file_{file_to_download}"
|
| 620 |
+
)
|
| 621 |
+
|
| 622 |
+
# Fonctionnalité 5: Rechercher des fichiers (simple recherche par nom)
|
| 623 |
+
st.markdown("---")
|
| 624 |
+
st.subheader("Rechercher des fichiers")
|
| 625 |
+
search_query = st.text_input("Rechercher par nom de fichier", key="file_search_query")
|
| 626 |
+
if st.button("Rechercher", key="search_files_btn"):
|
| 627 |
+
if search_query:
|
| 628 |
+
found_files = [f for f in st.session_state.database_files.keys() if search_query.lower() in f.lower()]
|
| 629 |
+
if found_files:
|
| 630 |
+
st.write("Fichiers trouvés :")
|
| 631 |
+
for f in found_files:
|
| 632 |
+
st.write(f"- {f}")
|
| 633 |
+
else:
|
| 634 |
+
st.info("Aucun fichier trouvé correspondant à votre recherche.")
|
| 635 |
+
else:
|
| 636 |
+
st.warning("Veuillez entrer un terme de recherche.")
|
| 637 |
+
|
| 638 |
+
# Fonctionnalité 6: Vider la base de données (pour l'utilisateur connecté)
|
| 639 |
+
st.markdown("---")
|
| 640 |
+
st.subheader("Vider la Base de Données")
|
| 641 |
+
st.warning("Attention : Cette action supprimera TOUS les fichiers stockés pour votre compte. Cette action est irréversible.")
|
| 642 |
+
if st.button("Vider tous les fichiers", key="clear_database_btn"):
|
| 643 |
+
users_data = load_users()
|
| 644 |
+
if st.session_state.database_user in users_data:
|
| 645 |
+
users_data[st.session_state.database_user]['database_files'] = {}
|
| 646 |
+
save_users(users_data)
|
| 647 |
+
st.session_state.database_files = {}
|
| 648 |
+
st.success("Tous les fichiers ont été supprimés de votre base de données.")
|
| 649 |
+
st.rerun()
|
| 650 |
+
|
| 651 |
+
|
| 652 |
+
# --- Gestion de l'état de la page principale ---
|
| 653 |
+
st.set_page_config(layout="wide")
|
| 654 |
+
|
| 655 |
+
# Appliquer le thème (mode sombre/clair)
|
| 656 |
+
current_theme = get_theme_preferences(st.session_state.theme)
|
| 657 |
+
if st.session_state.theme == "Dark":
|
| 658 |
+
st._config.set_option('theme.base', 'dark')
|
| 659 |
+
st._config.set_option('theme.backgroundColor', '#0E1117')
|
| 660 |
+
st._config.set_option('theme.primaryColor', '#265DCC')
|
| 661 |
+
st._config.set_option('theme.secondaryBackgroundColor', '#262730')
|
| 662 |
+
st._config.set_option('theme.textColor', '#FAFAFA')
|
| 663 |
+
st._config.set_option('theme.font', 'sans serif')
|
| 664 |
+
else: # Light theme or custom theme
|
| 665 |
+
st._config.set_option('theme.base', 'light')
|
| 666 |
+
st._config.set_option('theme.backgroundColor', '#FFFFFF')
|
| 667 |
+
st._config.set_option('theme.primaryColor', '#FF4B4B') # Default Streamlit red
|
| 668 |
+
st._config.set_option('theme.secondaryBackgroundColor', '#F0F2F6')
|
| 669 |
+
st._config.set_option('theme.textColor', '#303030')
|
| 670 |
+
st._config.set_option('theme.font', 'sans serif')
|
| 671 |
+
|
| 672 |
+
# --- Barre latérale pour la navigation ---
|
| 673 |
+
with st.sidebar:
|
| 674 |
+
st.title(txt("app_title"))
|
| 675 |
+
st.markdown(f"**{txt('app_subtitle')}**") # Mettre en gras le sous-titre
|
| 676 |
+
|
| 677 |
+
if not st.session_state.is_logged_in and not st.session_state.demo_mode:
|
| 678 |
+
pass # The login form is handled in the main body
|
| 679 |
+
else:
|
| 680 |
+
st.info(f"{txt('logged_in_as')}: **{st.session_state.username}**") # Display username in bold
|
| 681 |
+
|
| 682 |
+
# Section de gestion des discussions
|
| 683 |
+
st.subheader("Discussions")
|
| 684 |
+
st.markdown(f"**{txt('current_discussion_label').format(discussion_name=st.session_state.active_discussion_name)}**")
|
| 685 |
+
|
| 686 |
+
# Bouton Nouvelle Discussion
|
| 687 |
+
if st.button(f"✨ {txt('new_discussion_button')}", use_container_width=True):
|
| 688 |
+
with st.popover(txt("enter_discussion_name")):
|
| 689 |
+
new_disc_name = st.text_input("Nom de la nouvelle discussion", key="new_discussion_name_input")
|
| 690 |
+
if st.button("Créer"):
|
| 691 |
+
create_new_discussion(new_disc_name)
|
| 692 |
+
|
| 693 |
+
# Liste des discussions existantes
|
| 694 |
+
if st.session_state.is_logged_in and not st.session_state.demo_mode:
|
| 695 |
+
users_data = load_users()
|
| 696 |
+
user_discussions_meta = users_data.get(st.session_state.username, {}).get('discussions_meta', {})
|
| 697 |
+
|
| 698 |
+
if user_discussions_meta:
|
| 699 |
+
st.markdown("---")
|
| 700 |
+
st.markdown("Historique des discussions :")
|
| 701 |
+
for disc_name, disc_id in user_discussions_meta.items():
|
| 702 |
+
col_disc_name, col_load_btn, col_del_btn = st.columns([0.6, 0.2, 0.2])
|
| 703 |
+
with col_disc_name:
|
| 704 |
+
st.write(disc_name)
|
| 705 |
+
with col_load_btn:
|
| 706 |
+
if st.button("Charger", key=f"load_disc_{disc_id}"):
|
| 707 |
+
load_discussion_state(disc_id)
|
| 708 |
+
with col_del_btn:
|
| 709 |
+
if st.button("🗑️", key=f"del_disc_{disc_id}"):
|
| 710 |
+
delete_discussion(disc_id, disc_name)
|
| 711 |
+
else:
|
| 712 |
+
st.info(txt("no_discussions_saved"))
|
| 713 |
+
|
| 714 |
+
|
| 715 |
+
st.markdown("---")
|
| 716 |
+
st.header(txt("main_modules"))
|
| 717 |
+
if st.button(f"🏠 {txt('home_section')}", use_container_width=True):
|
| 718 |
+
set_section("home")
|
| 719 |
+
if st.button(f"📊 {txt('data_diagnostic_title')}", use_container_width=True):
|
| 720 |
+
set_section("data_diagnostic_title")
|
| 721 |
+
if st.button(f"🛠️ {txt('data_prep_title')}", use_container_width=True):
|
| 722 |
+
set_section("data_prep_title")
|
| 723 |
+
if st.button(f"🧠 {txt('ai_prediction_title')}", use_container_width=True):
|
| 724 |
+
set_section("ai_prediction_title")
|
| 725 |
+
if st.button(f"📄 {txt('report_generation_title')}", use_container_width=True):
|
| 726 |
+
set_section("report_generation_title")
|
| 727 |
+
|
| 728 |
+
# New Database button and explanation
|
| 729 |
+
st.markdown("---")
|
| 730 |
+
if st.button(f"🗄️ {txt('database_section')}", use_container_width=True, key="database_button"):
|
| 731 |
+
st.session_state.show_database_form = not st.session_state.show_database_form
|
| 732 |
+
st.session_state.show_static_page = False # Hide static page if database button is clicked
|
| 733 |
+
st.session_state.current_section = "database" # Set a specific section for the database interface
|
| 734 |
+
|
| 735 |
+
if st.session_state.show_database_form:
|
| 736 |
+
st.markdown(txt("database_intro"))
|
| 737 |
+
|
| 738 |
+
st.markdown("---")
|
| 739 |
+
st.header(txt("settings_section"))
|
| 740 |
+
|
| 741 |
+
# Theme management
|
| 742 |
+
theme_options = ["Light", "Dark"] + list(get_saved_themes().keys())
|
| 743 |
+
selected_theme = st.selectbox(
|
| 744 |
+
txt("select_theme"),
|
| 745 |
+
options=theme_options,
|
| 746 |
+
index=theme_options.index(st.session_state.theme) if st.session_state.theme in theme_options else 0,
|
| 747 |
+
key="theme_selector",
|
| 748 |
+
on_change=lambda: st.session_state.update({'theme': st.session_state.theme_selector})
|
| 749 |
+
)
|
| 750 |
+
|
| 751 |
+
if selected_theme not in ["Light", "Dark"]:
|
| 752 |
+
if st.button(txt("delete_theme_button")):
|
| 753 |
+
success, msg = delete_theme_preferences(selected_theme)
|
| 754 |
+
if success:
|
| 755 |
+
st.success(msg)
|
| 756 |
+
st.session_state.theme = "Light"
|
| 757 |
+
else:
|
| 758 |
+
st.error(msg)
|
| 759 |
+
st.rerun()
|
| 760 |
+
|
| 761 |
+
st.info(txt("theme_reload_info"))
|
| 762 |
+
|
| 763 |
+
# Logout button in the sidebar
|
| 764 |
+
st.markdown("---")
|
| 765 |
+
if st.button(txt("logout_button"), use_container_width=True):
|
| 766 |
+
# Before logging out, save active discussion if it exists
|
| 767 |
+
if st.session_state.is_logged_in and st.session_state.active_discussion_id:
|
| 768 |
+
update_discussion_state()
|
| 769 |
+
|
| 770 |
+
st.session_state.is_logged_in = False
|
| 771 |
+
st.session_state.username = None
|
| 772 |
+
st.session_state.user_id = None
|
| 773 |
+
st.session_state.df = None
|
| 774 |
+
st.session_state.demo_mode = False
|
| 775 |
+
st.session_state.active_discussion_id = None
|
| 776 |
+
st.session_state.active_discussion_name = "Nouvelle Discussion"
|
| 777 |
+
st.session_state.current_section = "home"
|
| 778 |
+
st.session_state.last_module_choice = "home"
|
| 779 |
+
st.session_state.show_static_page = False
|
| 780 |
+
st.session_state.generate_visuals_clicked = False
|
| 781 |
+
st.session_state.show_database_form = False
|
| 782 |
+
st.session_state.is_database_connected = False
|
| 783 |
+
st.session_state.database_user = None
|
| 784 |
+
st.session_state.database_files = {} # Clear database files on logout
|
| 785 |
+
st.rerun()
|
| 786 |
+
|
| 787 |
+
|
| 788 |
+
# --- Main page content ---
|
| 789 |
+
if not st.session_state.is_logged_in and not st.session_state.demo_mode:
|
| 790 |
+
st.title(txt("app_title_welcome"))
|
| 791 |
+
login_form()
|
| 792 |
+
elif st.session_state.show_static_page:
|
| 793 |
+
st.header(txt(st.session_state.last_module_choice)) # Uses the section key
|
| 794 |
+
st.write(txt(f"{st.session_state.last_module_choice}_content")) # Uses the key_content
|
| 795 |
+
if st.button(txt("back_to_dashboard_button")):
|
| 796 |
+
st.session_state.show_static_page = False
|
| 797 |
+
st.rerun()
|
| 798 |
+
elif st.session_state.current_section == "database":
|
| 799 |
+
if not st.session_state.is_database_connected:
|
| 800 |
+
database_login_form()
|
| 801 |
+
else:
|
| 802 |
+
database_management_interface()
|
| 803 |
+
elif st.session_state.current_section == "home":
|
| 804 |
+
st.title(txt("home_welcome_title").format(username=st.session_state.username))
|
| 805 |
+
st.markdown(txt("home_intro"))
|
| 806 |
+
|
| 807 |
+
st.subheader(txt("home_feature_discovery_title"))
|
| 808 |
+
|
| 809 |
+
# Concrete use cases
|
| 810 |
+
st.markdown("#### Exemples d'Analyse :")
|
| 811 |
+
st.markdown("""
|
| 812 |
+
- **Agent Immobilier 🏡:** Analysez les prix du marché, identifiez les propriétés surévaluées/sous-évaluées, comprenez les facteurs clés de valeur.
|
| 813 |
+
- **Investisseur 💰:** Détectez des opportunités d'investissement, segmentez le marché pour trouver des niches, évaluez les risques.
|
| 814 |
+
- **Promoteur Immobilier 🏗️:** Évaluez le potentiel de nouveaux projets, anticipez les tendances, optimisez les stratégies de vente.
|
| 815 |
+
""")
|
| 816 |
+
|
| 817 |
+
st.subheader(txt("home_ai_models_title"))
|
| 818 |
+
st.markdown(txt("home_ai_models_description"))
|
| 819 |
+
|
| 820 |
+
st.markdown(f"- **LightGBM:** Un algorithme d'apprentissage puissant pour la prédiction. 🚀")
|
| 821 |
+
st.markdown(f"- **Isolation Forest:** Idéal pour détecter les anomalies et les valeurs aberrantes. 🔍")
|
| 822 |
+
st.markdown(f"- **K-Means:** Pour regrouper les propriétés similaires et découvrir des segments de marché. 🧩")
|
| 823 |
+
|
| 824 |
+
# Main button to import a file, visible on the home page if not in demo mode
|
| 825 |
+
if not st.session_state.demo_mode:
|
| 826 |
+
st.markdown("---")
|
| 827 |
+
if st.button(txt("main_section_import_button"), use_container_width=True):
|
| 828 |
+
set_section("data_diagnostic_title")
|
| 829 |
+
st.rerun()
|
| 830 |
+
|
| 831 |
+
else: # Main application logic
|
| 832 |
+
# Section for file upload if not in demo mode
|
| 833 |
+
if not st.session_state.demo_mode:
|
| 834 |
+
st.header(f"📥 {txt('data_diagnostic_title')} - {txt('upload_label')}")
|
| 835 |
+
st.info(txt("import_file_types_info"))
|
| 836 |
+
uploaded_file = st.file_uploader(txt("upload_label"), type=["csv", "txt", "json", "xls", "xlsx", "parquet", "orc", "feather", "dta", "sas7bdat"])
|
| 837 |
+
|
| 838 |
+
if uploaded_file is not None:
|
| 839 |
+
file_details = {"FileName": uploaded_file.name, "FileType": uploaded_file.type}
|
| 840 |
+
st.write(txt("file_details"))
|
| 841 |
+
st.write(file_details)
|
| 842 |
+
|
| 843 |
+
# Use a unique filename to avoid conflicts in temporary folders
|
| 844 |
+
unique_filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{uploaded_file.name}"
|
| 845 |
+
|
| 846 |
+
# Save the file temporarily for reading by read_data_file
|
| 847 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(uploaded_file.name)[1]) as tmp_file:
|
| 848 |
+
tmp_file.write(uploaded_file.getvalue())
|
| 849 |
+
tmp_file_path = tmp_file.name
|
| 850 |
+
|
| 851 |
+
df, message = read_data_file(tmp_file_path)
|
| 852 |
+
|
| 853 |
+
# Delete the temporary file after reading
|
| 854 |
+
os.unlink(tmp_file_path)
|
| 855 |
+
|
| 856 |
+
if df is not None:
|
| 857 |
+
st.session_state.df = df
|
| 858 |
+
st.success(txt("file_uploaded_success"))
|
| 859 |
+
st.session_state.generate_visuals_clicked = False # Reset when a new file is loaded
|
| 860 |
+
update_discussion_state() # Save the DF to the active discussion
|
| 861 |
+
st.rerun() # To display the information directly
|
| 862 |
+
|
| 863 |
+
else:
|
| 864 |
+
st.error(f"{txt('error_reading_file')} : {message}")
|
| 865 |
+
|
| 866 |
+
# Display demo DataFrame or loaded data
|
| 867 |
+
if st.session_state.df is not None:
|
| 868 |
+
if st.session_state.demo_mode:
|
| 869 |
+
st.subheader(txt("demo_data_title"))
|
| 870 |
+
st.write(txt("demo_data_intro"))
|
| 871 |
+
st.dataframe(st.session_state.df.head())
|
| 872 |
+
else:
|
| 873 |
+
st.subheader(txt("dataframe_sample"))
|
| 874 |
+
st.dataframe(st.session_state.df.head())
|
| 875 |
+
|
| 876 |
+
# --- Automatic display of initial information and visualizations ---
|
| 877 |
+
st.markdown("---")
|
| 878 |
+
st.header(f"📊 {txt('data_diagnostic_title')}")
|
| 879 |
+
st.info(txt("data_diagnostic_intro"))
|
| 880 |
+
|
| 881 |
+
overview = get_data_overview(st.session_state.df)
|
| 882 |
+
st.subheader(txt("overview_data"))
|
| 883 |
+
st.write(txt("num_rows").format(rows=overview['rows']))
|
| 884 |
+
st.write(txt("num_cols").format(cols=overview['cols']))
|
| 885 |
+
|
| 886 |
+
st.subheader(txt("descriptive_stats"))
|
| 887 |
+
st.write(st.session_state.df.describe())
|
| 888 |
+
|
| 889 |
+
st.subheader(txt("missing_values"))
|
| 890 |
+
missing_summary = get_missing_values_summary(st.session_state.df)
|
| 891 |
+
if not missing_summary.empty:
|
| 892 |
+
st.write(missing_summary)
|
| 893 |
+
else:
|
| 894 |
+
st.info(txt("no_missing_values"))
|
| 895 |
+
|
| 896 |
+
# Button to generate visualizations
|
| 897 |
+
if st.button(txt("generate_visualizations_button"), key="generate_data_viz_button"):
|
| 898 |
+
st.session_state.generate_visuals_clicked = True
|
| 899 |
+
st.rerun() # To display the charts below the button
|
| 900 |
+
|
| 901 |
+
if st.session_state.generate_visuals_clicked:
|
| 902 |
+
generate_multicolor_plots(st.session_state.df.copy())
|
| 903 |
+
|
| 904 |
+
# Display PDF/Excel download buttons here if the model is trained
|
| 905 |
+
if st.session_state.model is not None:
|
| 906 |
+
st.markdown("---")
|
| 907 |
+
st.subheader(txt("report_generation_title"))
|
| 908 |
+
st.info(txt("report_generation_intro"))
|
| 909 |
+
|
| 910 |
+
report_content = ReportContent(
|
| 911 |
+
df=st.session_state.df,
|
| 912 |
+
model=st.session_state.model,
|
| 913 |
+
shap_values_data=st.session_state.shap_values_data,
|
| 914 |
+
X_test_data=st.session_state.X_test_data,
|
| 915 |
+
y_test_data=st.session_state.y_test_data,
|
| 916 |
+
target_column=st.session_state.target_column,
|
| 917 |
+
model_type=st.session_state.model_type,
|
| 918 |
+
txt_func=txt
|
| 919 |
+
)
|
| 920 |
+
|
| 921 |
+
# Report customization (simplified for display here)
|
| 922 |
+
report_custom_title_line1 = txt("default_report_title_line1")
|
| 923 |
+
report_custom_subtitle = txt("default_report_subtitle")
|
| 924 |
+
report_custom_footer = txt("default_report_footer").format(date=datetime.now().strftime("%Y-%m-%d"))
|
| 925 |
+
selected_sections = report_content.available_report_sections # All default sections
|
| 926 |
+
|
| 927 |
+
report_options = {
|
| 928 |
+
"report_custom_title_line1": report_custom_title_line1,
|
| 929 |
+
"report_custom_subtitle": report_custom_subtitle,
|
| 930 |
+
"report_custom_footer": report_custom_footer,
|
| 931 |
+
"selected_report_sections": selected_sections
|
| 932 |
+
}
|
| 933 |
+
report_content.update_report_options(report_options)
|
| 934 |
+
|
| 935 |
+
col_pdf, col_excel = st.columns(2)
|
| 936 |
+
|
| 937 |
+
with col_pdf:
|
| 938 |
+
pdf_exporter = PdfExporter(report_content)
|
| 939 |
+
pdf_output = io.BytesIO()
|
| 940 |
+
pdf_exporter.export_pdf(pdf_output)
|
| 941 |
+
st.download_button(
|
| 942 |
+
label=txt("download_pdf_button"),
|
| 943 |
+
data=pdf_output.getvalue(),
|
| 944 |
+
file_name=f"Rapport_ErnestMind_{slugify(report_custom_title_line1)}.pdf",
|
| 945 |
+
mime="application/pdf",
|
| 946 |
+
use_container_width=True
|
| 947 |
+
)
|
| 948 |
+
|
| 949 |
+
with col_excel:
|
| 950 |
+
try:
|
| 951 |
+
excel_exporter = ExcelExporter(report_content)
|
| 952 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx") as tmp_excel_file:
|
| 953 |
+
excel_output_path = tmp_excel_file.name
|
| 954 |
+
|
| 955 |
+
excel_exporter.export_excel(excel_output_path)
|
| 956 |
+
with open(excel_output_path, "rb") as f:
|
| 957 |
+
excel_data = f.read()
|
| 958 |
+
st.download_button(
|
| 959 |
+
label=txt("download_excel_button"),
|
| 960 |
+
data=excel_data,
|
| 961 |
+
file_name=f"Rapport_ErnestMind_{slugify(report_custom_title_line1)}.xlsx",
|
| 962 |
+
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
| 963 |
+
use_container_width=True
|
| 964 |
+
)
|
| 965 |
+
os.unlink(excel_output_path)
|
| 966 |
+
except ImportError:
|
| 967 |
+
st.error(txt("excel_dependency_error"))
|
| 968 |
+
except Exception as e:
|
| 969 |
+
st.error(f"{txt('error_creating_excel')}: {e}")
|
| 970 |
+
else:
|
| 971 |
+
st.info(txt("upload_data_for_report_prompt")) # Reuse this message to indicate that a trained model is needed
|
| 972 |
+
|
| 973 |
+
|
| 974 |
+
elif st.session_state.current_section == "data_prep_title":
|
| 975 |
+
st.header(f"🛠️ {txt('data_prep_title')}")
|
| 976 |
+
|
| 977 |
+
st.info(txt("data_prep_intro"))
|
| 978 |
+
|
| 979 |
+
st.subheader(txt("missing_values_imputation_title"))
|
| 980 |
+
imputation_method = st.selectbox(txt("select_imputation_method"), ["mean", "median", "knn"])
|
| 981 |
+
if st.button(txt("apply_imputation_button")):
|
| 982 |
+
st.session_state.df = impute_missing_values(st.session_state.df, method=imputation_method)
|
| 983 |
+
st.success(txt("imputation_applied").format(method=imputation_method))
|
| 984 |
+
update_discussion_state() # Save state after modification
|
| 985 |
+
st.rerun()
|
| 986 |
+
|
| 987 |
+
st.subheader(txt("feature_scaling_title"))
|
| 988 |
+
scaling_method = st.selectbox(txt("select_scaling_method"), ["standard", "minmax"])
|
| 989 |
+
if st.button(txt("apply_scaling_button")):
|
| 990 |
+
st.session_state.df = scale_features(st.session_state.df, method=scaling_method)
|
| 991 |
+
st.success(txt("scaling_applied").format(method=scaling_method))
|
| 992 |
+
update_discussion_state()
|
| 993 |
+
st.rerun()
|
| 994 |
+
|
| 995 |
+
st.subheader(txt("outlier_detection_title"))
|
| 996 |
+
if st.button(txt("detect_outliers_button")):
|
| 997 |
+
st.session_state.df = detect_outliers_isolation_forest(st.session_state.df)
|
| 998 |
+
st.success(txt("outliers_detected"))
|
| 999 |
+
st.write(st.session_state.df.head())
|
| 1000 |
+
update_discussion_state()
|
| 1001 |
+
st.rerun()
|
| 1002 |
+
|
| 1003 |
+
st.subheader(txt("clustering_title"))
|
| 1004 |
+
n_clusters = st.number_input(txt("select_num_clusters"), min_value=2, value=3)
|
| 1005 |
+
if st.button(txt("apply_clustering_button")):
|
| 1006 |
+
st.session_state.df = perform_kmeans_clustering(st.session_state.df, n_clusters=n_clusters)
|
| 1007 |
+
st.success(txt("clustering_applied").format(n_clusters=n_clusters))
|
| 1008 |
+
st.write(st.session_state.df.head())
|
| 1009 |
+
update_discussion_state()
|
| 1010 |
+
st.rerun()
|
| 1011 |
+
|
| 1012 |
+
st.subheader(txt("feature_engineering_title"))
|
| 1013 |
+
|
| 1014 |
+
# Create polynomial features
|
| 1015 |
+
st.markdown("#### Créer des caractéristiques polynômiales")
|
| 1016 |
+
degree = st.number_input("Degré", min_value=2, max_value=5, value=2)
|
| 1017 |
+
if st.button("Créer des caractéristiques polynômiales"):
|
| 1018 |
+
st.session_state.df = create_polynomial_features(st.session_state.df, degree)
|
| 1019 |
+
st.success(f"Caractéristiques polynômiales de degré {degree} créées.")
|
| 1020 |
+
update_discussion_state()
|
| 1021 |
+
st.rerun()
|
| 1022 |
+
|
| 1023 |
+
# Create interaction terms
|
| 1024 |
+
st.markdown("#### Créer un terme d'interaction")
|
| 1025 |
+
num_cols = st.session_state.df.select_dtypes(include=np.number).columns
|
| 1026 |
+
col1 = st.selectbox("Première colonne", num_cols, key="interaction_col1")
|
| 1027 |
+
col2 = st.selectbox("Deuxième colonne", num_cols, key="interaction_col2")
|
| 1028 |
+
if st.button("Créer le terme d'interaction"):
|
| 1029 |
+
st.session_state.df = create_interaction_term(st.session_state.df, col1, col2)
|
| 1030 |
+
st.success(f"Terme d'interaction créé entre {col1} et {col2}.")
|
| 1031 |
+
update_discussion_state()
|
| 1032 |
+
st.rerun()
|
| 1033 |
+
|
| 1034 |
+
# Extract date/time features
|
| 1035 |
+
st.markdown("#### Extraire des caractéristiques de date/heure")
|
| 1036 |
+
# Convert potential date columns if not already
|
| 1037 |
+
for col in st.session_state.df.columns:
|
| 1038 |
+
if 'date' in col.lower():
|
| 1039 |
+
try:
|
| 1040 |
+
st.session_state.df[col] = pd.to_datetime(st.session_state.df[col], errors='coerce')
|
| 1041 |
+
except Exception:
|
| 1042 |
+
pass # Leave as is if not a valid date
|
| 1043 |
+
|
| 1044 |
+
datetime_cols = st.session_state.df.select_dtypes(include=['datetime64']).columns
|
| 1045 |
+
if len(datetime_cols) > 0:
|
| 1046 |
+
datetime_col = st.selectbox("Sélectionner la colonne de date/heure", datetime_cols)
|
| 1047 |
+
features_to_extract = st.multiselect("Sélectionner les caractéristiques à extraire", ["year", "month", "day", "hour", "minute", "second"])
|
| 1048 |
+
if st.button("Extraire les caractéristiques"):
|
| 1049 |
+
st.session_state.df = extract_datetime_features(st.session_state.df, datetime_col, features_to_extract)
|
| 1050 |
+
st.success("Caractéristiques de date/heure extraites.")
|
| 1051 |
+
update_discussion_state()
|
| 1052 |
+
st.rerun()
|
| 1053 |
+
else:
|
| 1054 |
+
st.info("Aucune colonne de date/heure détectée.")
|
| 1055 |
+
|
| 1056 |
+
elif st.session_state.current_section == "ai_prediction_title":
|
| 1057 |
+
st.header(f"🧠 {txt('ai_prediction_title')}")
|
| 1058 |
+
|
| 1059 |
+
if st.session_state.df is not None:
|
| 1060 |
+
st.info(txt("ai_prediction_intro"))
|
| 1061 |
+
|
| 1062 |
+
st.subheader(txt("model_training"))
|
| 1063 |
+
num_cols = st.session_state.df.select_dtypes(include=np.number).columns
|
| 1064 |
+
|
| 1065 |
+
# Filter columns that are not purely identifying for the target
|
| 1066 |
+
possible_target_cols = [col for col in num_cols if len(st.session_state.df[col].unique()) > 1]
|
| 1067 |
+
|
| 1068 |
+
if not possible_target_cols:
|
| 1069 |
+
st.warning(txt("no_suitable_target_column"))
|
| 1070 |
+
else:
|
| 1071 |
+
target_column = st.selectbox(txt("select_target_column"), options=possible_target_cols)
|
| 1072 |
+
model_type = st.selectbox(txt("select_model_type"), options=[txt("regression_model"), txt("classification_model")])
|
| 1073 |
+
|
| 1074 |
+
if st.button(txt("train_model_button")):
|
| 1075 |
+
if target_column:
|
| 1076 |
+
with st.spinner(txt("training_model_in_progress")):
|
| 1077 |
+
st.session_state.target_column = target_column
|
| 1078 |
+
st.session_state.model_type = model_type
|
| 1079 |
+
|
| 1080 |
+
X = st.session_state.df.drop(columns=[target_column])
|
| 1081 |
+
y = st.session_state.df[target_column]
|
| 1082 |
+
|
| 1083 |
+
# Encode categorical features
|
| 1084 |
+
X = pd.get_dummies(X, drop_first=True)
|
| 1085 |
+
|
| 1086 |
+
# Ensure X does not contain the target column after get_dummies if it was numeric
|
| 1087 |
+
if target_column in X.columns:
|
| 1088 |
+
X = X.drop(columns=[target_column])
|
| 1089 |
+
|
| 1090 |
+
# Handle remaining columns with NaN if they appear after get_dummies or other operations
|
| 1091 |
+
X = X.fillna(X.mean(numeric_only=True))
|
| 1092 |
+
|
| 1093 |
+
# Split data
|
| 1094 |
+
if len(X) > 1:
|
| 1095 |
+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
| 1096 |
+
else: # Case where there is not enough data to split
|
| 1097 |
+
X_train, X_test = X, X
|
| 1098 |
+
y_train, y_test = y, y
|
| 1099 |
+
|
| 1100 |
+
st.session_state.X_test_data = X_test
|
| 1101 |
+
st.session_state.y_test_data = y_test
|
| 1102 |
+
|
| 1103 |
+
if model_type == txt("regression_model"):
|
| 1104 |
+
model = LGBMRegressor(random_state=42)
|
| 1105 |
+
else:
|
| 1106 |
+
# For classification, ensure y is of int/categorical type
|
| 1107 |
+
if pd.api.types.is_numeric_dtype(y):
|
| 1108 |
+
y = y.astype('category').cat.codes # Convert to numeric codes for LGBM
|
| 1109 |
+
model = LGBMClassifier(random_state=42)
|
| 1110 |
+
|
| 1111 |
+
model.fit(X_train, y_train)
|
| 1112 |
+
st.session_state.model = model
|
| 1113 |
+
|
| 1114 |
+
# Calculate SHAP values
|
| 1115 |
+
try:
|
| 1116 |
+
explainer = shap.Explainer(model, X_train) # Use X_train for the explainer
|
| 1117 |
+
shap_values = explainer(X_test)
|
| 1118 |
+
st.session_state.shap_values_data = shap_values
|
| 1119 |
+
st.success(txt("model_trained_success"))
|
| 1120 |
+
except Exception as e:
|
| 1121 |
+
st.error(f"{txt('error_shap_calculation')}: {e}. Le modèle est entraîné mais les valeurs SHAP n'ont pas pu être calculées.")
|
| 1122 |
+
st.session_state.shap_values_data = None # Reset if error
|
| 1123 |
+
|
| 1124 |
+
update_discussion_state() # Save state after model training
|
| 1125 |
+
st.rerun() # To refresh model performance
|
| 1126 |
+
|
| 1127 |
+
else:
|
| 1128 |
+
st.warning(txt("select_target_column_prompt"))
|
| 1129 |
+
|
| 1130 |
+
if st.session_state.model:
|
| 1131 |
+
st.subheader(txt("model_performance"))
|
| 1132 |
+
|
| 1133 |
+
y_pred = st.session_state.model.predict(st.session_state.X_test_data)
|
| 1134 |
+
|
| 1135 |
+
if st.session_state.model_type == txt("regression_model"):
|
| 1136 |
+
rmse = np.sqrt(mean_squared_error(st.session_state.y_test_data, y_pred))
|
| 1137 |
+
r2 = r2_score(st.session_state.y_test_data, y_pred)
|
| 1138 |
+
st.metric(label=txt("rmse"), value=f"{rmse:.2f}")
|
| 1139 |
+
st.metric(label=txt("r2_score"), value=f"{r2:.2f}")
|
| 1140 |
+
else:
|
| 1141 |
+
accuracy = accuracy_score(st.session_state.y_test_data, y_pred.round())
|
| 1142 |
+
st.metric(label=txt("accuracy"), value=f"{accuracy:.2f}")
|
| 1143 |
+
|
| 1144 |
+
# Display SHAP visualizations only if they have been calculated
|
| 1145 |
+
if st.session_state.shap_values_data is not None:
|
| 1146 |
+
generate_ai_report_visualizations(st.session_state.df, st.session_state.shap_values_data, st.session_state.X_test_data)
|
| 1147 |
+
else:
|
| 1148 |
+
st.info(txt("shap_not_available"))
|
| 1149 |
+
|
| 1150 |
+
|
| 1151 |
+
else:
|
| 1152 |
+
st.warning(txt("upload_data_for_report_prompt"))
|
| 1153 |
+
|
| 1154 |
+
elif st.session_state.current_section == "report_generation_title":
|
| 1155 |
+
st.header(f"📄 {txt('report_generation_title')}")
|
| 1156 |
+
|
| 1157 |
+
if st.session_state.df is not None and st.session_state.model is not None:
|
| 1158 |
+
st.info(txt("report_generation_intro"))
|
| 1159 |
+
|
| 1160 |
+
# Create a ReportContent instance with session data
|
| 1161 |
+
report_content = ReportContent(
|
| 1162 |
+
df=st.session_state.df,
|
| 1163 |
+
model=st.session_state.model,
|
| 1164 |
+
shap_values_data=st.session_state.shap_values_data,
|
| 1165 |
+
X_test_data=st.session_state.X_test_data,
|
| 1166 |
+
y_test_data=st.session_state.y_test_data,
|
| 1167 |
+
target_column=st.session_state.target_column,
|
| 1168 |
+
model_type=st.session_state.model_type,
|
| 1169 |
+
txt_func=txt
|
| 1170 |
+
)
|
| 1171 |
+
|
| 1172 |
+
# Report customization
|
| 1173 |
+
st.subheader(txt("report_customization_title"))
|
| 1174 |
+
report_custom_title_line1 = st.text_input(txt("custom_report_title_line1_label"), value=txt("default_report_title_line1"))
|
| 1175 |
+
report_custom_subtitle = st.text_input(txt("custom_report_subtitle_label"), value=txt("default_report_subtitle"))
|
| 1176 |
+
report_custom_footer = st.text_area(txt("custom_report_footer_label"), value=txt("default_report_footer").format(date=datetime.now().strftime("%Y-%m-%d")))
|
| 1177 |
+
|
| 1178 |
+
selected_sections = st.multiselect(
|
| 1179 |
+
txt("select_report_sections"),
|
| 1180 |
+
options=report_content.available_report_sections,
|
| 1181 |
+
default=report_content.available_report_sections
|
| 1182 |
+
)
|
| 1183 |
+
|
| 1184 |
+
report_options = {
|
| 1185 |
+
"report_custom_title_line1": report_custom_title_line1,
|
| 1186 |
+
"report_custom_subtitle": report_custom_subtitle,
|
| 1187 |
+
"report_custom_footer": report_custom_footer,
|
| 1188 |
+
"selected_report_sections": selected_sections
|
| 1189 |
+
}
|
| 1190 |
+
|
| 1191 |
+
# Update options for the ReportContent instance
|
| 1192 |
+
report_content.update_report_options(report_options)
|
| 1193 |
+
|
| 1194 |
+
col_pdf, col_excel = st.columns(2)
|
| 1195 |
+
|
| 1196 |
+
# PDF download button
|
| 1197 |
+
with col_pdf:
|
| 1198 |
+
pdf_exporter = PdfExporter(report_content)
|
| 1199 |
+
pdf_output = io.BytesIO()
|
| 1200 |
+
pdf_exporter.export_pdf(pdf_output)
|
| 1201 |
+
st.download_button(
|
| 1202 |
+
label=txt("download_pdf_button"),
|
| 1203 |
+
data=pdf_output.getvalue(),
|
| 1204 |
+
file_name=f"Rapport_ErnestMind_{slugify(report_custom_title_line1)}.pdf",
|
| 1205 |
+
mime="application/pdf",
|
| 1206 |
+
use_container_width=True
|
| 1207 |
+
)
|
| 1208 |
+
|
| 1209 |
+
# Excel download button
|
| 1210 |
+
with col_excel:
|
| 1211 |
+
try:
|
| 1212 |
+
excel_exporter = ExcelExporter(report_content)
|
| 1213 |
+
# Use a temporary file on the file system for xlsxwriter
|
| 1214 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx") as tmp_excel_file:
|
| 1215 |
+
excel_output_path = tmp_excel_file.name
|
| 1216 |
+
|
| 1217 |
+
excel_exporter.export_excel(excel_output_path)
|
| 1218 |
+
with open(excel_output_path, "rb") as f:
|
| 1219 |
+
excel_data = f.read()
|
| 1220 |
+
st.download_button(
|
| 1221 |
+
label=txt("download_excel_button"),
|
| 1222 |
+
data=excel_data,
|
| 1223 |
+
file_name=f"Rapport_ErnestMind_{slugify(report_custom_title_line1)}.xlsx",
|
| 1224 |
+
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
| 1225 |
+
use_container_width=True
|
| 1226 |
+
)
|
| 1227 |
+
os.unlink(excel_output_path) # Delete temporary file
|
| 1228 |
+
except ImportError:
|
| 1229 |
+
st.error(txt("excel_dependency_error"))
|
| 1230 |
+
except Exception as e:
|
| 1231 |
+
st.error(f"{txt('error_creating_excel')}: {e}")
|
| 1232 |
+
|
| 1233 |
+
else:
|
| 1234 |
+
st.warning(txt("upload_data_for_report_prompt"))
|
| 1235 |
+
|
| 1236 |
+
# --- Global footer (new: moved from sidebar) ---
|
| 1237 |
+
st.markdown("---") # Visual separator
|
| 1238 |
+
col_footer_priv, col_footer_legal, col_footer_terms, col_footer_about, col_footer_help = st.columns(5)
|
| 1239 |
+
with col_footer_priv:
|
| 1240 |
+
if st.button(txt("footer_privacy_policy"), key="footer_privacy_policy_button_main", use_container_width=True):
|
| 1241 |
+
static_page("privacy_policy_section")
|
| 1242 |
+
st.rerun()
|
| 1243 |
+
with col_footer_legal:
|
| 1244 |
+
if st.button(txt("footer_legal_notices"), key="footer_legal_notices_button_main", use_container_width=True):
|
| 1245 |
+
static_page("legal_notices_section")
|
| 1246 |
+
st.rerun()
|
| 1247 |
+
with col_footer_terms:
|
| 1248 |
+
if st.button(txt("footer_terms_of_use"), key="footer_terms_of_use_button_main", use_container_width=True):
|
| 1249 |
+
static_page("terms_of_use_section")
|
| 1250 |
+
st.rerun()
|
| 1251 |
+
with col_footer_about:
|
| 1252 |
+
if st.button(txt("footer_about_ernestmind"), key="footer_about_ernestmind_button_main", use_container_width=True):
|
| 1253 |
+
static_page("about_ernestmind_section")
|
| 1254 |
+
st.rerun()
|
| 1255 |
+
with col_footer_help:
|
| 1256 |
+
if st.button(txt("read_more_need_help"), key="footer_help_button_main", use_container_width=True):
|
| 1257 |
+
static_page("help_section")
|
| 1258 |
+
st.rerun()
|
| 1259 |
+
|
| 1260 |
+
# Note : Static pages are now displayed by the `elif st.session_state.show_static_page:` logic
|
| 1261 |
+
# and the contents are pulled from `translations_report_content.py` or `translations_base.py`.
|
a6ea61c8-951a-413a-ba9d-7365d83fbd4d/gitforge/coolo/report_excel_exporter.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
+
import os
|
| 4 |
+
import io
|
| 5 |
+
import base64
|
| 6 |
+
import tempfile
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
import seaborn as sns
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
from PIL import Image
|
| 11 |
+
import json
|
| 12 |
+
from matplotlib.colors import LinearSegmentedColormap
|
| 13 |
+
|
| 14 |
+
# Importation de la fonction de traduction et des traductions
|
| 15 |
+
from translations import txt, translations, slugify # Importe slugify depuis translations
|
| 16 |
+
# xlsxwriter est utilisé pour des fonctionnalités avancées comme le style
|
| 17 |
+
try:
|
| 18 |
+
import xlsxwriter
|
| 19 |
+
except ImportError:
|
| 20 |
+
xlsxwriter = None
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class ExcelExporter:
|
| 24 |
+
"""Class to export reports in Excel format."""
|
| 25 |
+
|
| 26 |
+
def __init__(self, report_content):
|
| 27 |
+
self.content = report_content
|
| 28 |
+
self.report_title_line1 = self.content.report_options['report_custom_title_line1']
|
| 29 |
+
self.report_title_line2 = self.content.report_title_line2
|
| 30 |
+
self.report_subtitle = self.content.report_options['report_custom_subtitle']
|
| 31 |
+
self.report_footer_text = self.content.report_options['report_custom_footer']
|
| 32 |
+
self.report_logo_path = self.content.custom_logo_path
|
| 33 |
+
|
| 34 |
+
def export_excel(self, tmpfile_path):
|
| 35 |
+
"""Exports the report in Excel format."""
|
| 36 |
+
if xlsxwriter is None:
|
| 37 |
+
raise ImportError(f"{txt('Erreur : Une dépendance nécessaire pour ce format est manquante. Veuillez installer `xlsxwriter` via `pip install xlsxwriter`')}")
|
| 38 |
+
|
| 39 |
+
try:
|
| 40 |
+
workbook = xlsxwriter.Workbook(tmpfile_path, {'in_memory': True})
|
| 41 |
+
|
| 42 |
+
# Définition des formats
|
| 43 |
+
title_format = workbook.add_format({'bold': True, 'font_size': 20, 'align': 'center', 'valign': 'vcenter'})
|
| 44 |
+
subheader_format = workbook.add_format({'bold': True, 'font_size': 14, 'bg_color': '#D9D9D9', 'border': 1})
|
| 45 |
+
text_format = workbook.add_format({'font_size': 11, 'align': 'left', 'valign': 'top', 'text_wrap': True})
|
| 46 |
+
|
| 47 |
+
# Création des feuilles
|
| 48 |
+
if txt("report_cover_page_title") in self.content.selected_report_sections:
|
| 49 |
+
cover_sheet = workbook.add_worksheet(txt("report_cover_page_title"))
|
| 50 |
+
cover_sheet.merge_range('A1:B1', self.report_title_line1, title_format)
|
| 51 |
+
cover_sheet.merge_range('A2:B2', self.report_title_line2, title_format)
|
| 52 |
+
cover_sheet.merge_range('A3:B3', self.report_subtitle, text_format)
|
| 53 |
+
|
| 54 |
+
if txt("about_this_report_title") in self.content.selected_report_sections:
|
| 55 |
+
about_sheet = workbook.add_worksheet(txt("about_this_report_title"))
|
| 56 |
+
about_sheet.write(0, 0, txt("about_this_report_title"), subheader_format)
|
| 57 |
+
about_sheet.write(1, 0, self.content.get_about_this_report_content(), text_format)
|
| 58 |
+
|
| 59 |
+
if txt("data_info_section") in self.content.selected_report_sections:
|
| 60 |
+
data_info_sheet = workbook.add_worksheet(txt("data_info_section"))
|
| 61 |
+
data_info_sheet.write(0, 0, txt("data_info_section"), subheader_format)
|
| 62 |
+
data_info_sheet.write(1, 0, self.content.get_data_info_content(), text_format)
|
| 63 |
+
|
| 64 |
+
if txt("report_data_quality_title") in self.content.selected_report_sections:
|
| 65 |
+
data_quality_sheet = workbook.add_worksheet(txt("report_data_quality_title"))
|
| 66 |
+
data_quality_sheet.write(0, 0, txt("report_data_quality_title"), subheader_format)
|
| 67 |
+
data_quality_sheet.write(1, 0, self.content.get_data_quality_content(), text_format)
|
| 68 |
+
|
| 69 |
+
if txt("report_kpis_infographic_title") in self.content.selected_report_sections:
|
| 70 |
+
kpis_sheet = workbook.add_worksheet(txt("report_kpis_infographic_title"))
|
| 71 |
+
kpis_sheet.write(0, 0, txt("report_kpis_infographic_title"), subheader_format)
|
| 72 |
+
# Ajout des KPIs
|
| 73 |
+
kpis_content = self.content.get_kpis_content()
|
| 74 |
+
kpis_sheet.write(1, 0, kpis_content, text_format)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
if txt("report_ai_observations_title") in self.content.selected_report_sections:
|
| 78 |
+
observations_sheet = workbook.add_worksheet(txt("report_ai_observations_title"))
|
| 79 |
+
observations_sheet.write(0, 0, txt("report_ai_observations_title"), subheader_format)
|
| 80 |
+
observations_sheet.write(1, 0, self.content.get_strategic_observations_content(), text_format)
|
| 81 |
+
|
| 82 |
+
if txt("report_ai_recommendations_title") in self.content.selected_report_sections:
|
| 83 |
+
recommendations_sheet = workbook.add_worksheet(txt("report_ai_recommendations_title"))
|
| 84 |
+
recommendations_sheet.write(0, 0, txt("report_ai_recommendations_title"), subheader_format)
|
| 85 |
+
recommendations_sheet.write(1, 0, self.content.get_strategic_recommendations_content(), text_format)
|
| 86 |
+
|
| 87 |
+
if txt("report_methodology_annex_title") in self.content.selected_report_sections:
|
| 88 |
+
methodology_sheet = workbook.add_worksheet(txt("report_methodology_annex_title"))
|
| 89 |
+
methodology_sheet.write(0, 0, txt("report_methodology_annex_title"), subheader_format)
|
| 90 |
+
methodology_sheet.write(1, 0, self.content.get_methodology_content(), text_format)
|
| 91 |
+
|
| 92 |
+
if txt("report_glossary_annex_title") in self.content.selected_report_sections:
|
| 93 |
+
glossary_sheet = workbook.add_worksheet(txt("report_glossary_annex_title"))
|
| 94 |
+
glossary_sheet.write(0, 0, txt("report_glossary_annex_title"), subheader_format)
|
| 95 |
+
glossary_sheet.write(1, 0, self.content.get_glossary_content(), text_format)
|
| 96 |
+
glossary_sheet.set_column(0, 0, 100)
|
| 97 |
+
glossary_sheet.set_row(1, 150)
|
| 98 |
+
|
| 99 |
+
if txt("report_about_app_annex_title") in self.content.selected_report_sections:
|
| 100 |
+
about_app_sheet = workbook.add_worksheet(txt("report_about_app_annex_title"))
|
| 101 |
+
about_app_sheet.write(0, 0, txt("report_about_app_annex_title"), subheader_format)
|
| 102 |
+
about_app_text = self.content.get_about_app_content()
|
| 103 |
+
about_app_text_formatted = about_app_text.replace('**', '')
|
| 104 |
+
about_app_sheet.write(1, 0, about_app_text_formatted, text_format)
|
| 105 |
+
about_app_sheet.set_column(0, 0, 100)
|
| 106 |
+
about_app_sheet.set_row(1, 400) # Increased height for all content
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
# --- Footer global ---
|
| 110 |
+
footer_text_lines = self.content.footer_lines
|
| 111 |
+
for sheet_name in workbook.sheetnames:
|
| 112 |
+
worksheet = workbook.get_worksheet_by_name(sheet_name)
|
| 113 |
+
# Ajouter un pied de page à chaque feuille (peut être fait plus proprement avec un gestionnaire d'événements si xlsxwriter le permet)
|
| 114 |
+
# Pour un exemple simple, ajoutons-le aux dernières lignes utilisées
|
| 115 |
+
last_row = worksheet.dim_rowmax + 2
|
| 116 |
+
worksheet.write(last_row, 0, self.report_footer_text, text_format)
|
| 117 |
+
|
| 118 |
+
workbook.close()
|
| 119 |
+
|
| 120 |
+
except Exception as e:
|
| 121 |
+
st.error(f"Erreur lors de la création du fichier Excel : {e}")
|
a6ea61c8-951a-413a-ba9d-7365d83fbd4d/gitforge/coolo/report_generator.py
ADDED
|
@@ -0,0 +1,461 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
from translations import txt, translations, slugify
|
| 5 |
+
import streamlit as st
|
| 6 |
+
import shap
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
from sklearn.metrics import mean_squared_error, accuracy_score, r2_score
|
| 9 |
+
from lightgbm import LGBMClassifier, LGBMRegressor
|
| 10 |
+
import os
|
| 11 |
+
import tempfile
|
| 12 |
+
import re
|
| 13 |
+
from collections import Counter
|
| 14 |
+
from matplotlib.colors import LinearSegmentedColormap
|
| 15 |
+
from sklearn.cluster import KMeans
|
| 16 |
+
from sklearn.ensemble import IsolationForest
|
| 17 |
+
|
| 18 |
+
class AIRecommender:
|
| 19 |
+
"""
|
| 20 |
+
Génère des observations stratégiques et des recommandations actionnables
|
| 21 |
+
basées sur l'analyse des données.
|
| 22 |
+
"""
|
| 23 |
+
def __init__(self, df: pd.DataFrame, shap_values_data=None, X_test_data=None, txt_func=None, target_column=None):
|
| 24 |
+
self.df = df
|
| 25 |
+
self.ai_knowledge_profile = {}
|
| 26 |
+
self.shap_values_data = shap_values_data
|
| 27 |
+
self.X_test_data = X_test_data
|
| 28 |
+
self.txt = txt_func if txt_func else (lambda key, **kwargs: key)
|
| 29 |
+
self.target_column = target_column
|
| 30 |
+
self._extract_insights()
|
| 31 |
+
self.observations = self._generate_potential_strategic_observations()
|
| 32 |
+
self.recommendations = self._generate_strategic_recommendations()
|
| 33 |
+
|
| 34 |
+
def _extract_insights(self):
|
| 35 |
+
"""
|
| 36 |
+
Phase 1 : Extraction d'Insights Contextuels Approfondis.
|
| 37 |
+
Cette méthode peuple le ai_knowledge_profile avec des observations
|
| 38 |
+
spécifiques au domaine immobilier.
|
| 39 |
+
"""
|
| 40 |
+
df = self.df.copy()
|
| 41 |
+
|
| 42 |
+
# Aperçu des données
|
| 43 |
+
self.ai_knowledge_profile['num_rows'] = df.shape[0]
|
| 44 |
+
self.ai_knowledge_profile['num_cols'] = df.shape[1]
|
| 45 |
+
self.ai_knowledge_profile['column_types'] = df.dtypes.apply(lambda x: x.name).to_dict()
|
| 46 |
+
self.ai_knowledge_profile['duplicate_rows'] = df.duplicated().sum()
|
| 47 |
+
|
| 48 |
+
# Valeurs manquantes
|
| 49 |
+
missing_data = df.isnull().sum()
|
| 50 |
+
self.ai_knowledge_profile['missing_cols'] = missing_data[missing_data > 0].index.tolist()
|
| 51 |
+
if self.target_column and df[self.target_column].isnull().any():
|
| 52 |
+
self.ai_knowledge_profile['missing_target_values'] = True
|
| 53 |
+
else:
|
| 54 |
+
self.ai_knowledge_profile['missing_target_values'] = False
|
| 55 |
+
|
| 56 |
+
# Détection d'anomalies (Isolation Forest)
|
| 57 |
+
num_df = df.select_dtypes(include=np.number).dropna()
|
| 58 |
+
if not num_df.empty:
|
| 59 |
+
try:
|
| 60 |
+
model = IsolationForest(random_state=42)
|
| 61 |
+
outliers = model.fit_predict(num_df)
|
| 62 |
+
self.ai_knowledge_profile['num_outliers'] = list(outliers).count(-1)
|
| 63 |
+
self.ai_knowledge_profile['outlier_percentage'] = (self.ai_knowledge_profile['num_outliers'] / len(df)) * 100
|
| 64 |
+
except Exception:
|
| 65 |
+
self.ai_knowledge_profile['num_outliers'] = 0
|
| 66 |
+
self.ai_knowledge_profile['outlier_percentage'] = 0.0
|
| 67 |
+
|
| 68 |
+
# Analyse des colonnes numériques
|
| 69 |
+
num_cols = df.select_dtypes(include=np.number).columns
|
| 70 |
+
for col in num_cols:
|
| 71 |
+
self.ai_knowledge_profile[f'median_of_{col}'] = df[col].median()
|
| 72 |
+
self.ai_knowledge_profile[f'mean_of_{col}'] = df[col].mean()
|
| 73 |
+
self.ai_knowledge_profile[f'std_of_{col}'] = df[col].std()
|
| 74 |
+
|
| 75 |
+
# Détection d'asymétrie
|
| 76 |
+
if len(df[col].dropna()) > 1:
|
| 77 |
+
skewness = df[col].skew()
|
| 78 |
+
if abs(skewness) > 1: # Seuil pour considérer une distribution asymétrique
|
| 79 |
+
self.ai_knowledge_profile[f'skewed_distribution_{col}'] = True
|
| 80 |
+
else:
|
| 81 |
+
self.ai_knowledge_profile[f'skewed_distribution_{col}'] = False
|
| 82 |
+
else:
|
| 83 |
+
self.ai_knowledge_profile[f'skewed_distribution_{col}'] = False
|
| 84 |
+
|
| 85 |
+
# Faible variance
|
| 86 |
+
if df[col].nunique() < 5 and len(df[col].dropna()) > 0: # Moins de 5 valeurs uniques pour une colonne numérique
|
| 87 |
+
if df[col].std() < 0.1: # Seuil arbitraire pour faible écart-type
|
| 88 |
+
self.ai_knowledge_profile[f'low_variance_{col}'] = True
|
| 89 |
+
else:
|
| 90 |
+
self.ai_knowledge_profile[f'low_variance_{col}'] = False
|
| 91 |
+
else:
|
| 92 |
+
self.ai_knowledge_profile[f'low_variance_{col}'] = False
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# Analyse des colonnes catégorielles
|
| 96 |
+
cat_cols = df.select_dtypes(include=['object', 'category']).columns
|
| 97 |
+
for col in cat_cols:
|
| 98 |
+
top_value = df[col].mode()[0]
|
| 99 |
+
self.ai_knowledge_profile[f'top_category_in_{col}'] = top_value
|
| 100 |
+
self.ai_knowledge_profile[f'top_category_count_in_{col}'] = df[col].value_counts().get(top_value, 0)
|
| 101 |
+
|
| 102 |
+
# Déséquilibre de classes
|
| 103 |
+
value_counts = df[col].value_counts(normalize=True)
|
| 104 |
+
if value_counts.min() < 0.1 and len(value_counts) > 1: # Si une classe représente moins de 10%
|
| 105 |
+
self.ai_knowledge_profile[f'categorical_imbalance_{col}'] = True
|
| 106 |
+
self.ai_knowledge_profile[f'minority_category_{col}'] = value_counts.idxmin()
|
| 107 |
+
else:
|
| 108 |
+
self.ai_knowledge_profile[f'categorical_imbalance_{col}'] = False
|
| 109 |
+
|
| 110 |
+
# Cardinalité élevée
|
| 111 |
+
if df[col].nunique() / df.shape[0] > 0.5: # Si plus de 50% de valeurs uniques
|
| 112 |
+
self.ai_knowledge_profile[f'high_cardinality_{col}'] = df[col].nunique()
|
| 113 |
+
else:
|
| 114 |
+
self.ai_knowledge_profile[f'high_cardinality_{col}'] = None
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
# Clustering (K-Means)
|
| 118 |
+
if not num_df.empty and len(num_df) > 1 and len(num_df) >= 3: # Au moins 3 points pour 3 clusters
|
| 119 |
+
try:
|
| 120 |
+
kmeans = KMeans(n_clusters=3, random_state=42, n_init=10)
|
| 121 |
+
clusters = kmeans.fit_predict(num_df)
|
| 122 |
+
self.ai_knowledge_profile['cluster_means'] = kmeans.cluster_centers_.tolist()
|
| 123 |
+
except Exception:
|
| 124 |
+
self.ai_knowledge_profile['cluster_means'] = []
|
| 125 |
+
else:
|
| 126 |
+
self.ai_knowledge_profile['cluster_means'] = []
|
| 127 |
+
|
| 128 |
+
# Analyse des dates
|
| 129 |
+
datetime_cols = df.select_dtypes(include=['datetime64']).columns
|
| 130 |
+
for col in datetime_cols:
|
| 131 |
+
if len(df[col].dropna()) > 1:
|
| 132 |
+
# Vérifier si la colonne est effectivement une série temporelle avec une tendance
|
| 133 |
+
# Une détection simple ici : si la moyenne des différences consécutives est non nulle
|
| 134 |
+
# et que les valeurs ne sont pas toutes identiques.
|
| 135 |
+
diffs = df[col].diff().dropna()
|
| 136 |
+
if not diffs.empty and diffs.mean() != 0 and df[col].nunique() > 1:
|
| 137 |
+
self.ai_knowledge_profile[f'time_series_trend_{col}'] = True
|
| 138 |
+
else:
|
| 139 |
+
self.ai_knowledge_profile[f'time_series_trend_{col}'] = False
|
| 140 |
+
else:
|
| 141 |
+
self.ai_knowledge_profile[f'time_series_trend_{col}'] = False
|
| 142 |
+
|
| 143 |
+
# Multicolinéarité
|
| 144 |
+
if num_df.shape[1] > 1:
|
| 145 |
+
corr_matrix = num_df.corr().abs()
|
| 146 |
+
# Compter les paires avec une corrélation très élevée (excluant la diagonale)
|
| 147 |
+
upper_tri = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(bool))
|
| 148 |
+
to_drop = [column for column in upper_tri.columns if any(upper_tri[column] > 0.9)] # Seuil > 0.9 pour forte multicolinéarité
|
| 149 |
+
if len(to_drop) > 0:
|
| 150 |
+
self.ai_knowledge_profile['multicollinearity'] = True
|
| 151 |
+
self.ai_knowledge_profile['highly_correlated_cols'] = to_drop
|
| 152 |
+
else:
|
| 153 |
+
self.ai_knowledge_profile['multicollinearity'] = False
|
| 154 |
+
else:
|
| 155 |
+
self.ai_knowledge_profile['multicollinearity'] = False
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _generate_potential_strategic_observations(self):
|
| 159 |
+
"""
|
| 160 |
+
Phase 2 : Génération d'observations stratégiques en se basant sur les insights.
|
| 161 |
+
Retourne une liste des observations les plus pertinentes.
|
| 162 |
+
"""
|
| 163 |
+
observations_list = []
|
| 164 |
+
|
| 165 |
+
# Règle 1: Observation sur les valeurs manquantes
|
| 166 |
+
if self.ai_knowledge_profile.get('missing_cols'):
|
| 167 |
+
observations_list.append(self.txt("obs_missing_values").format(
|
| 168 |
+
cols=", ".join(self.ai_knowledge_profile['missing_cols'])
|
| 169 |
+
))
|
| 170 |
+
|
| 171 |
+
# Règle 2: Observation sur les valeurs aberrantes
|
| 172 |
+
outlier_percent = self.ai_knowledge_profile.get('outlier_percentage', 0)
|
| 173 |
+
if outlier_percent > 5.0:
|
| 174 |
+
observations_list.append(self.txt("obs_high_outlier_rate").format(
|
| 175 |
+
percent=f"{outlier_percent:.2f}"
|
| 176 |
+
))
|
| 177 |
+
elif outlier_percent > 0:
|
| 178 |
+
observations_list.append(self.txt("obs_outliers_exist").format(
|
| 179 |
+
percent=f"{outlier_percent:.2f}"
|
| 180 |
+
))
|
| 181 |
+
|
| 182 |
+
# Règle 3: Observation sur les clusters de données
|
| 183 |
+
if self.ai_knowledge_profile.get('cluster_means'):
|
| 184 |
+
observations_list.append(self.txt("obs_data_clusters"))
|
| 185 |
+
|
| 186 |
+
# Règle 4: Observation sur la distribution des prix (s'il y a une colonne de prix)
|
| 187 |
+
price_col = None
|
| 188 |
+
for col in self.df.columns:
|
| 189 |
+
if re.search(r'prix|price', col, re.IGNORECASE) and self.df[col].dtype in ['int64', 'float64']:
|
| 190 |
+
price_col = col
|
| 191 |
+
break
|
| 192 |
+
|
| 193 |
+
if price_col:
|
| 194 |
+
median_price = self.ai_knowledge_profile.get(f'median_of_{price_col}')
|
| 195 |
+
if median_price:
|
| 196 |
+
observations_list.append(self.txt("obs_median_price").format(
|
| 197 |
+
price=median_price, col=price_col
|
| 198 |
+
))
|
| 199 |
+
|
| 200 |
+
# Règle 5: Observation sur la corrélation
|
| 201 |
+
# Cette règle est maintenant intégrée directement dans _extract_insights
|
| 202 |
+
num_df = self.df.select_dtypes(include=np.number)
|
| 203 |
+
if num_df.shape[1] > 1:
|
| 204 |
+
corr_matrix = num_df.corr().abs()
|
| 205 |
+
high_corr_pairs = []
|
| 206 |
+
# On cherche des corrélations > 0.8 (moins strict que multicolinéarité)
|
| 207 |
+
for col1 in corr_matrix.columns:
|
| 208 |
+
for col2 in corr_matrix.index:
|
| 209 |
+
if col1 != col2 and corr_matrix.loc[col1, col2] > 0.8:
|
| 210 |
+
pair = sorted([col1, col2])
|
| 211 |
+
if pair not in high_corr_pairs: # Éviter les doublons (A,B) et (B,A)
|
| 212 |
+
high_corr_pairs.append(pair)
|
| 213 |
+
|
| 214 |
+
if high_corr_pairs:
|
| 215 |
+
observations_list.append(self.txt("obs_high_correlation").format(
|
| 216 |
+
pairs=", ".join([f"({p[0]}, {p[1]})" for p in high_corr_pairs])
|
| 217 |
+
))
|
| 218 |
+
|
| 219 |
+
# Nouvelles observations basées sur les insights
|
| 220 |
+
for col in self.df.select_dtypes(include=np.number).columns:
|
| 221 |
+
if self.ai_knowledge_profile.get(f'skewed_distribution_{col}'):
|
| 222 |
+
observations_list.append(self.txt("obs_skewed_distribution").format(col=col))
|
| 223 |
+
if self.ai_knowledge_profile.get(f'low_variance_{col}'):
|
| 224 |
+
observations_list.append(self.txt("obs_low_variance").format(col=col))
|
| 225 |
+
|
| 226 |
+
for col in self.df.select_dtypes(include=['object', 'category']).columns:
|
| 227 |
+
if self.ai_knowledge_profile.get(f'categorical_imbalance_{col}'):
|
| 228 |
+
observations_list.append(self.txt("obs_categorical_imbalance").format(
|
| 229 |
+
col=col, minority=self.ai_knowledge_profile[f'minority_category_{col}']
|
| 230 |
+
))
|
| 231 |
+
if self.ai_knowledge_profile.get(f'high_cardinality_{col}'):
|
| 232 |
+
observations_list.append(self.txt("obs_high_cardinality").format(
|
| 233 |
+
col=col, count=self.ai_knowledge_profile[f'high_cardinality_{col}']
|
| 234 |
+
))
|
| 235 |
+
|
| 236 |
+
for col in self.df.select_dtypes(include=['datetime64']).columns:
|
| 237 |
+
if self.ai_knowledge_profile.get(f'time_series_trend_{col}'):
|
| 238 |
+
observations_list.append(self.txt("obs_time_series_trend").format(col=col))
|
| 239 |
+
|
| 240 |
+
if self.ai_knowledge_profile.get('missing_target_values') and self.target_column:
|
| 241 |
+
observations_list.append(self.txt("obs_missing_target_values").format(target_col=self.target_column))
|
| 242 |
+
|
| 243 |
+
if self.ai_knowledge_profile.get('duplicate_rows') > 0:
|
| 244 |
+
observations_list.append(self.txt("obs_duplicate_rows").format(count=self.ai_knowledge_profile['duplicate_rows']))
|
| 245 |
+
|
| 246 |
+
if self.ai_knowledge_profile.get('multicollinearity'):
|
| 247 |
+
observations_list.append(self.txt("obs_multicollinearity"))
|
| 248 |
+
|
| 249 |
+
# Sélectionner les 5 observations les plus pertinentes (ou moins si moins de 5)
|
| 250 |
+
# Ceci est une simplification. Dans une vraie application, on pourrait prioriser
|
| 251 |
+
# ou utiliser des scores pour choisir les plus impactantes.
|
| 252 |
+
return observations_list[:5] # Limiter à 5 observations
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def _generate_strategic_recommendations(self):
|
| 256 |
+
"""
|
| 257 |
+
Génère les recommandations stratégiques en se basant sur les insights.
|
| 258 |
+
Retourne une liste des recommandations les plus pertinentes.
|
| 259 |
+
"""
|
| 260 |
+
recommendations_list = []
|
| 261 |
+
|
| 262 |
+
# Règle 1: Recommandation sur la préparation des données
|
| 263 |
+
if self.ai_knowledge_profile.get('missing_cols') or self.ai_knowledge_profile.get('num_outliers', 0) > 0:
|
| 264 |
+
recommendations_list.append(self.txt("rec_data_prep_focus"))
|
| 265 |
+
|
| 266 |
+
# Règle 2: Recommandation sur l'analyse des caractéristiques SHAP
|
| 267 |
+
if self.shap_values_data is not None and self.X_test_data is not None and not self.X_test_data.empty:
|
| 268 |
+
try:
|
| 269 |
+
shap_df = pd.DataFrame(self.shap_values_data.values, columns=self.X_test_data.columns)
|
| 270 |
+
mean_abs_shap = shap_df.abs().mean().sort_values(ascending=False)
|
| 271 |
+
top_features = mean_abs_shap.index[:3].tolist()
|
| 272 |
+
if top_features:
|
| 273 |
+
recommendations_list.append(self.txt("rec_focus_on_features").format(
|
| 274 |
+
features=", ".join(top_features)
|
| 275 |
+
))
|
| 276 |
+
except Exception:
|
| 277 |
+
pass # Ignorer si SHAP a échoué
|
| 278 |
+
|
| 279 |
+
# Règle 3: Recommandation pour les modèles de clustering
|
| 280 |
+
if self.ai_knowledge_profile.get('cluster_means'):
|
| 281 |
+
recommendations_list.append(self.txt("rec_explore_segmentation"))
|
| 282 |
+
|
| 283 |
+
# Règle 4: Recommandation pour la détection d'anomalies
|
| 284 |
+
if self.ai_knowledge_profile.get('num_outliers', 0) > 0:
|
| 285 |
+
recommendations_list.append(self.txt("rec_investigate_anomalies"))
|
| 286 |
+
|
| 287 |
+
# Règle 5: Recommandation sur la collecte de données supplémentaires
|
| 288 |
+
if self.df.shape[0] < 500: # Seuil arbitraire
|
| 289 |
+
recommendations_list.append(self.txt("rec_collect_more_data"))
|
| 290 |
+
|
| 291 |
+
# Règle 6: Recommandation pour l'ingénierie des caractéristiques
|
| 292 |
+
num_cols = self.df.select_dtypes(include=np.number).columns
|
| 293 |
+
if len(num_cols) >= 2:
|
| 294 |
+
recommendations_list.append(self.txt("rec_feature_engineering_terms"))
|
| 295 |
+
|
| 296 |
+
# Nouvelles recommandations basées sur les insights
|
| 297 |
+
for col in self.df.select_dtypes(include=np.number).columns:
|
| 298 |
+
if self.ai_knowledge_profile.get(f'skewed_distribution_{col}'):
|
| 299 |
+
recommendations_list.append(self.txt("rec_handle_skewness").format(col=col))
|
| 300 |
+
if self.ai_knowledge_profile.get(f'low_variance_{col}'):
|
| 301 |
+
recommendations_list.append(self.txt("rec_remove_low_variance_features").format(col=col))
|
| 302 |
+
|
| 303 |
+
for col in self.df.select_dtypes(include=['object', 'category']).columns:
|
| 304 |
+
if self.ai_knowledge_profile.get(f'categorical_imbalance_{col}'):
|
| 305 |
+
recommendations_list.append(self.txt("rec_balance_categories").format(col=col))
|
| 306 |
+
if self.ai_knowledge_profile.get(f'high_cardinality_{col}'):
|
| 307 |
+
recommendations_list.append(self.txt("rec_dimensionality_reduction").format(col=col))
|
| 308 |
+
|
| 309 |
+
for col in self.df.select_dtypes(include=['datetime64']).columns:
|
| 310 |
+
if self.ai_knowledge_profile.get(f'time_series_trend_{col}'):
|
| 311 |
+
recommendations_list.append(self.txt("rec_time_series_model"))
|
| 312 |
+
|
| 313 |
+
if self.ai_knowledge_profile.get('missing_target_values') and self.target_column:
|
| 314 |
+
recommendations_list.append(self.txt("rec_clean_target_missing").format(target_col=self.target_column))
|
| 315 |
+
|
| 316 |
+
if self.ai_knowledge_profile.get('duplicate_rows') > 0:
|
| 317 |
+
recommendations_list.append(self.txt("rec_deduplicate_data"))
|
| 318 |
+
|
| 319 |
+
if self.ai_knowledge_profile.get('multicollinearity'):
|
| 320 |
+
recommendations_list.append(self.txt("rec_address_multicollinearity"))
|
| 321 |
+
|
| 322 |
+
# Sélectionner les 5 recommandations les plus pertinentes (ou moins si moins de 5)
|
| 323 |
+
return recommendations_list[:5] # Limiter à 5 recommandations
|
| 324 |
+
|
| 325 |
+
def get_strategic_observations(self):
|
| 326 |
+
return self.observations
|
| 327 |
+
|
| 328 |
+
def get_strategic_recommendations(self):
|
| 329 |
+
return self.recommendations
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
class ReportContent:
|
| 333 |
+
"""
|
| 334 |
+
Génère le contenu des différentes sections du rapport.
|
| 335 |
+
"""
|
| 336 |
+
def __init__(self, df: pd.DataFrame, model=None, shap_values_data=None, X_test_data=None, y_test_data=None, target_column=None, model_type=None, txt_func=None):
|
| 337 |
+
self.df = df
|
| 338 |
+
self.model = model
|
| 339 |
+
self.shap_values_data = shap_values_data
|
| 340 |
+
self.X_test_data = X_test_data
|
| 341 |
+
self.y_test_data = y_test_data
|
| 342 |
+
self.target_column = target_column
|
| 343 |
+
self.model_type = model_type
|
| 344 |
+
self.txt = txt_func if txt_func else (lambda key, **kwargs: key)
|
| 345 |
+
self.report_options = {}
|
| 346 |
+
self.custom_logo_path = None
|
| 347 |
+
self.report_title_line2 = txt("default_report_title_line2")
|
| 348 |
+
|
| 349 |
+
self.ai_recommender = AIRecommender(
|
| 350 |
+
df=self.df,
|
| 351 |
+
shap_values_data=self.shap_values_data,
|
| 352 |
+
X_test_data=self.X_test_data,
|
| 353 |
+
txt_func=self.txt,
|
| 354 |
+
target_column=self.target_column # Passer la colonne cible au recommender
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
self.available_report_sections = [
|
| 358 |
+
txt("report_cover_page_title"),
|
| 359 |
+
txt("about_this_report_title"),
|
| 360 |
+
txt("data_info_section"),
|
| 361 |
+
txt("report_data_quality_title"),
|
| 362 |
+
txt("report_kpis_infographic_title"),
|
| 363 |
+
txt("report_ai_observations_title"),
|
| 364 |
+
txt("report_ai_recommendations_title"),
|
| 365 |
+
txt("report_methodology_annex_title"),
|
| 366 |
+
txt("report_glossary_annex_title"),
|
| 367 |
+
txt("report_about_app_annex_title")
|
| 368 |
+
]
|
| 369 |
+
|
| 370 |
+
def update_report_options(self, options):
|
| 371 |
+
self.report_options = options
|
| 372 |
+
self.selected_report_sections = options.get('selected_report_sections', [])
|
| 373 |
+
|
| 374 |
+
def get_about_this_report_content(self):
|
| 375 |
+
return self.txt("about_this_report_content")
|
| 376 |
+
|
| 377 |
+
def get_data_info_content(self):
|
| 378 |
+
overview = {
|
| 379 |
+
"Numéro de lignes": self.df.shape[0],
|
| 380 |
+
"Numéro de colonnes": self.df.shape[1],
|
| 381 |
+
"Types de colonnes": self.df.dtypes.to_dict()
|
| 382 |
+
}
|
| 383 |
+
content = self.txt("data_info_intro") + "\n\n"
|
| 384 |
+
for key, value in overview.items():
|
| 385 |
+
content += f"- **{key}** : {value}\n"
|
| 386 |
+
return content
|
| 387 |
+
|
| 388 |
+
def get_data_quality_content(self):
|
| 389 |
+
missing_summary = self.df.isnull().sum()
|
| 390 |
+
missing_summary = missing_summary[missing_summary > 0].to_dict()
|
| 391 |
+
|
| 392 |
+
outliers = detect_outliers_isolation_forest(self.df.copy())
|
| 393 |
+
num_outliers = (outliers['outlier_score'] == -1).sum()
|
| 394 |
+
|
| 395 |
+
content = self.txt("data_quality_intro") + "\n\n"
|
| 396 |
+
content += self.txt("missing_values_title") + ":\n"
|
| 397 |
+
if missing_summary:
|
| 398 |
+
for col, count in missing_summary.items():
|
| 399 |
+
content += f"- **{col}** : {count} ({count/len(self.df)*100:.2f}%)\n"
|
| 400 |
+
else:
|
| 401 |
+
content += self.txt("no_missing_values") + "\n"
|
| 402 |
+
|
| 403 |
+
content += "\n" + self.txt("outlier_detection_title") + ":\n"
|
| 404 |
+
content += f"- {num_outliers} outliers détectés ({num_outliers/len(self.df)*100:.2f}%).\n"
|
| 405 |
+
|
| 406 |
+
return content
|
| 407 |
+
|
| 408 |
+
def get_kpis_content(self):
|
| 409 |
+
if self.model and self.y_test_data is not None and self.X_test_data is not None and not self.X_test_data.empty:
|
| 410 |
+
y_pred = self.model.predict(self.X_test_data)
|
| 411 |
+
|
| 412 |
+
content = self.txt("kpis_intro") + "\n\n"
|
| 413 |
+
|
| 414 |
+
if self.model_type == self.txt("regression_model"):
|
| 415 |
+
rmse = np.sqrt(mean_squared_error(self.y_test_data, y_pred))
|
| 416 |
+
r2 = r2_score(self.y_test_data, y_pred)
|
| 417 |
+
content += f"- **{self.txt('rmse')}** : {rmse:.2f}\n"
|
| 418 |
+
content += f"- **{self.txt('r2_score')}** : {r2:.2f}\n"
|
| 419 |
+
else:
|
| 420 |
+
accuracy = accuracy_score(self.y_test_data, y_pred.round())
|
| 421 |
+
content += f"- **{self.txt('accuracy')}** : {accuracy:.2f}\n"
|
| 422 |
+
|
| 423 |
+
return content
|
| 424 |
+
else:
|
| 425 |
+
return self.txt("no_kpis_available")
|
| 426 |
+
|
| 427 |
+
def get_strategic_observations_content(self):
|
| 428 |
+
observations = self.ai_recommender.get_strategic_observations()
|
| 429 |
+
if observations:
|
| 430 |
+
content = self.txt('res_observations_intro') + "\n\n"
|
| 431 |
+
content += "\n".join([f"- {obs}" for obs in observations])
|
| 432 |
+
return content
|
| 433 |
+
else:
|
| 434 |
+
return self.txt("no_observations_available")
|
| 435 |
+
|
| 436 |
+
def get_strategic_recommendations_content(self):
|
| 437 |
+
recommendations = self.ai_recommender.get_strategic_recommendations()
|
| 438 |
+
if recommendations:
|
| 439 |
+
content = ""
|
| 440 |
+
for rec in recommendations:
|
| 441 |
+
content += f"- {rec}\n"
|
| 442 |
+
return content
|
| 443 |
+
else:
|
| 444 |
+
return self.txt("no_recommendations_available")
|
| 445 |
+
|
| 446 |
+
def get_methodology_content(self):
|
| 447 |
+
"""Returns the methodology content for the report."""
|
| 448 |
+
content = self.txt("methodology_intro") + "\n\n"
|
| 449 |
+
content += self.txt("methodology_data_prep") + "\n"
|
| 450 |
+
content += self.txt("methodology_model_training") + "\n"
|
| 451 |
+
content += self.txt("methodology_shap_explanation") + "\n"
|
| 452 |
+
content += self.txt("methodology_report_generation") + "\n"
|
| 453 |
+
content += self.txt("methodology_data_confidentiality") + "\n"
|
| 454 |
+
return content
|
| 455 |
+
|
| 456 |
+
def get_glossary_content(self):
|
| 457 |
+
"""Returns the glossary content for the report."""
|
| 458 |
+
return self.txt("glossary_full_text")
|
| 459 |
+
|
| 460 |
+
def get_about_app_content(self):
|
| 461 |
+
return self.txt("about_app_content")
|
a6ea61c8-951a-413a-ba9d-7365d83fbd4d/gitforge/coolo/report_pdf_exporter.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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empfile
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
import seaborn as sns
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
from reportlab.lib.pagesizes import letter, A4
|
| 11 |
+
from reportlab.pdfgen import canvas
|
| 12 |
+
from reportlab.lib.utils import ImageReader
|
| 13 |
+
from PIL import Image
|
| 14 |
+
import json
|
| 15 |
+
from matplotlib.colors import LinearSegmentedColormap
|
| 16 |
+
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_RIGHT
|
| 17 |
+
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
|
| 18 |
+
from reportlab.platypus import Paragraph, Spacer
|
| 19 |
+
from reportlab.lib.colors import black, blue, green, red, HexColor
|
| 20 |
+
from reportlab.platypus import Table, TableStyle
|
| 21 |
+
|
| 22 |
+
from translations import txt, slugify
|
| 23 |
+
from report_generator import ReportContent
|
| 24 |
+
|
| 25 |
+
class PdfCore:
|
| 26 |
+
"""
|
| 27 |
+
Gère la logique de base de la création de PDF en utilisant ReportLab.
|
| 28 |
+
Fournit des méthodes pour la gestion du canevas, des styles, des en-têtes/pieds de page,
|
| 29 |
+
et l'ajout générique de texte, images et tableaux.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
def __init__(self, canvas_obj, report_title_line1, report_title_line2, report_footer_text):
|
| 33 |
+
"""
|
| 34 |
+
Initialise PdfCore avec un objet canvas ReportLab et des informations de rapport.
|
| 35 |
+
"""
|
| 36 |
+
self.c = canvas_obj
|
| 37 |
+
self.report_title_line1 = report_title_line1
|
| 38 |
+
self.report_title_line2 = report_title_line2
|
| 39 |
+
self.report_footer_text = report_footer_text
|
| 40 |
+
self.width, self.height = A4
|
| 41 |
+
self.margin = 50
|
| 42 |
+
self.styles = getSampleStyleSheet()
|
| 43 |
+
self.styles.add(ParagraphStyle(name='TitleStyle', fontSize=20, leading=24, alignment=TA_CENTER, fontName='Helvetica-Bold'))
|
| 44 |
+
self.styles.add(ParagraphStyle(name='SubtitleStyle', fontSize=14, leading=16, alignment=TA_CENTER))
|
| 45 |
+
self.styles.add(ParagraphStyle(name='SectionTitleStyle', fontSize=16, leading=20, alignment=TA_LEFT, fontName='Helvetica-Bold'))
|
| 46 |
+
self.styles.add(ParagraphStyle(name='ParagraphStyle', fontSize=10, leading=12, alignment=TA_LEFT, text_wrap=True))
|
| 47 |
+
self.c.setPageSize(A4)
|
| 48 |
+
|
| 49 |
+
def add_header(self, page_num):
|
| 50 |
+
"""Ajoute l'en-tête de page."""
|
| 51 |
+
self.c.setFont('Helvetica-Bold', 10)
|
| 52 |
+
self.c.drawString(self.margin, self.height - 30, f"{self.report_title_line1} {self.report_title_line2}")
|
| 53 |
+
self.c.drawString(self.width - self.margin - 20, self.height - 30, f"Page {page_num}")
|
| 54 |
+
|
| 55 |
+
def add_footer(self):
|
| 56 |
+
"""Ajoute le pied de page."""
|
| 57 |
+
self.c.setFont('Helvetica', 8)
|
| 58 |
+
self.c.drawString(self.margin, 30, self.report_footer_text)
|
| 59 |
+
|
| 60 |
+
def add_section_title(self, y_cursor, title):
|
| 61 |
+
"""Ajoute un titre de section au PDF."""
|
| 62 |
+
p_title = Paragraph(title, self.styles['SectionTitleStyle'])
|
| 63 |
+
p_title.wrapOn(self.c, self.width - 2 * self.margin, self.height)
|
| 64 |
+
p_title.drawOn(self.c, self.margin, y_cursor - p_title.height)
|
| 65 |
+
return y_cursor - p_title.height - 10
|
| 66 |
+
|
| 67 |
+
def add_paragraph(self, y_cursor, text):
|
| 68 |
+
"""Ajoute un paragraphe de texte au PDF."""
|
| 69 |
+
p_text = Paragraph(text, self.styles['ParagraphStyle'])
|
| 70 |
+
p_text.wrapOn(self.c, self.width - 2 * self.margin, self.height)
|
| 71 |
+
if y_cursor - p_text.height < self.margin:
|
| 72 |
+
self.c.showPage()
|
| 73 |
+
y_cursor = self.height - self.margin
|
| 74 |
+
p_text.drawOn(self.c, self.margin, y_cursor - p_text.height)
|
| 75 |
+
return y_cursor - p_text.height - 10
|
| 76 |
+
|
| 77 |
+
def add_image_from_plt(self, y_cursor, fig):
|
| 78 |
+
"""Ajoute une image à partir d'une figure Matplotlib."""
|
| 79 |
+
img_buffer = io.BytesIO()
|
| 80 |
+
fig.savefig(img_buffer, format='png', bbox_inches='tight')
|
| 81 |
+
img_buffer.seek(0)
|
| 82 |
+
img = ImageReader(img_buffer)
|
| 83 |
+
aspect = img.getSize()[1] / img.getSize()[0]
|
| 84 |
+
img_width = self.width * 0.8
|
| 85 |
+
img_height = img_width * aspect
|
| 86 |
+
|
| 87 |
+
if y_cursor - img_height < self.margin:
|
| 88 |
+
self.c.showPage()
|
| 89 |
+
y_cursor = self.height - self.margin
|
| 90 |
+
|
| 91 |
+
self.c.drawImage(img, self.margin + (self.width - 2*self.margin - img_width)/2, y_cursor - img_height, width=img_width, height=img_height)
|
| 92 |
+
plt.close(fig) # Ferme la figure pour libérer la mémoire
|
| 93 |
+
return y_cursor - img_height - 10
|
| 94 |
+
|
| 95 |
+
class PdfExporter:
|
| 96 |
+
"""Class to export reports in PDF format."""
|
| 97 |
+
|
| 98 |
+
def __init__(self, report_content):
|
| 99 |
+
self.content = report_content
|
| 100 |
+
self.report_title_line1 = self.content.report_options['report_custom_title_line1']
|
| 101 |
+
self.report_title_line2 = self.content.report_title_line2
|
| 102 |
+
self.report_subtitle = self.content.report_options['report_custom_subtitle']
|
| 103 |
+
self.report_footer_text = self.content.report_options['report_custom_footer']
|
| 104 |
+
|
| 105 |
+
def export_pdf(self, buffer):
|
| 106 |
+
c = canvas.Canvas(buffer, pagesize=A4)
|
| 107 |
+
pdf_core = PdfCore(c, self.report_title_line1, self.report_title_line2, self.report_footer_text)
|
| 108 |
+
page_num = 1
|
| 109 |
+
|
| 110 |
+
for section in self.content.selected_report_sections:
|
| 111 |
+
if section == txt("report_cover_page_title"):
|
| 112 |
+
pdf_core.c.showPage()
|
| 113 |
+
y_cursor = pdf_core.height / 2
|
| 114 |
+
p_title = Paragraph(self.report_title_line1, pdf_core.styles['TitleStyle'])
|
| 115 |
+
p_subtitle = Paragraph(self.report_title_line2, pdf_core.styles['TitleStyle'])
|
| 116 |
+
p_custom_subtitle = Paragraph(self.report_subtitle, pdf_core.styles['SubtitleStyle'])
|
| 117 |
+
|
| 118 |
+
p_title.wrapOn(c, pdf_core.width, pdf_core.height)
|
| 119 |
+
p_title.drawOn(c, pdf_core.margin, y_cursor)
|
| 120 |
+
y_cursor -= p_title.height
|
| 121 |
+
p_subtitle.wrapOn(c, pdf_core.width, pdf_core.height)
|
| 122 |
+
p_subtitle.drawOn(c, pdf_core.margin, y_cursor)
|
| 123 |
+
y_cursor -= p_subtitle.height
|
| 124 |
+
p_custom_subtitle.wrapOn(c, pdf_core.width, pdf_core.height)
|
| 125 |
+
p_custom_subtitle.drawOn(c, pdf_core.margin, y_cursor)
|
| 126 |
+
|
| 127 |
+
elif section == txt("about_this_report_title"):
|
| 128 |
+
pdf_core.c.showPage()
|
| 129 |
+
page_num += 1
|
| 130 |
+
pdf_core.add_header(page_num)
|
| 131 |
+
pdf_core.add_footer()
|
| 132 |
+
y_cursor = pdf_core.height - pdf_core.margin
|
| 133 |
+
y_cursor = pdf_core.add_section_title(y_cursor, txt("about_this_report_title"))
|
| 134 |
+
y_cursor = pdf_core.add_paragraph(y_cursor, self.content.get_about_this_report_content())
|
| 135 |
+
|
| 136 |
+
elif section == txt("data_info_section"):
|
| 137 |
+
pdf_core.c.showPage()
|
| 138 |
+
page_num += 1
|
| 139 |
+
pdf_core.add_header(page_num)
|
| 140 |
+
pdf_core.add_footer()
|
| 141 |
+
y_cursor = pdf_core.height - pdf_core.margin
|
| 142 |
+
y_cursor = pdf_core.add_section_title(y_cursor, txt("data_info_section"))
|
| 143 |
+
y_cursor = pdf_core.add_paragraph(y_cursor, self.content.get_data_info_content())
|
| 144 |
+
|
| 145 |
+
elif section == txt("report_data_quality_title"):
|
| 146 |
+
pdf_core.c.showPage()
|
| 147 |
+
page_num += 1
|
| 148 |
+
pdf_core.add_header(page_num)
|
| 149 |
+
pdf_core.add_footer()
|
| 150 |
+
y_cursor = pdf_core.height - pdf_core.margin
|
| 151 |
+
y_cursor = pdf_core.add_section_title(y_cursor, txt("report_data_quality_title"))
|
| 152 |
+
y_cursor = pdf_core.add_paragraph(y_cursor, self.content.get_data_quality_content())
|
| 153 |
+
|
| 154 |
+
elif section == txt("report_kpis_infographic_title"):
|
| 155 |
+
pdf_core.c.showPage()
|
| 156 |
+
page_num += 1
|
| 157 |
+
pdf_core.add_header(page_num)
|
| 158 |
+
pdf_core.add_footer()
|
| 159 |
+
y_cursor = pdf_core.height - pdf_core.margin
|
| 160 |
+
y_cursor = pdf_core.add_section_title(y_cursor, txt("report_kpis_infographic_title"))
|
| 161 |
+
y_cursor = pdf_core.add_paragraph(y_cursor, self.content.get_kpis_content())
|
| 162 |
+
|
| 163 |
+
elif section == txt("report_ai_observations_title"):
|
| 164 |
+
pdf_core.c.showPage()
|
| 165 |
+
page_num += 1
|
| 166 |
+
pdf_core.add_header(page_num)
|
| 167 |
+
pdf_core.add_footer()
|
| 168 |
+
y_cursor = pdf_core.height - pdf_core.margin
|
| 169 |
+
y_cursor = pdf_core.add_section_title(y_cursor, txt("report_ai_observations_title"))
|
| 170 |
+
y_cursor = pdf_core.add_paragraph(y_cursor, self.content.get_strategic_observations_content())
|
| 171 |
+
c.showPage()
|
| 172 |
+
page_num += 1
|
| 173 |
+
|
| 174 |
+
elif section == txt("report_ai_recommendations_title"):
|
| 175 |
+
y_cursor = pdf_core.height - pdf_core.margin
|
| 176 |
+
y_cursor = pdf_core.add_section_title(y_cursor, txt("report_ai_recommendations_title"))
|
| 177 |
+
y_cursor = pdf_core.add_paragraph(y_cursor, self.content.get_strategic_recommendations_content())
|
| 178 |
+
c.showPage()
|
| 179 |
+
page_num += 1
|
| 180 |
+
|
| 181 |
+
# Annexes
|
| 182 |
+
elif section == txt("report_methodology_annex_title"):
|
| 183 |
+
y_cursor = pdf_core.height - pdf_core.margin
|
| 184 |
+
y_cursor = pdf_core.add_section_title(y_cursor, txt("report_methodology_annex_title"))
|
| 185 |
+
y_cursor = pdf_core.add_paragraph(y_cursor, self.content.get_methodology_content())
|
| 186 |
+
c.showPage()
|
| 187 |
+
page_num += 1
|
| 188 |
+
|
| 189 |
+
elif section == txt("report_glossary_annex_title"):
|
| 190 |
+
y_cursor = pdf_core.height - pdf_core.margin
|
| 191 |
+
y_cursor = pdf_core.add_section_title(y_cursor, txt("report_glossary_annex_title"))
|
| 192 |
+
y_cursor = pdf_core.add_paragraph(y_cursor, self.content.get_glossary_content())
|
| 193 |
+
c.showPage()
|
| 194 |
+
page_num += 1
|
| 195 |
+
|
| 196 |
+
elif section == txt("report_about_app_annex_title"):
|
| 197 |
+
y_cursor = pdf_core.height - pdf_core.margin
|
| 198 |
+
y_cursor = pdf_core.add_section_title(y_cursor, txt("report_about_app_annex_title"))
|
| 199 |
+
y_cursor = pdf_core.add_paragraph(y_cursor, self.content.get_about_app_content())
|
| 200 |
+
c.showPage()
|
| 201 |
+
page_num += 1
|
| 202 |
+
|
| 203 |
+
c.save()
|
a6ea61c8-951a-413a-ba9d-7365d83fbd4d/gitforge/coolo/translations.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import unicodedata
|
| 3 |
+
import string
|
| 4 |
+
import re
|
| 5 |
+
import hashlib
|
| 6 |
+
import json
|
| 7 |
+
import pandas as pd
|
| 8 |
+
import numpy as np
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# Importation des dictionnaires de traduction spécifiques
|
| 13 |
+
from translations_base import fr_translations_base # load_users et save_users ne sont plus importés ici
|
| 14 |
+
from translations_data_processing import fr_translations_data_processing
|
| 15 |
+
from translations_ai_report import fr_translations_ai_report
|
| 16 |
+
from translations_report_content import fr_translations_report_content
|
| 17 |
+
|
| 18 |
+
# Variable globale pour stocker le code de la langue actuelle
|
| 19 |
+
_current_language_code = 'fr'
|
| 20 |
+
|
| 21 |
+
# --- Données de Démonstration Fictives ---
|
| 22 |
+
# Ces données sont intégrées directement pour le mode démo.
|
| 23 |
+
# Elles représentent un petit jeu de données immobilier avec des types variés.
|
| 24 |
+
demo_data_fr = {
|
| 25 |
+
"ID_Propriete": [101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115],
|
| 26 |
+
"Type_Propriete": ["Appartement", "Maison", "Appartement", "Maison", "Appartement", "Studio", "Maison", "Appartement", "Maison", "Appartement", "Studio", "Maison", "Appartement", "Maison", "Loft"],
|
| 27 |
+
"Surface_m2": [75, 120, 90, 150, 60, 30, 180, 85, 130, 70, 35, 200, 95, 160, 100],
|
| 28 |
+
"Nombre_Pieces": [3, 5, 4, 6, 2, 1, 7, 3, 5, 3, 1, 8, 4, 6, 3],
|
| 29 |
+
"Prix": [350000, 600000, 420000, 750000, 280000, 180000, 900000, 380000, 650000, 320000, 195000, 1100000, 450000, 800000, 500000],
|
| 30 |
+
"Date_Construction": ["2005-01-15", "1998-06-20", "2010-03-01", "1975-11-10", "2015-08-22", "2020-02-01", "1960-04-05", "2008-09-12", "1985-07-30", "2012-05-01", "2021-01-01", "1950-02-15", "2000-11-20", "1970-03-25", "2018-04-10"],
|
| 31 |
+
"Localisation": ["Paris", "Lyon", "Marseille", "Toulouse", "Nice", "Bordeaux", "Nantes", "Strasbourg", "Montpellier", "Lille", "Rennes", "Reims", "Le Havre", "Saint-Étienne", "Dijon"],
|
| 32 |
+
"Latitude": [48.8566, 45.7640, 43.2965, 43.6047, 43.7102, 44.8378, 47.2184, 48.5734, 43.6108, 50.6292, 48.1173, 49.2583, 49.4944, 45.4397, 47.3220],
|
| 33 |
+
"Longitude": [2.3522, 4.8357, 5.3698, 1.4442, 7.2620, -0.5792, -1.5536, 7.7521, 3.8767, 3.0573, -1.6778, 4.0317, 0.1077, 4.3899, 5.0415],
|
| 34 |
+
"Description": [
|
| 35 |
+
"Bel appartement en centre-ville, proche commodités.",
|
| 36 |
+
"Grande maison familiale avec jardin, quartier calme.",
|
| 37 |
+
"Appartement moderne avec balcon, vue imprenable.",
|
| 38 |
+
"Maison de caractère rénovée, grand terrain arboré.",
|
| 39 |
+
"Petit appartement idéal étudiant ou jeune couple.",
|
| 40 |
+
"Studio fonctionnel, lumineux, proche transports.",
|
| 41 |
+
"Propriété d'exception avec piscine, grand luxe.",
|
| 42 |
+
"Appartement traversant, lumineux, deux chambres.",
|
| 43 |
+
"Maison avec potentiel, travaux à prévoir, bon investissement.",
|
| 44 |
+
"Appartement refait à neuf, équipements modernes.",
|
| 45 |
+
"Studio étudiant avec kitchenette, très demandé.",
|
| 46 |
+
"Vaste demeure historique, cadre unique, grand parc.",
|
| 47 |
+
"Appartement spacieux, à rénover, forte demande locative.",
|
| 48 |
+
"Maison avec jardin, proche écoles et commerces.",
|
| 49 |
+
"Loft design, esprit industriel, très recherché."
|
| 50 |
+
]
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
# Fusionner tous les dictionnaires de traduction pour chaque langue
|
| 54 |
+
translations = {
|
| 55 |
+
"fr": {
|
| 56 |
+
**fr_translations_base,
|
| 57 |
+
**fr_translations_data_processing,
|
| 58 |
+
**fr_translations_ai_report,
|
| 59 |
+
**fr_translations_report_content,
|
| 60 |
+
"demo_data": demo_data_fr, # Ajout des données de démo
|
| 61 |
+
# Nouvelles observations pour enrichir le modèle AIRecommender
|
| 62 |
+
"obs_skewed_distribution": "La distribution de la colonne '{col}' est asymétrique, ce qui peut affecter les performances de certains modèles. Une transformation des données pourrait être bénéfique.",
|
| 63 |
+
"obs_categorical_imbalance": "La colonne catégorielle '{col}' présente un déséquilibre important de classes, avec la catégorie '{minority}' sous-représentée. Cela peut biaiser les prédictions pour cette classe.",
|
| 64 |
+
"obs_high_cardinality": "La colonne '{col}' a une cardinalité élevée ({count} valeurs uniques). Cela pourrait rendre l'encodage coûteux et potentiellement introduire du surapprentissage.",
|
| 65 |
+
"obs_time_series_trend": "Une tendance claire a été détectée dans la colonne de date '{col}', suggérant que le temps est un facteur important dans les variations des données.",
|
| 66 |
+
"obs_missing_target_values": "Des valeurs manquantes ont été trouvées dans la colonne cible '{target_col}'. Il est crucial de les traiter avant l'entraînement du modèle.",
|
| 67 |
+
"obs_low_variance": "La colonne '{col}' présente une très faible variance, ce qui signifie qu'elle ne contient pas beaucoup d'informations utiles pour le modèle et pourrait être retirée.",
|
| 68 |
+
"obs_duplicate_rows": "Des lignes dupliquées ({count} duplicata) ont été identifiées dans le jeu de données. Leur suppression peut améliorer la qualité de l'analyse.",
|
| 69 |
+
"obs_multicollinearity": "Une forte multicolinéarité est présente parmi les variables. Cela peut rendre l'interprétation des coefficients du modèle difficile et impacter sa stabilité.",
|
| 70 |
+
|
| 71 |
+
# Nouvelles recommandations pour enrichir le modèle AIRecommender
|
| 72 |
+
"rec_handle_skewness": "Envisagez d'appliquer une transformation logarithmique ou Box-Cox à la colonne '{col}' pour normaliser sa distribution et améliorer la performance du modèle.",
|
| 73 |
+
"rec_balance_categories": "Pour la colonne '{col}', utilisez des techniques de rééchantillonnage (suréchantillonnage ou sous-échantillonnage) pour équilibrer les classes et éviter le biais du modèle.",
|
| 74 |
+
"rec_dimensionality_reduction": "Compte tenu de la cardinalité élevée de la colonne '{col}', explorez des techniques de réduction de dimensionnalité (comme le PCA ou l'encodage d'entités) pour gérer cette variable.",
|
| 75 |
+
"rec_time_series_model": "Puisqu'une tendance temporelle a été observée, l'utilisation de modèles de séries chronologiques (ARIMA, Prophet) pourrait être plus appropriée pour des prédictions futures.",
|
| 76 |
+
"rec_clean_target_missing": "Nettoyez ou imputez soigneusement les valeurs manquantes dans la colonne cible '{target_col}' pour garantir l'intégrité de l'entraînement du modèle.",
|
| 77 |
+
"rec_remove_low_variance_features": "Supprimez la colonne '{col}' en raison de sa faible variance. Elle n'apporte pas d'informations significatives au modèle.",
|
| 78 |
+
"rec_deduplicate_data": "Supprimez les lignes dupliquées pour éviter que le modèle n'apprenne sur des observations redondantes et n'en surestime l'importance.",
|
| 79 |
+
"rec_address_multicollinearity": "Utilisez des méthodes comme l'analyse en composantes principales (PCA) ou la suppression de l'une des variables fortement corrélées pour gérer la multicolinéarité."
|
| 80 |
+
}
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
# Utility function to get translated text
|
| 84 |
+
def txt(key, **kwargs):
|
| 85 |
+
"""
|
| 86 |
+
Récupère la traduction pour une clé donnée dans la langue actuelle, avec un avertissement si non trouvée.
|
| 87 |
+
Permet également le formatage de chaînes avec des arguments nommés.
|
| 88 |
+
"""
|
| 89 |
+
global _current_language_code
|
| 90 |
+
|
| 91 |
+
# Vérifier si la clé est présente directement dans la langue actuelle
|
| 92 |
+
translation = translations[_current_language_code].get(key)
|
| 93 |
+
if translation is not None:
|
| 94 |
+
try:
|
| 95 |
+
return translation.format(**kwargs)
|
| 96 |
+
except KeyError:
|
| 97 |
+
return translation
|
| 98 |
+
|
| 99 |
+
# Si la clé n'est pas trouvée directement, chercher dans les sous-dictionnaires
|
| 100 |
+
for _, lang_dict in translations.items():
|
| 101 |
+
if key in lang_dict:
|
| 102 |
+
try:
|
| 103 |
+
return lang_dict[key].format(**kwargs)
|
| 104 |
+
except KeyError:
|
| 105 |
+
return lang_dict[key]
|
| 106 |
+
# Vérifier si la clé est dans un sous-dictionnaire comme "users" ou "demo_data"
|
| 107 |
+
for sub_key, sub_dict in lang_dict.items():
|
| 108 |
+
if isinstance(sub_dict, dict) and key in sub_dict:
|
| 109 |
+
try:
|
| 110 |
+
return sub_dict[key].format(**kwargs)
|
| 111 |
+
except KeyError:
|
| 112 |
+
return sub_dict[key]
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
return f"[{key}]"
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def set_language(lang_code):
|
| 119 |
+
"""Définit la langue actuelle."""
|
| 120 |
+
global _current_language_code
|
| 121 |
+
if lang_code in translations:
|
| 122 |
+
_current_language_code = lang_code
|
| 123 |
+
else:
|
| 124 |
+
st.warning(f"La langue '{lang_code}' n'est pas supportée. Utilisation du français par défaut.", icon="⚠️")
|
| 125 |
+
_current_language_code = 'fr'
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def slugify(value):
|
| 129 |
+
"""
|
| 130 |
+
Convertit une chaîne en un format compatible avec les noms de fichiers.
|
| 131 |
+
"""
|
| 132 |
+
value = str(value)
|
| 133 |
+
# Normalise la chaîne pour supprimer les accents et les caractères spéciaux
|
| 134 |
+
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('utf-8')
|
| 135 |
+
# Remplace les espaces et les tirets par des tirets
|
| 136 |
+
value = re.sub(r'[-\s]+', '-', value).strip('-_')
|
| 137 |
+
# Supprime les caractères non alphanumériques sauf les tirets
|
| 138 |
+
value = re.sub(r'[^\w\s-]', '', value)
|
| 139 |
+
return value.lower()
|
| 140 |
+
|
| 141 |
+
# Les fonctions _get_users_file_path, load_users, save_users ne sont plus ici
|
| 142 |
+
# Elles sont déplacées dans translations_base.py
|
a6ea61c8-951a-413a-ba9d-7365d83fbd4d/gitforge/coolo/translations_ai_report.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# translations_ai_report.py - Contient les traductions pour la prédiction IA et la génération de rapports
|
| 2 |
+
|
| 3 |
+
# Dictionnaire pour la langue française
|
| 4 |
+
fr_translations_ai_report = {
|
| 5 |
+
"model_training": "Entraînement du Modèle",
|
| 6 |
+
"select_target_column": "Sélectionnez la colonne cible",
|
| 7 |
+
"select_model_type": "Sélectionnez le type de modèle",
|
| 8 |
+
"regression_model": "Modèle de Régression",
|
| 9 |
+
"classification_model": "Modèle de Classification",
|
| 10 |
+
"train_model_button": "Entraîner le Modèle",
|
| 11 |
+
"training_model_in_progress": "Entraînement du modèle en cours...",
|
| 12 |
+
"model_trained_success": "Modèle entraîné avec succès !",
|
| 13 |
+
"feature_importance_shap": "Importance des Caractéristiques (SHAP)",
|
| 14 |
+
"shap_values_calculated": "Valeurs SHAP calculées et graphique généré.",
|
| 15 |
+
"select_target_column_prompt": "Veuillez sélectionner une colonne cible pour l'entraînement du modèle.",
|
| 16 |
+
"model_performance": "Performance du Modèle",
|
| 17 |
+
"accuracy": "Précision",
|
| 18 |
+
"rmse": "RMSE",
|
| 19 |
+
"r2_score": "Score R²",
|
| 20 |
+
"upload_data_for_report_prompt": "Veuillez télécharger un fichier de données et le préparer pour générer un rapport.",
|
| 21 |
+
"shap_summary_plot": "Graphique récapitulatif SHAP",
|
| 22 |
+
"report_customization_title": "Personnalisation du Rapport",
|
| 23 |
+
"custom_report_title_line1_label": "Titre du Rapport (Ligne 1)",
|
| 24 |
+
"custom_report_subtitle_label": "Sous-titre du Rapport",
|
| 25 |
+
"custom_report_footer_label": "Texte de Pied de Page",
|
| 26 |
+
"default_report_title_line1": "Rapport d'Analyse Automatisée",
|
| 27 |
+
"default_report_title_line2": "Généré par ErnestMind",
|
| 28 |
+
"default_report_subtitle": "Analyse de Données et Insights IA",
|
| 29 |
+
"default_report_footer": "Rapport généré le {date}. Tous droits réservés.",
|
| 30 |
+
"select_report_sections": "Sélectionnez les sections à inclure dans le rapport",
|
| 31 |
+
"download_pdf_button": "Télécharger au format PDF",
|
| 32 |
+
"download_excel_button": "Télécharger au format Excel",
|
| 33 |
+
|
| 34 |
+
# Clés pour les informations clés du rapport
|
| 35 |
+
"key_info_report_title": "Titre du rapport",
|
| 36 |
+
"key_info_app_version": "Version de l'application",
|
| 37 |
+
"key_info_targeted_sector": "Secteur ciblé",
|
| 38 |
+
"key_info_language": "Langue du rapport",
|
| 39 |
+
"key_info_table_data": "Informations Clés du Rapport",
|
| 40 |
+
"key_info_model_ai": "Informations Clés du Modèle IA",
|
| 41 |
+
|
| 42 |
+
# Nouvelles clés pour les cartes d'information
|
| 43 |
+
"card_model_status_title": "Statut du Modèle",
|
| 44 |
+
"card_model_status_desc_trained": "Le modèle est entraîné et prêt pour l'analyse.",
|
| 45 |
+
"card_model_status_desc_not_trained": "Le modèle n'est pas entraîné. Veuillez charger des données et lancer l'entraînement.",
|
| 46 |
+
"card_target_column_title": "Colonne Cible",
|
| 47 |
+
"card_target_column_desc": "La colonne {target_column} est utilisée comme variable cible.",
|
| 48 |
+
"card_target_column_desc_na": "Aucune colonne cible sélectionnée.",
|
| 49 |
+
"card_model_type_title": "Type de Modèle",
|
| 50 |
+
"card_model_type_desc": "Modèle de {model_type}.",
|
| 51 |
+
"card_model_type_desc_na": "Type de modèle non défini.",
|
| 52 |
+
|
| 53 |
+
# Nouvelles recommandations stratégiques
|
| 54 |
+
"rec_data_prep_focus": "Concentrez-vous sur la préparation des données pour améliorer la précision du modèle. Les valeurs manquantes et aberrantes peuvent fausser les résultats.",
|
| 55 |
+
"rec_explore_segmentation": "Explorez une segmentation plus fine des données à l'aide d'algorithmes de clustering (comme K-Means) pour découvrir des sous-groupes de propriétés aux caractéristiques similaires. Cela peut révéler des niches de marché inexploitées ou des tendances cachées.",
|
| 56 |
+
"rec_investigate_anomalies": "Menez une investigation plus approfondie sur les propriétés identifiées comme anomalies. Elles pourraient représenter des opportunités d'investissement uniques ou des erreurs de saisie à corriger.",
|
| 57 |
+
"rec_collect_more_data": "Vos données sont limitées. La collecte de plus d'informations (plus de lignes) ou l'ajout de nouvelles variables (plus de colonnes) pourrait considérablement améliorer la capacité prédictive du modèle et la robustesse de l'analyse.",
|
| 58 |
+
"rec_feature_engineering_terms": "Considérez la création de nouvelles caractéristiques (feature engineering) en combinant des variables existantes. Par exemple, un terme d'interaction entre la superficie et le nombre de pièces pourrait mieux capturer la valeur d'une propriété.",
|
| 59 |
+
"rec_focus_on_features": "Les caractéristiques suivantes sont les plus influentes sur les prédictions du modèle : {features}. Concentrez vos efforts d'analyse sur ces variables pour comprendre les principaux leviers de valeur.",
|
| 60 |
+
"rec_handle_skewness": "Envisagez d'appliquer une transformation logarithmique ou Box-Cox à la colonne '{col}' pour normaliser sa distribution et améliorer la performance du modèle.",
|
| 61 |
+
"rec_balance_categories": "Pour la colonne '{col}', utilisez des techniques de rééchantillonnage (suréchantillonnage ou sous-échantillonnage) pour équilibrer les classes et éviter le biais du modèle.",
|
| 62 |
+
"rec_dimensionality_reduction": "Compte tenu de la cardinalité élevée de la colonne '{col}', explorez des techniques de réduction de dimensionnalité (comme le PCA ou l'encodage d'entités) pour gérer cette variable.",
|
| 63 |
+
"rec_time_series_model": "Puisqu'une tendance temporelle a été observée, l'utilisation de modèles de séries chronologiques (ARIMA, Prophet) pourrait être plus appropriée pour des prédictions futures.",
|
| 64 |
+
"rec_clean_target_missing": "Nettoyez ou imputez soigneusement les valeurs manquantes dans la colonne cible '{target_col}' pour garantir l'intégrité de l'entraînement du modèle.",
|
| 65 |
+
"rec_remove_low_variance_features": "Supprimez la colonne '{col}' en raison de sa faible variance. Elle n'apporte pas d'informations significatives au modèle.",
|
| 66 |
+
"rec_deduplicate_data": "Supprimez les lignes dupliquées pour éviter que le modèle n'apprenne sur des observations redondantes et n'en surestime l'importance.",
|
| 67 |
+
"rec_address_multicollinearity": "Utilisez des méthodes comme l'analyse en composantes principales (PCA) ou la suppression de l'une des variables fortement corrélées pour gérer la multicolinéarité."
|
| 68 |
+
}
|
a6ea61c8-951a-413a-ba9d-7365d83fbd4d/gitforge/coolo/translations_base.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# translations_base.py - Contient les traductions de base de l'application et de l'aide
|
| 2 |
+
import hashlib
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import tempfile
|
| 6 |
+
import unicodedata # Ajout pour slugify si besoin dans ce fichier
|
| 7 |
+
import re # Ajout pour slugify si besoin dans ce fichier
|
| 8 |
+
|
| 9 |
+
# Fonctions pour gérer la persistance des utilisateurs
|
| 10 |
+
def _get_users_file_path():
|
| 11 |
+
"""Retourne le chemin du fichier JSON pour les utilisateurs."""
|
| 12 |
+
return os.path.join(tempfile.gettempdir(), 'app_users.json')
|
| 13 |
+
|
| 14 |
+
def load_users():
|
| 15 |
+
"""Charge les utilisateurs depuis le fichier JSON ou initialise avec l'admin par défaut."""
|
| 16 |
+
users_path = _get_users_file_path()
|
| 17 |
+
try:
|
| 18 |
+
if os.path.exists(users_path):
|
| 19 |
+
with open(users_path, 'r', encoding='utf-8') as f:
|
| 20 |
+
return json.load(f)
|
| 21 |
+
else:
|
| 22 |
+
# Initialiser avec l'utilisateur admin par défaut
|
| 23 |
+
default_users = {
|
| 24 |
+
"admin": {
|
| 25 |
+
"password": hashlib.sha256("admin_password".encode('utf-8')).hexdigest(),
|
| 26 |
+
"user_id": hashlib.md5("admin".encode('utf-8')).hexdigest(),
|
| 27 |
+
"profile": {},
|
| 28 |
+
"discussions": {}, # Initialise les discussions pour l'admin
|
| 29 |
+
"database_files": {} # Initialize database files for the admin
|
| 30 |
+
}
|
| 31 |
+
}
|
| 32 |
+
with open(users_path, 'w', encoding='utf-8') as f:
|
| 33 |
+
json.dump(default_users, f, ensure_ascii=False, indent=4)
|
| 34 |
+
return default_users
|
| 35 |
+
except Exception as e:
|
| 36 |
+
# Gérer l'erreur si le fichier est corrompu ou illisible
|
| 37 |
+
print(f"Erreur lors du chargement des utilisateurs: {e}. Réinitialisation du fichier des utilisateurs.")
|
| 38 |
+
default_users = {
|
| 39 |
+
"admin": {
|
| 40 |
+
"password": hashlib.sha256("admin_password".encode('utf-8')).hexdigest(),
|
| 41 |
+
"user_id": hashlib.md5("admin".encode('utf-8')).hexdigest(),
|
| 42 |
+
"profile": {},
|
| 43 |
+
"discussions": {},
|
| 44 |
+
"database_files": {}
|
| 45 |
+
}
|
| 46 |
+
}
|
| 47 |
+
with open(users_path, 'w', encoding='utf-8') as f:
|
| 48 |
+
json.dump(default_users, f, ensure_ascii=False, indent=4)
|
| 49 |
+
return default_users
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def save_users(users_data):
|
| 53 |
+
"""Sauvegarde les utilisateurs dans le fichier JSON."""
|
| 54 |
+
users_path = _get_users_file_path()
|
| 55 |
+
with open(users_path, 'w', encoding='utf-8') as f:
|
| 56 |
+
json.dump(users_data, f, ensure_ascii=False, indent=4)
|
| 57 |
+
|
| 58 |
+
# Dictionnaire pour la langue française
|
| 59 |
+
fr_translations_base = {
|
| 60 |
+
"lang_name": "Français",
|
| 61 |
+
"app_title": "ErnestMind V80 - Plateforme d'Analyse Immobilière",
|
| 62 |
+
"app_subtitle": "Plateforme IA locale et collaborative pour l'analyse de données — confidentielle, puissante, multilingue.",
|
| 63 |
+
"upload_label": "Téléchargez un fichier de données",
|
| 64 |
+
"file_uploaded_success": "Fichier téléchargé avec succès !",
|
| 65 |
+
"file_read_success": "Fichier lu et converti en DataFrame avec succès.",
|
| 66 |
+
"unsupported_file_type": "Type de fichier non supporté.",
|
| 67 |
+
"error_reading_file": "Une erreur est survenue lors de la lecture du fichier.",
|
| 68 |
+
"select_delimiter": "Sélectionnez le délimiteur pour le fichier CSV/TXT",
|
| 69 |
+
"file_details": "Détails du Fichier",
|
| 70 |
+
|
| 71 |
+
# Nouveaux modules
|
| 72 |
+
"data_diagnostic_title": "Diagnostic des Données",
|
| 73 |
+
"data_prep_title": "Préparation des Données",
|
| 74 |
+
"ai_prediction_title": "Prédiction & Rapports IA",
|
| 75 |
+
"report_generation_title": "Génération de Rapports",
|
| 76 |
+
"settings_section": "Paramètres",
|
| 77 |
+
"visualizations": "Visualisations des Données",
|
| 78 |
+
"home_section": "Accueil", # Nouvelle clé pour la section Accueil
|
| 79 |
+
"main_modules": "Modules Principaux",
|
| 80 |
+
|
| 81 |
+
# Footer
|
| 82 |
+
"footer_privacy_policy": "Politique de Confidentialité",
|
| 83 |
+
"footer_legal_notices": "Mentions Légales",
|
| 84 |
+
"footer_terms_of_use": "Conditions d'Utilisation",
|
| 85 |
+
"footer_about_ernestmind": "À Propos d'ErnestMind",
|
| 86 |
+
"help_title": "Aide et Guide d'Utilisation",
|
| 87 |
+
|
| 88 |
+
# Aide et guide
|
| 89 |
+
"help_intro_part1": """
|
| 90 |
+
**Bienvenue dans le guide d'aide d'ErnestMind !**
|
| 91 |
+
|
| 92 |
+
Pour commencer, suivez ces trois étapes simples :
|
| 93 |
+
|
| 94 |
+
1. **Télécharger un Fichier :** Utilisez le module 'Diagnostic des Données' pour téléchargez un fichier de données (CSV, XLSX, JSON, etc.) ou explorez en mode démo.
|
| 95 |
+
2. **Préparation des Données :** Une fois le fichier lu, les statistiques descriptives et un résumé des valeurs manquantes s'afficheront.
|
| 96 |
+
3. **Entraînement du Modèle :** Le système sélectionnera automatiquement une colonne numérique comme cible. Cliquez sur "Entraîner le Modèle" pour générer des insights IA et activer les autres modules.
|
| 97 |
+
""",
|
| 98 |
+
"help_our_strengths": """
|
| 99 |
+
ErnestMind est conçu pour la simplicité et la puissance. Ses points forts incluent :
|
| 100 |
+
* **Autonomie :** Traitez vos données directement sur votre machine, sans besoin de les t��lécharger sur des serveurs externes.
|
| 101 |
+
* **Puissance :** Bénéficiez d'algorithmes d'IA avancés pour l'analyse prédictive, l'explicabilité et la génération d'insights.
|
| 102 |
+
* **Simplicité :** Une interface utilisateur conçue pour être intuitive, rendant l'analyse complexe accessible à tous.
|
| 103 |
+
* **Personnalisation :** Adaptez les rapports et les analyses à vos besoins spécifiques.
|
| 104 |
+
* **Multilinguisme :** Travaillez dans la langue de votre choix pour une expérience utilisateur optimale.
|
| 105 |
+
""",
|
| 106 |
+
"read_more_need_help": "Aide", # Renommé pour être plus court pour le footer
|
| 107 |
+
"close_button": "Fermer",
|
| 108 |
+
"back_to_dashboard_button": "Retour au Tableau de Bord",
|
| 109 |
+
"help_module_data_diag_content": "Ce module offre un diagnostic rapide et complet de vos données : aperçu, statistiques descriptives, analyse des valeurs manquantes et visualisations automatiques (histogrammes, barres, matrices de corrélation, nuages de mots).",
|
| 110 |
+
"help_module_data_prep_content": "Préparez vos données pour l'analyse IA. Gérez les valeurs manquantes, les valeurs aberrantes, appliquez la mise à l'échelle des caractéristiques et créez de nouvelles fonctionnalités (polynômiales, interaction, date/heure, agrégation).",
|
| 111 |
+
"help_module_ai_pred_content": "Entraînez et évaluez des modèles d'intelligence artificielle (régression ou classification). Obtenez des métriques de performance et visualisez l'importance des caractéristiques avec les valeurs SHAP.",
|
| 112 |
+
"help_module_report_gen_content": "Générez des rapports professionnels personnalisés en formats PDF ou Excel. Incluez des observations stratégiques, des recommandations IA, des visualisations et toutes les informations clés de votre analyse.",
|
| 113 |
+
"privacy_policy_section": "Politique de Confidentialité", # Renommé pour correspondre à la clé de section
|
| 114 |
+
"privacy_policy_section_content": "Cette application est 100% locale et ne collecte aucune de vos données personnelles ou de vos fichiers. Tout est traité sur votre machine. Votre confidentialité est notre priorité absolue. Nous n'accédons ni ne stockons vos informations.",
|
| 115 |
+
"legal_notices_section": "Mentions Légales", # Renommé
|
| 116 |
+
"legal_notices_section_content": "ErnestMind V80 est une plateforme d'analyse de données en mode local. Son utilisation est soumise à nos conditions générales d'utilisation. Pour toute question, veuillez nous contacter à support@ernestmind.ai.",
|
| 117 |
+
"terms_of_use_section": "Conditions d'Utilisation", # Renommé
|
| 118 |
+
"terms_of_use_section_content": "En utilisant cette application, vous acceptez de ne pas l'utiliser à des fins illégales ou non autorisées. Vous êtes seul responsable du contenu de vos données et de leur conformité avec les lois en vigueur. Toute utilisation abusive est strictement interdite.",
|
| 119 |
+
"about_ernestmind_section": "À Propos d'ErnestMind", # Renommé
|
| 120 |
+
"about_ernestmind_section_content": "ErnestMind V80 est une plateforme d'analyse de données immobilières propulsée par l'IA, conçue pour être puissante, confidentielle et facile d'utilisation. Notre mission est de démocratiser l'analyse avancée des données pour les professionnels de l'immobilier, en garantissant une autonomie totale et une sécurité maximale des données.",
|
| 121 |
+
"about_app_content": "ErnestMind V80 est une plateforme d'analyse de données immobilières propulsée par l'IA. Elle vous permet d'analyser vos données en toute confidentialité, directement sur votre machine, sans aucune collecte ni stockage externe. Profitez de fonctionnalités avancées pour la prédiction, la détection d'anomalies, le clustering et la génération de rapports personnalisés.",
|
| 122 |
+
|
| 123 |
+
# Nouvelles clés pour les observations
|
| 124 |
+
"res_observations_intro": "Voici une série d'observations stratégiques générées automatiquement à partir de l'analyse de vos données :",
|
| 125 |
+
"no_observations_available": "Aucune observation pertinente n'a pu être générée à partir des données fournies.",
|
| 126 |
+
"obs_missing_values": "Des valeurs manquantes ont été détectées dans les colonnes suivantes : {cols}. Ce phénomène peut impacter la performance des modèles si elles ne sont pas traitées.",
|
| 127 |
+
"obs_high_outlier_rate": "Un taux élevé de valeurs aberrantes ({percent}%) a été identifié. Ces points de données inhabituels méritent une attention particulière car ils peuvent biaiser l'analyse et les prédictions.",
|
| 128 |
+
"obs_outliers_exist": "Des valeurs aberrantes existent dans vos données ({percent}%). Il est recommandé d'examiner ces cas pour s'assurer qu'ils ne sont pas le résultat d'erreurs de saisie.",
|
| 129 |
+
"obs_data_clusters": "Le modèle a identifié des clusters distincts dans vos données. Cette segmentation suggère la présence de sous-groupes de propriétés avec des caractéristiques et des comportements de prix différents.",
|
| 130 |
+
"obs_median_price": "Le prix médian de la colonne '{col}' est de {price:.2f}. Ce chiffre est un indicateur clé pour évaluer le marché global de votre jeu de données.",
|
| 131 |
+
"obs_high_correlation": "Une forte corrélation a été observée entre certaines paires de caractéristiques ({pairs}). Ceci peut indiquer une redondance ou une interaction significative qui pourrait être exploitée ou gérée dans le modèle.",
|
| 132 |
+
"obs_skewed_distribution": "La distribution de la colonne '{col}' est asymétrique, ce qui peut affecter les performances de certains modèles. Une transformation des données pourrait être bénéfique.",
|
| 133 |
+
"obs_categorical_imbalance": "La colonne catégorielle '{col}' présente un déséquilibre important de classes, avec la catégorie '{minority}' sous-représentée. Cela peut biaiser les prédictions pour cette classe.",
|
| 134 |
+
"obs_high_cardinality": "La colonne '{col}' a une cardinalité élevée ({count} valeurs uniques). Cela pourrait rendre l'encodage coûteux et potentiellement introduire du surapprentissage.",
|
| 135 |
+
"obs_time_series_trend": "Une tendance claire a été détectée dans la colonne de date '{col}', suggérant que le temps est un facteur important dans les variations des données.",
|
| 136 |
+
"obs_missing_target_values": "Des valeurs manquantes ont été trouvées dans la colonne cible '{target_col}'. Il est crucial de les traiter avant l'entraînement du modèle.",
|
| 137 |
+
"obs_low_variance": "La colonne '{col}' présente une très faible variance, ce qui signifie qu'elle ne contient pas beaucoup d'informations utiles pour le modèle et pourrait être retirée.",
|
| 138 |
+
"obs_duplicate_rows": "Des lignes dupliquées ({count} duplicata) ont été identifiées dans le jeu de données. Leur suppression peut améliorer la qualité de l'analyse.",
|
| 139 |
+
"obs_multicollinearity": "Une forte multicolinéarité est présente parmi les variables. Cela peut rendre l'interprétation des coefficients du modèle difficile et impacter sa stabilité.",
|
| 140 |
+
|
| 141 |
+
# Messages d'interface utilisateur
|
| 142 |
+
"login_title": "Connexion / Création de compte",
|
| 143 |
+
"login_intro": "Bienvenue ! Connectez-vous ou créez un compte pour accéder à toutes les fonctionnalités, ou explorez en mode démo.",
|
| 144 |
+
"username_label": "Nom d'utilisateur",
|
| 145 |
+
"password_label": "Mot de passe",
|
| 146 |
+
"login_button": "Se connecter",
|
| 147 |
+
"create_account_button": "Créer un compte",
|
| 148 |
+
"explore_demo_button": "Explorer en mode Démo",
|
| 149 |
+
"login_success": "Connexion réussie !",
|
| 150 |
+
"login_error": "Nom d'utilisateur ou mot de passe incorrect.",
|
| 151 |
+
"login_fields_prompt": "Veuillez entrer un nom d'utilisateur et un mot de passe.",
|
| 152 |
+
"create_account_fields_prompt": "Veuillez entrer un nom d'utilisateur, un mot de passe et sélectionner un type de profil pour créer un compte.",
|
| 153 |
+
"demo_mode_activated": "Mode Démo activé ! Données fictives chargées.",
|
| 154 |
+
"logged_in_as": "Connecté en tant que",
|
| 155 |
+
"logout_button": "Se déconnecter",
|
| 156 |
+
"theme_reload_info": "Le thème changera après le rechargement de la page.",
|
| 157 |
+
"app_title_welcome": "Bienvenue sur ErnestMind V80",
|
| 158 |
+
"login_prompt_or_demo": "Veuillez vous connecter, créer un compte ou explorer en mode démo pour commencer.",
|
| 159 |
+
"home_welcome_title": "Bienvenue, {username} !",
|
| 160 |
+
"home_intro": "Explorez les capacités d'analyse de données et d'IA d'ErnestMind V80.",
|
| 161 |
+
"home_feature_discovery_title": "Découvrez nos fonctionnalités clés",
|
| 162 |
+
"home_ai_models_title": "Modèles d'IA utilisés",
|
| 163 |
+
"home_ai_models_description": "ErnestMind V80 exploite plusieurs algorithmes d'IA puissants pour vous offrir des analyses approfondies et des prédictions fiables :",
|
| 164 |
+
"ai_model_lightgbm": "Un algorithme de machine learning rapide et performant pour la régression et la classification.",
|
| 165 |
+
"ai_model_isolation_forest": "Utilisé pour la détection efficace des anomalies dans vos données.",
|
| 166 |
+
"ai_model_kmeans": "Un algorithme de clustering pour identifier des groupes naturels au sein de vos données.",
|
| 167 |
+
"your_latest_projects_title": "Vos derniers projets",
|
| 168 |
+
"load_project_button": "Charger {filename}",
|
| 169 |
+
"no_projects_saved": "Aucun projet sauvegardé pour cet utilisateur.",
|
| 170 |
+
"demo_data_title": "Données de Démonstration",
|
| 171 |
+
"demo_data_intro": "Voici un aperçu des données fictives préchargées que vous pouvez utiliser en mode démo pour explorer les fonctionnalités de l'application.",
|
| 172 |
+
"interactive_map_title": "Carte Interactive des Propriétés",
|
| 173 |
+
"property_map_title": "Localisation des propriétés de démonstration",
|
| 174 |
+
"demo_kpis_title": "Indicateurs Clés de Performance (KPIs) de Démonstration",
|
| 175 |
+
"average_price": "Prix Moyen",
|
| 176 |
+
"number_of_properties": "Nombre de Propriétés",
|
| 177 |
+
"average_surface": "Surface Moyenne",
|
| 178 |
+
"user_data_saved": "Données de l'utilisateur sauvegardées localement.",
|
| 179 |
+
"user_data_loaded": "Données de l'utilisateur '{filename}' chargées avec succès.",
|
| 180 |
+
"save_not_available_demo": "La sauvegarde n'est pas disponible en mode démo.",
|
| 181 |
+
"login_required_save": "Veuillez vous connecter pour sauvegarder vos données.",
|
| 182 |
+
"load_not_available_demo": "Le chargement de projets n'est pas disponible en mode démo.",
|
| 183 |
+
"login_required_load": "Veuillez vous connecter pour charger vos projets.",
|
| 184 |
+
"error_loading_user_data": "Erreur lors du chargement des données utilisateur.",
|
| 185 |
+
"file_not_found_on_server": "Le fichier '{filename}' n'a pas été trouvé sur le serveur.",
|
| 186 |
+
"file_not_found_for_user": "Le fichier '{filename}' n'a pas été trouvé pour cet utilisateur.",
|
| 187 |
+
"no_suitable_target_column": "Aucune colonne numérique appropriée trouvée pour la colonne cible. Veuillez vérifier vos données.",
|
| 188 |
+
"error_shap_calculation": "Erreur lors du calcul des valeurs SHAP",
|
| 189 |
+
"shap_not_available": "Les valeurs SHAP n'ont pas pu être calculées ou affichées pour ce modèle. Vérifiez les données ou les paramètres du modèle.",
|
| 190 |
+
"error_creating_excel": "Erreur lors de la création du fichier Excel",
|
| 191 |
+
"excel_dependency_error": "Erreur : Une dépendance nécessaire pour ce format est manquante. Veuillez installer `xlsxwriter` via `pip install xlsxwriter`.",
|
| 192 |
+
"create_profile_explanation": "Créer un profil aide ErnestMind à mieux adapter les analyses et les rapports à vos besoins spécifiques. Vos données restent confidentielles et locales.",
|
| 193 |
+
"profile_type_label": "Quel est votre profil ?",
|
| 194 |
+
"profile_agent_immobilier": "Agent Immobilier",
|
| 195 |
+
"profile_investisseur": "Investisseur Immobilier",
|
| 196 |
+
"profile_expert_data": "Expert en Science des Données",
|
| 197 |
+
"profile_autre": "Autre",
|
| 198 |
+
"profile_saved_success": "Profil sauvegardé avec succès !",
|
| 199 |
+
"new_discussion_button": "Nouvelle Discussion",
|
| 200 |
+
"current_discussion_label": "Discussion actuelle : {discussion_name}",
|
| 201 |
+
"load_discussion_button": "Charger {discussion_name}",
|
| 202 |
+
"delete_discussion_button": "Supprimer",
|
| 203 |
+
"discussion_deleted_success": "Discussion '{discussion_name}' supprimée avec succès.",
|
| 204 |
+
"discussion_created_success": "Nouvelle discussion '{discussion_name}' créée !",
|
| 205 |
+
"enter_discussion_name": "Veuillez nommer votre nouvelle discussion :",
|
| 206 |
+
"discussion_name_exists": "Une discussion avec ce nom existe déjà. Veuillez en choisir un autre.",
|
| 207 |
+
"no_discussions_saved": "Aucune discussion sauvegardée pour cet utilisateur.",
|
| 208 |
+
"select_discussion_to_load": "Sélectionnez une discussion à charger",
|
| 209 |
+
"auto_generated_visualizations_title": "Visualisations Automatiques des Données",
|
| 210 |
+
"scatter_surface_price": "Prix vs Surface ($m^2$)",
|
| 211 |
+
"scatter_generic": "Nuage de points : {col1} vs {col2}",
|
| 212 |
+
"box_price_by_location": "Distribution des Prix par Localisation",
|
| 213 |
+
"box_generic": "Distribution de {num_col} par {cat_col}",
|
| 214 |
+
"sunburst_hierarchical": "Répartition Hiérarchique des Catégories",
|
| 215 |
+
"pie_chart_of": "Diagramme Circulaire de {col}",
|
| 216 |
+
"main_section_import_button": "Importer un fichier pour l'analyse",
|
| 217 |
+
"import_file_types_info": "Formats supportés : CSV, TXT, JSON, XLSX, XLS, Parquet, ORC, Feather, Stata, SAS."
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
# Mettre à jour la structure des traductions de base avec la gestion des utilisateurs
|
| 221 |
+
# Cette ligne doit être exécutée APRÈS la définition des fonctions de gestion des utilisateurs
|
| 222 |
+
fr_translations_base['users'] = load_users()
|
a6ea61c8-951a-413a-ba9d-7365d83fbd4d/gitforge/coolo/translations_data_processing.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# translations_data_processing.py - Contient les traductions pour le diagnostic et la préparation des données
|
| 2 |
+
|
| 3 |
+
# Dictionnaire pour la langue française
|
| 4 |
+
fr_translations_data_processing = {
|
| 5 |
+
"overview_data": "Aperçu des Données",
|
| 6 |
+
"num_rows": "Nombre de lignes : {rows}",
|
| 7 |
+
"num_cols": "Nombre de colonnes : {cols}",
|
| 8 |
+
"descriptive_stats": "Statistiques Descriptives",
|
| 9 |
+
"missing_values": "Valeurs Manquantes",
|
| 10 |
+
"no_missing_values": "Aucune valeur manquante détectée dans le jeu de données.",
|
| 11 |
+
"dataframe_sample": "Échantillon du DataFrame",
|
| 12 |
+
"visualizations_generated_success": "Visualisations générées avec succès !",
|
| 13 |
+
"dist_num_cols": "Distributions des principales colonnes numériques",
|
| 14 |
+
"dist_of": "Distribution de",
|
| 15 |
+
"frequency": "Fréquence",
|
| 16 |
+
"freq_cat_cols": "Fréquences des principales colonnes catégorielles",
|
| 17 |
+
"freq_of": "Fréquence de",
|
| 18 |
+
"count": "Compte",
|
| 19 |
+
"correlation_matrix": "Matrice de Corrélation",
|
| 20 |
+
"correlation_matrix_title": "Matrice de Corrélation des Caractéristiques Numériques",
|
| 21 |
+
"correlation_matrix_caption": "Heatmap de la matrice de corrélation",
|
| 22 |
+
|
| 23 |
+
"data_prep_intro": "Utilisez ce module pour nettoyer, transformer et préparer vos données pour l'analyse IA. Les options incluent le traitement des valeurs manquantes et aberrantes, la mise à l'échelle des caractéristiques et la création de nouvelles fonctionnalités.",
|
| 24 |
+
|
| 25 |
+
# Nouvelles clés pour la préparation des données
|
| 26 |
+
"missing_values_imputation_title": "Traitement des Valeurs Manquantes",
|
| 27 |
+
"select_imputation_method": "Sélectionnez la méthode d'imputation",
|
| 28 |
+
"apply_imputation_button": "Appliquer l'Imputation",
|
| 29 |
+
"imputation_applied": "Imputation par '{method}' appliquée avec succès.",
|
| 30 |
+
"feature_scaling_title": "Mise à l'Échelle des Caractéristiques",
|
| 31 |
+
"select_scaling_method": "Sélectionnez la méthode de mise à l'échelle",
|
| 32 |
+
"apply_scaling_button": "Appliquer la Mise à l'Échelle",
|
| 33 |
+
"scaling_applied": "Mise à l'échelle par '{method}' appliquée avec succès.",
|
| 34 |
+
"feature_engineering_title": "Ingénierie des Caractéristiques",
|
| 35 |
+
"create_polynomial_features": "Créer des Caractéristiques Polynômiales",
|
| 36 |
+
"select_poly_degree": "Sélectionnez le degré pour les caractéristiques polynômiales.",
|
| 37 |
+
"create_interaction_term": "Créer un Terme d'Interaction",
|
| 38 |
+
"select_interaction_cols": "Sélectionnez deux colonnes pour le terme d'interaction",
|
| 39 |
+
"create_interaction_button": "Créer le terme d'interaction",
|
| 40 |
+
"interaction_term_created": "Terme d'interaction '{new_name}' créé à partir de '{col1}' et '{col2}'.",
|
| 41 |
+
"extract_datetime_features": "Extraire les Caractéristiques de Date/Heure",
|
| 42 |
+
"select_datetime_col": "Sélectionnez une colonne de date/heure",
|
| 43 |
+
"select_datetime_features": "Sélectionnez les caractéristiques à extraire",
|
| 44 |
+
"extract_features": "Extraire les caractéristiques",
|
| 45 |
+
"datetime_features_extracted": "Caractéristiques de date/heure '{features}' extraites de la colonne '{col}'.",
|
| 46 |
+
"select_datetime_col_and_features": "Veuillez sélectionner une colonne de date/heure et au moins une caractéristique à extraire.",
|
| 47 |
+
"apply_aggregation": "Appliquer l'Agrégation",
|
| 48 |
+
"select_groupby_col": "Sélectionnez la colonne de groupement",
|
| 49 |
+
"select_target_col_agg": "Sélectionnez la colonne cible pour l'agrégation",
|
| 50 |
+
"select_agg_method": "Sélectionnez la (les) méthode(s) d'agrégation",
|
| 51 |
+
"apply_aggregation_button": "Appliquer l'agrégation",
|
| 52 |
+
"aggregation_applied": "Agrégation '{method}' appliquée à la colonne '{target}' groupée par '{group}'.",
|
| 53 |
+
|
| 54 |
+
# Nouvelles clés pour les visualisations
|
| 55 |
+
"no_numeric_columns": "Aucune colonne numérique n'a été trouvée pour les distributions.",
|
| 56 |
+
"no_categorical_columns": "Aucune colonne catégorielle n'a été trouvée pour les fréquences.",
|
| 57 |
+
"not_enough_numeric_for_corr": "Pas assez de colonnes numériques pour une matrice de corrélation.",
|
| 58 |
+
"word_cloud_title": "Nuage de Mots",
|
| 59 |
+
"word_cloud_info": "Génère un nuage de mots à partir d'une colonne de texte pour visualiser les termes les plus fréquents.",
|
| 60 |
+
"select_text_column": "Sélectionnez une colonne de texte",
|
| 61 |
+
"no_text_data_for_wordcloud": "La colonne sélectionnée ne contient pas de données textuelles à analyser pour le nuage de mots.",
|
| 62 |
+
"no_text_columns": "Aucune colonne de type texte n'a été trouvée.",
|
| 63 |
+
"generate_visualizations_button": "Générer les Visualisations",
|
| 64 |
+
|
| 65 |
+
# Nouvelles clés pour les modèles avancés
|
| 66 |
+
"outlier_detection_title": "Détection des Valeurs Aberrantes",
|
| 67 |
+
"detect_outliers_button": "Détecter les Valeurs Aberrantes",
|
| 68 |
+
"outliers_detected": "Valeurs aberrantes détectées. Une nouvelle colonne 'outlier_score' a été ajoutée. -1 pour les outliers, 1 pour les autres.",
|
| 69 |
+
"clustering_title": "Clustering des Données",
|
| 70 |
+
"select_num_clusters": "Sélectionnez le nombre de clusters",
|
| 71 |
+
"apply_clustering_button": "Appliquer le Clustering",
|
| 72 |
+
"clustering_applied": "Clustering K-Means avec {n_clusters} clusters appliqué avec succès. Une nouvelle colonne 'cluster' a été ajoutée."
|
| 73 |
+
}
|
a6ea61c8-951a-413a-ba9d-7365d83fbd4d/gitforge/coolo/translations_report_content.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# translations_report_content.py - Contient les traductions pour le contenu des sections de rapport spécifiques
|
| 2 |
+
|
| 3 |
+
# Dictionnaire pour la langue française
|
| 4 |
+
fr_translations_report_content = {
|
| 5 |
+
# Nouvelles clés pour les sections du rapport et annexes
|
| 6 |
+
"report_cover_page_title": "Page de Garde",
|
| 7 |
+
"about_this_report_title": "À Propos de ce Rapport",
|
| 8 |
+
"about_this_report_content": """
|
| 9 |
+
Ce rapport a été généré automatiquement par ErnestMind V80, une plateforme d'analyse immobilière basée sur l'IA. Il vise à fournir une compréhension approfondie des données immobilières fournies, à identifier les tendances clés, à évaluer la performance des modèles prédictifs et à proposer des recommandations stratégiques actionnables.
|
| 10 |
+
|
| 11 |
+
Le contenu de ce rapport est structuré en plusieurs sections clés, chacune conçue pour éclairer différents aspects de votre analyse immobilière.
|
| 12 |
+
""",
|
| 13 |
+
"data_info_section": "Informations Générales sur les Données",
|
| 14 |
+
"data_info_intro": "Cette section présente un aperçu général et des statistiques descriptives du jeu de données analysé.",
|
| 15 |
+
"report_data_quality_title": "Qualité des Données et Traitement",
|
| 16 |
+
"data_quality_intro": "Une analyse de la qualité des données a été effectuée, incluant la détection et la gestion des valeurs manquantes et des valeurs aberrantes.",
|
| 17 |
+
"report_kpis_infographic_title": "Indicateurs Clés de Performance (KPIs)",
|
| 18 |
+
"kpis_intro": "Cette section présente les principaux indicateurs de performance du modèle prédictif.",
|
| 19 |
+
"report_ai_observations_title": "Observations Stratégiques",
|
| 20 |
+
"report_ai_recommendations_title": "Recommandations d'Actions IA",
|
| 21 |
+
"report_methodology_annex_title": "Annexe - Méthodologie",
|
| 22 |
+
"methodology_intro": "Ce rapport a été généré en utilisant la méthodologie suivante pour l'analyse des données et la création de modèles IA :",
|
| 23 |
+
"methodology_data_prep": "- **Préparation des Données :** Nettoyage, gestion des valeurs manquantes, encodage des variables catégorielles et standardisation des caractéristiques numériques.",
|
| 24 |
+
"methodology_model_training": "- **Entraînement du Modèle :** Un modèle LightGBM a été entraîné pour la prédiction sur un sous-ensemble des données (80% pour l'entraînement, 20% pour les tests).",
|
| 25 |
+
"methodology_shap_explanation": "- **Explicabilité du Modèle (SHAP) :** Les valeurs SHAP ont été calculées pour expliquer l'impact de chaque caractéristique sur les prédictions du modèle.",
|
| 26 |
+
"methodology_report_generation": "- **Génération de Rapport :** Le rapport a été généré automatiquement, incluant des observations et des recommandations basées sur les insights du modèle IA.",
|
| 27 |
+
"methodology_data_confidentiality": "- **Confidentialité des Données :** Toutes les analyses sont effectuées localement sur votre machine. Aucune de vos données n'est transmise ou stockée sur des serveurs externes.",
|
| 28 |
+
"report_glossary_annex_title": "Annexe - Glossaire",
|
| 29 |
+
"glossary_full_text": """
|
| 30 |
+
**KPI (Key Performance Indicator) :** Indicateur clé de performance.
|
| 31 |
+
**RMSE (Root Mean Squared Error) :** Erreur quadratique moyenne. Mesure la différence entre les valeurs prédites et les valeurs réelles.
|
| 32 |
+
**R² Score (Coefficient de Détermination) :** Mesure la proportion de la variance de la variable dépendante qui est prévisible à partir de la ou des variables indépendantes.
|
| 33 |
+
**SHAP (SHapley Additive exPlanations) :** Une méthode d'explicabilité de l'IA qui permet d'expliquer comment les caractéristiques d'un modèle influencent les prédictions.
|
| 34 |
+
**LightGBM :** Un algorithme d'apprentissage automatique de type gradient boosting. Très performant et rapide.
|
| 35 |
+
**Valeurs Manquantes :** Données non disponibles dans le jeu de données.
|
| 36 |
+
**Valeurs Aberrantes (Outliers) :** Observations qui s'écartent significativement des autres observations.
|
| 37 |
+
**Clustering :** Technique non supervisée qui regroupe des points de données similaires.
|
| 38 |
+
""",
|
| 39 |
+
"report_about_app_annex_title": "Annexe - À Propos d'ErnestMind V80",
|
| 40 |
+
"about_app_content": """
|
| 41 |
+
ErnestMind V80 est une plateforme d'analyse de données en mode local, conçue pour les professionnels de l'immobilier. Elle combine l'autonomie des logiciels de bureau avec la puissance de l'IA pour offrir une expérience d'analyse unique.
|
| 42 |
+
|
| 43 |
+
**Nos Atouts :**
|
| 44 |
+
* **Autonomie :** Traitez vos données directement sur votre machine, sans besoin de les télécharger sur des serveurs externes.
|
| 45 |
+
* **Puissance :** Bénéficiez d'algorithmes d'IA avancés pour l'analyse prédictive, l'explicabilité et la génération d'insights.
|
| 46 |
+
* **Simplicité :** Une interface utilisateur conçue pour être intuitive, rendant l'analyse complexe accessible à tous.
|
| 47 |
+
* **Personnalisation :** Adaptez les rapports et les analyses à vos besoins spécifiques.
|
| 48 |
+
* **Multilinguisme :** Travaillez dans la langue de votre choix pour une expérience utilisateur optimale.
|
| 49 |
+
|
| 50 |
+
**Notre Engagement :**
|
| 51 |
+
* **Confidentialité :** La sécurité de vos données est notre priorité absolue. Nous n'accédons ni ne stockons vos informations.
|
| 52 |
+
* **Innovation :** Nous nous engageons à améliorer constamment ErnestMind V80 avec les dernières avancées en IA et en science des données.
|
| 53 |
+
* **Support :** Notre équipe est là pour vous aider et répondre à vos questions.
|
| 54 |
+
|
| 55 |
+
Rejoignez la communauté ErnestMind.ai et transformez la façon dont vous interagissez avec vos données !
|
| 56 |
+
""",
|
| 57 |
+
# Observations et recommandations du modèle (exemples)
|
| 58 |
+
"observation_median_price_per_sqm": "Le prix médian par mètre carré est de {price:.2f} €, ce qui est un indicateur clé de la valeur immobilière dans cette région.",
|
| 59 |
+
"recommendation_price_analysis": "Analysez plus en profondeur les facteurs qui influencent le prix par mètre carré pour identifier les opportunités d'investissement.",
|
| 60 |
+
"no_kpis_available": "Aucun KPI n'est disponible car le modèle n'a pas été entraîné ou les données de test sont insuffisantes.",
|
| 61 |
+
|
| 62 |
+
# Database specific translations
|
| 63 |
+
"database_section": "Base de Données",
|
| 64 |
+
"database_intro": "Gérez et analysez vos fichiers de données de manière sécurisée et locale. Importez jusqu'à 10 fichiers à la fois pour les stocker ou lancer une analyse avancée sur un seul fichier.",
|
| 65 |
+
"login_to_database": "Connectez-vous pour accéder à la base de données",
|
| 66 |
+
"open_database_button": "Ouvrir la Base de Données",
|
| 67 |
+
"import_files_to_db_title": "Importer des Fichiers dans la Base de Données",
|
| 68 |
+
"upload_db_files_label": "Téléchargez un ou plusieurs fichiers (max. 10)",
|
| 69 |
+
"file_storage_option": "Stocker le(s) fichier(s) dans la base de données",
|
| 70 |
+
"advanced_analysis_option": "Lancer une analyse avancée sur un seul fichier",
|
| 71 |
+
"select_file_for_analysis": "Sélectionnez un fichier pour l'analyse avancée",
|
| 72 |
+
"analyze_selected_file_button": "Analyser le Fichier Sélectionné",
|
| 73 |
+
"file_saved_to_db": "Fichier '{filename}' sauvegardé dans la base de données.",
|
| 74 |
+
"files_saved_to_db": "{count} fichiers sauvegardés dans la base de données.",
|
| 75 |
+
"analysis_triggered_for_file": "Analyse avancée déclenchée pour le fichier '{filename}'.",
|
| 76 |
+
"please_select_one_file_for_analysis": "Veuillez sélectionner un seul fichier pour l'analyse avancée.",
|
| 77 |
+
"no_files_uploaded_for_db": "Veuillez télécharger au moins un fichier.",
|
| 78 |
+
"stored_files_title": "Fichiers Stockés",
|
| 79 |
+
"no_stored_files": "Aucun fichier stocké dans votre base de données.",
|
| 80 |
+
"select_stored_file_for_analysis": "Sélectionnez un fichier stocké pour lancer une analyse",
|
| 81 |
+
"view_file_content_button": "Voir le Contenu du Fichier",
|
| 82 |
+
"delete_file_button": "Supprimer le Fichier",
|
| 83 |
+
"file_deleted_success": "Fichier '{filename}' supprimé avec succès de la base de données.",
|
| 84 |
+
"enter_password_strong_requirements": "Le mot de passe doit contenir entre 8 et 15 caractères, incluant des chiffres, des lettres et des caractères spéciaux."
|
| 85 |
+
}
|