Spaces:
Runtime error
Runtime error
Delete archive.py
Browse files- archive.py +0 -212
archive.py
DELETED
|
@@ -1,212 +0,0 @@
|
|
| 1 |
-
#-------------------------------------------------------- Imports nécessaires ---------------------------------------------------
|
| 2 |
-
import os
|
| 3 |
-
import warnings
|
| 4 |
-
import pandas as pd
|
| 5 |
-
import numpy as np
|
| 6 |
-
import plotly.express as px
|
| 7 |
-
import streamlit as st
|
| 8 |
-
import boto3
|
| 9 |
-
import mlflow
|
| 10 |
-
import mlflow.pyfunc
|
| 11 |
-
|
| 12 |
-
from sklearn.exceptions import UndefinedMetricWarning
|
| 13 |
-
from sklearn import set_config
|
| 14 |
-
|
| 15 |
-
warnings.filterwarnings("ignore", category=UndefinedMetricWarning)
|
| 16 |
-
set_config(display="text")
|
| 17 |
-
|
| 18 |
-
#-------------------------------------------------------- Configuration AWS S3 ---------------------------------------------------
|
| 19 |
-
aws_access_key_id = os.environ.get("AWS_ACCESS_KEY_ID")
|
| 20 |
-
aws_secret_access_key = os.environ.get("AWS_SECRET_ACCESS_KEY")
|
| 21 |
-
aws_region = "eu-west-3"
|
| 22 |
-
|
| 23 |
-
s3 = boto3.client(
|
| 24 |
-
's3',
|
| 25 |
-
region_name=aws_region,
|
| 26 |
-
aws_access_key_id=aws_access_key_id,
|
| 27 |
-
aws_secret_access_key=aws_secret_access_key
|
| 28 |
-
)
|
| 29 |
-
|
| 30 |
-
#-------------------------------------------------------- Streamlit page config ---------------------------------------------------
|
| 31 |
-
st.set_page_config(page_title="Projet Incendies", layout="wide")
|
| 32 |
-
|
| 33 |
-
#-------------------------------------------------------- Sidebar navigation ---------------------------------------------------
|
| 34 |
-
st.sidebar.title("Navigation")
|
| 35 |
-
page = st.sidebar.radio("Aller à", [
|
| 36 |
-
"Accueil",
|
| 37 |
-
"Notre Projet",
|
| 38 |
-
"Résultats des modèles",
|
| 39 |
-
])
|
| 40 |
-
|
| 41 |
-
#-------------------------------------------------------- Footer ---------------------------------------------------
|
| 42 |
-
def show_footer():
|
| 43 |
-
st.markdown("---")
|
| 44 |
-
st.markdown("Projet réalisé dans le cadre de la formation Lead Data Scientist. © 2025")
|
| 45 |
-
|
| 46 |
-
#-------------------------------------------------------- Chargement des datasets depuis S3 ---------------------------------------------------
|
| 47 |
-
@st.cache_data(show_spinner="🔄 Téléchargement du dataset modèle…", ttl=None)
|
| 48 |
-
def load_model_data() -> pd.DataFrame:
|
| 49 |
-
bucket = "projet-final-lead"
|
| 50 |
-
key = "data/dataset_complet_meteo.csv"
|
| 51 |
-
try:
|
| 52 |
-
# Utilise boto3 pour accéder au S3 avec tes credentials déjà définis dans l'environnement
|
| 53 |
-
obj = s3.get_object(Bucket=bucket, Key=key)
|
| 54 |
-
df = pd.read_csv(obj['Body'], sep=';')
|
| 55 |
-
for col in df.columns:
|
| 56 |
-
if "date" in col.lower():
|
| 57 |
-
df[col] = pd.to_datetime(df[col], errors="coerce", dayfirst=True)
|
| 58 |
-
return df
|
| 59 |
-
except Exception as e:
|
| 60 |
-
st.error(f"❌ Erreur lors du chargement du dataset modèle : {e}")
|
| 61 |
-
return pd.DataFrame()
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
@st.cache_data(show_spinner="🔄 Téléchargement du dataset historique…", ttl=None)
|
| 65 |
-
def load_df_merge() -> pd.DataFrame:
|
| 66 |
-
bucket = "projet-final-lead"
|
| 67 |
-
key = "data/historique_incendies_avec_coordonnees.csv"
|
| 68 |
-
try:
|
| 69 |
-
obj = s3.get_object(Bucket=bucket, Key=key)
|
| 70 |
-
df = pd.read_csv(obj['Body'], sep=';', encoding='utf-8')
|
| 71 |
-
return df
|
| 72 |
-
except Exception as e:
|
| 73 |
-
st.error(f"❌ Erreur lors du chargement du dataset historique : {e}")
|
| 74 |
-
return pd.DataFrame()
|
| 75 |
-
|
| 76 |
-
#-------------------------------------------------------- MLflow ---------------------------------------------------
|
| 77 |
-
mlflow.set_tracking_uri("https://djohell-ml-flow.hf.space")
|
| 78 |
-
|
| 79 |
-
@st.cache_data(show_spinner="🔄 Chargement du modèle MLflow…", ttl=None)
|
| 80 |
-
def load_mlflow_model():
|
| 81 |
-
# Remplace ce run_id par le run_id correct de ton modèle
|
| 82 |
-
model_uri = 'runs:/69a3c889954f4ce9a2139a4fb4cefc59/survival_xgb_model'
|
| 83 |
-
model = mlflow.pyfunc.load_model(model_uri)
|
| 84 |
-
return model
|
| 85 |
-
|
| 86 |
-
# Exemple d'utilisation
|
| 87 |
-
_model = load_mlflow_model()
|
| 88 |
-
st.write("✅ Modèle MLflow chargé !")
|
| 89 |
-
|
| 90 |
-
#-------------------------------------------------------- Prédiction via MLflow ---------------------------------------------------
|
| 91 |
-
@st.cache_data(show_spinner="⚙️ Prédiction des risques…", ttl=None)
|
| 92 |
-
def predict_risk(df_raw: pd.DataFrame, _model) -> pd.DataFrame:
|
| 93 |
-
df = df_raw.copy()
|
| 94 |
-
df = df.rename(columns={"Feu prévu": "event", "décompte": "duration"})
|
| 95 |
-
df["event"] = df["event"].astype(bool)
|
| 96 |
-
df["duration"] = df["duration"].fillna(0)
|
| 97 |
-
|
| 98 |
-
features = [
|
| 99 |
-
"moyenne precipitations mois", "moyenne temperature mois",
|
| 100 |
-
"moyenne evapotranspiration mois", "moyenne vitesse vent année",
|
| 101 |
-
"moyenne vitesse vent mois", "moyenne temperature année",
|
| 102 |
-
"RR", "UM", "ETPMON", "TN", "TX", "Nombre de feu par an",
|
| 103 |
-
"Nombre de feu par mois", "jours_sans_pluie", "jours_TX_sup_30",
|
| 104 |
-
"ETPGRILLE_7j", "compteur jours vers prochain feu",
|
| 105 |
-
"compteur feu log", "Année", "Mois",
|
| 106 |
-
"moyenne precipitations année", "moyenne evapotranspiration année",
|
| 107 |
-
]
|
| 108 |
-
features = [f for f in features if f in df.columns]
|
| 109 |
-
|
| 110 |
-
# ⚡ Correction : passer directement le DataFrame
|
| 111 |
-
log_hr_all = _model.predict(df[features])
|
| 112 |
-
HR = np.exp(log_hr_all)
|
| 113 |
-
|
| 114 |
-
# Baseline hazard factice
|
| 115 |
-
def S0(t):
|
| 116 |
-
return np.exp(-t/1000)
|
| 117 |
-
|
| 118 |
-
horizons = {7:"proba_7j", 30:"proba_30j", 60:"proba_60j", 90:"proba_90j", 180:"proba_180j"}
|
| 119 |
-
for t, col in horizons.items():
|
| 120 |
-
df[col] = 1 - (S0(t) ** HR)
|
| 121 |
-
|
| 122 |
-
for col in ["latitude","longitude","ville"]:
|
| 123 |
-
if col not in df.columns:
|
| 124 |
-
df[col] = np.nan
|
| 125 |
-
|
| 126 |
-
df_map = df[["latitude","longitude","ville"] + list(horizons.values())].copy()
|
| 127 |
-
return df_map
|
| 128 |
-
|
| 129 |
-
#-------------------------------------------------------- Page Accueil ---------------------------------------------------
|
| 130 |
-
if page == "Accueil":
|
| 131 |
-
st.title("Carte du risque d’incendie en Corse")
|
| 132 |
-
|
| 133 |
-
df_raw = load_model_data()
|
| 134 |
-
df_map = predict_risk(df_raw, _model)
|
| 135 |
-
|
| 136 |
-
horizons_lbl = {
|
| 137 |
-
"7 jours":"proba_7j",
|
| 138 |
-
"30 jours":"proba_30j",
|
| 139 |
-
"60 jours":"proba_60j",
|
| 140 |
-
"90 jours":"proba_90j",
|
| 141 |
-
"180 jours":"proba_180j",
|
| 142 |
-
}
|
| 143 |
-
choix = st.radio("Choisis l’horizon temporel :", list(horizons_lbl.keys()), horizontal=True, index=0)
|
| 144 |
-
col_proba = horizons_lbl[choix]
|
| 145 |
-
|
| 146 |
-
vmax = float(df_map[col_proba].max())
|
| 147 |
-
fig = px.scatter_mapbox(
|
| 148 |
-
df_map,
|
| 149 |
-
lat="latitude",
|
| 150 |
-
lon="longitude",
|
| 151 |
-
hover_name="ville",
|
| 152 |
-
hover_data={col_proba: ":.2%"},
|
| 153 |
-
color=col_proba,
|
| 154 |
-
color_continuous_scale="YlOrRd",
|
| 155 |
-
range_color=(0.0, vmax),
|
| 156 |
-
zoom=7,
|
| 157 |
-
height=650,
|
| 158 |
-
)
|
| 159 |
-
fig.update_layout(
|
| 160 |
-
mapbox_style="open-street-map",
|
| 161 |
-
margin=dict(l=0,r=0,t=0,b=0),
|
| 162 |
-
coloraxis_colorbar=dict(title="Probabilité", tickformat=".0%"),
|
| 163 |
-
)
|
| 164 |
-
st.subheader(f"Risque d’incendie – horizon **{choix}**")
|
| 165 |
-
st.plotly_chart(fig, use_container_width=True)
|
| 166 |
-
|
| 167 |
-
show_footer()
|
| 168 |
-
|
| 169 |
-
#-------------------------------------------------------- Page Notre Projet ---------------------------------------------------
|
| 170 |
-
elif page == "Notre Projet":
|
| 171 |
-
st.title("🔥 Projet Analyse des Incendies 🔥")
|
| 172 |
-
|
| 173 |
-
st.subheader(" 📊 Contexte")
|
| 174 |
-
st.subheader("🌲La forêt française en chiffres")
|
| 175 |
-
col1, col2 = st.columns([2,1])
|
| 176 |
-
with col1:
|
| 177 |
-
st.markdown("""
|
| 178 |
-
La France est le 4ᵉ pays européen en superficie forestière, avec **17,5 millions d’hectares** en métropole (32 % du territoire) et **8 millions** en Guyane.
|
| 179 |
-
Au total, les forêts couvrent environ **41 %** du territoire national.
|
| 180 |
-
- **75 %** des forêts sont privées (3,5 millions de propriétaires).
|
| 181 |
-
- **16 %** publiques (collectivités).
|
| 182 |
-
- **9 %** domaniales (État).
|
| 183 |
-
La forêt française est un réservoir de biodiversité :
|
| 184 |
-
- **190 espèces d’arbres** (67 % feuillus, 33 % conifères).
|
| 185 |
-
- **73 espèces de mammifères**, **120 d’oiseaux**.
|
| 186 |
-
- Environ **30 000 espèces de champignons et autant d’insectes**.
|
| 187 |
-
- **72 %** de la flore française se trouve en forêt.
|
| 188 |
-
Les forêts françaises absorbent environ **9 %** des émissions nationales de gaz à effet de serre, jouant un rôle crucial dans la lutte contre le changement climatique.
|
| 189 |
-
Le Code forestier encadre leur gestion durable pour protéger la biodiversité, l’air, l’eau et prévenir les risques naturels.
|
| 190 |
-
""")
|
| 191 |
-
st.header("🔥 Corse : Bilan Campagne Feux de Forêts 2024")
|
| 192 |
-
tab1, tab2, tab3, tab4, tab5, tab6 = st.tabs(["📌 Contexte","🛠️ Prévention","🚒 Moyens","📊 Statistiques","🔍 Causes","🔎 Enquêtes"])
|
| 193 |
-
|
| 194 |
-
with tab1:
|
| 195 |
-
with st.expander("📌 Contexte général"):
|
| 196 |
-
st.markdown("- **80 %** de la Corse est couverte de forêts/maquis → **fort risque incendie** \n- **2023-2024** : la plus chaude et la plus sèche jamais enregistrée \n- **714 mm** de pluie sur l’année (**78 %** de la normale) \n- **Façade orientale** : seulement **30 %** des précipitations normales")
|
| 197 |
-
# Les autres tabs peuvent suivre exactement ton code initial...
|
| 198 |
-
|
| 199 |
-
show_footer()
|
| 200 |
-
|
| 201 |
-
#-------------------------------------------------------- Page Résultats des modèles ---------------------------------------------------
|
| 202 |
-
elif page == "Résultats des modèles":
|
| 203 |
-
st.title("📈 Résultats des modèles prédictifs")
|
| 204 |
-
st.markdown("### Comparaison des modèles de Survival Analysis")
|
| 205 |
-
st.markdown("""
|
| 206 |
-
| Modèle | Concordance Index |
|
| 207 |
-
|-----------------------------------|-------------------|
|
| 208 |
-
| Predict survival fonction (MVP) | 0.69 |
|
| 209 |
-
| XGBOOST survival cox | 0.809 |
|
| 210 |
-
""")
|
| 211 |
-
st.markdown("👉 Le modèle **XGBOOST survival cox** obtient la meilleure performance globale.")
|
| 212 |
-
show_footer()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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