Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,15 +3,14 @@ import pandas as pd
|
|
| 3 |
import duckdb
|
| 4 |
import polars as pl
|
| 5 |
import pyarrow.csv as pv
|
| 6 |
-
import pyarrow.parquet as pq
|
| 7 |
import time
|
| 8 |
import os
|
| 9 |
import tempfile
|
| 10 |
import matplotlib.pyplot as plt
|
|
|
|
| 11 |
|
| 12 |
# === DEBUG + TEST RAPIDE ===
|
| 13 |
print("=== APP STARTING ===")
|
| 14 |
-
st.success("App démarrée avec succès !")
|
| 15 |
|
| 16 |
# === CONFIG PAGE ===
|
| 17 |
st.set_page_config(
|
|
@@ -33,6 +32,8 @@ st.markdown("""
|
|
| 33 |
background: linear-gradient(145deg, #f5f5f5, #e0e0e0);
|
| 34 |
box-shadow: 4px 4px 8px #cbced1, -4px -4px 8px #ffffff;
|
| 35 |
transition: all 0.3s;
|
|
|
|
|
|
|
| 36 |
}
|
| 37 |
.stButton > button:hover {
|
| 38 |
border: 2px solid #4CAF50;
|
|
@@ -42,32 +43,46 @@ st.markdown("""
|
|
| 42 |
.stButton > button:active {
|
| 43 |
transform: translateY(2px);
|
| 44 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
</style>
|
| 46 |
""", unsafe_allow_html=True)
|
| 47 |
|
| 48 |
-
# === FONCTIONS DE CHARGEMENT ===
|
| 49 |
-
def load_with_pandas(
|
| 50 |
start = time.time()
|
| 51 |
-
df = pd.read_csv(
|
| 52 |
return df, time.time() - start
|
| 53 |
|
| 54 |
-
def load_with_polars(
|
| 55 |
start = time.time()
|
| 56 |
-
df = pl.read_csv(
|
| 57 |
-
return df
|
| 58 |
|
| 59 |
-
def load_with_duckdb(
|
| 60 |
start = time.time()
|
| 61 |
-
df = duckdb.read_csv(
|
| 62 |
return df, time.time() - start
|
| 63 |
|
| 64 |
-
def load_with_pyarrow(
|
| 65 |
start = time.time()
|
| 66 |
-
|
|
|
|
|
|
|
| 67 |
df = table.to_pandas()
|
| 68 |
return df, time.time() - start
|
| 69 |
|
| 70 |
-
# ===
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
st.sidebar.markdown("# ⚡ Speed Benchmark")
|
| 72 |
st.sidebar.markdown("### 🧪 Fichiers de test (~30 Mo)")
|
| 73 |
|
|
@@ -78,19 +93,22 @@ with col1:
|
|
| 78 |
if os.path.exists("faker_text.csv"):
|
| 79 |
st.session_state.file_path = "faker_text.csv"
|
| 80 |
st.session_state.file_name = "faker_text.csv"
|
|
|
|
| 81 |
else:
|
| 82 |
-
st.sidebar.error("faker_text.csv manquant")
|
| 83 |
|
| 84 |
with col2:
|
| 85 |
if st.button("🔢 Numeric\nOnly", use_container_width=True, type="secondary"):
|
| 86 |
if os.path.exists("numeric_only.csv"):
|
| 87 |
st.session_state.file_path = "numeric_only.csv"
|
| 88 |
st.session_state.file_name = "numeric_only.csv"
|
|
|
|
| 89 |
else:
|
| 90 |
-
st.sidebar.error("numeric_only.csv manquant")
|
| 91 |
|
| 92 |
st.sidebar.markdown("---")
|
| 93 |
|
|
|
|
| 94 |
uploaded_file = st.sidebar.file_uploader(
|
| 95 |
"📁 Ou chargez votre fichier",
|
| 96 |
type=["csv", "parquet", "txt"],
|
|
@@ -98,83 +116,133 @@ uploaded_file = st.sidebar.file_uploader(
|
|
| 98 |
)
|
| 99 |
|
| 100 |
if uploaded_file is not None:
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
st.title("⚡ Comparaison de vitesse de chargement")
|
| 111 |
-
st.markdown("**
|
| 112 |
|
| 113 |
-
if
|
| 114 |
-
st.info("👈 Choisissez un fichier de test ou
|
| 115 |
st.stop()
|
| 116 |
|
| 117 |
file_path = st.session_state.file_path
|
| 118 |
file_name = st.session_state.file_name
|
| 119 |
|
| 120 |
-
st.markdown(f"### 📊 Fichier
|
| 121 |
|
| 122 |
-
|
| 123 |
-
|
|
|
|
| 124 |
|
|
|
|
|
|
|
|
|
|
| 125 |
results = []
|
| 126 |
-
|
|
|
|
| 127 |
# === 1. Pandas ===
|
| 128 |
-
with st.spinner("Pandas (
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
|
| 133 |
# === 2. Polars ===
|
| 134 |
-
with st.spinner("Polars (le
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
# === 3. DuckDB ===
|
| 140 |
-
with st.spinner("DuckDB (SQL
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
# === 4. PyArrow ===
|
| 146 |
-
with st.spinner("PyArrow (C++
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
try:
|
| 154 |
os.unlink(st.session_state.temp_file)
|
|
|
|
| 155 |
except:
|
| 156 |
pass
|
| 157 |
|
| 158 |
-
# ===
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import duckdb
|
| 4 |
import polars as pl
|
| 5 |
import pyarrow.csv as pv
|
|
|
|
| 6 |
import time
|
| 7 |
import os
|
| 8 |
import tempfile
|
| 9 |
import matplotlib.pyplot as plt
|
| 10 |
+
import numpy as np
|
| 11 |
|
| 12 |
# === DEBUG + TEST RAPIDE ===
|
| 13 |
print("=== APP STARTING ===")
|
|
|
|
| 14 |
|
| 15 |
# === CONFIG PAGE ===
|
| 16 |
st.set_page_config(
|
|
|
|
| 32 |
background: linear-gradient(145deg, #f5f5f5, #e0e0e0);
|
| 33 |
box-shadow: 4px 4px 8px #cbced1, -4px -4px 8px #ffffff;
|
| 34 |
transition: all 0.3s;
|
| 35 |
+
white-space: pre-line;
|
| 36 |
+
text-align: center;
|
| 37 |
}
|
| 38 |
.stButton > button:hover {
|
| 39 |
border: 2px solid #4CAF50;
|
|
|
|
| 43 |
.stButton > button:active {
|
| 44 |
transform: translateY(2px);
|
| 45 |
}
|
| 46 |
+
.benchmark-btn {
|
| 47 |
+
height: 4rem !important;
|
| 48 |
+
font-size: 1rem !important;
|
| 49 |
+
}
|
| 50 |
</style>
|
| 51 |
""", unsafe_allow_html=True)
|
| 52 |
|
| 53 |
+
# === FONCTIONS DE CHARGEMENT (CORRIGÉES POUR newlines_in_values) ===
|
| 54 |
+
def load_with_pandas(file_path):
|
| 55 |
start = time.time()
|
| 56 |
+
df = pd.read_csv(file_path)
|
| 57 |
return df, time.time() - start
|
| 58 |
|
| 59 |
+
def load_with_polars(file_path):
|
| 60 |
start = time.time()
|
| 61 |
+
df = pl.read_csv(file_path, infer_schema_length=10000).to_pandas()
|
| 62 |
+
return df, time.time() - start
|
| 63 |
|
| 64 |
+
def load_with_duckdb(file_path):
|
| 65 |
start = time.time()
|
| 66 |
+
df = duckdb.read_csv(file_path).df()
|
| 67 |
return df, time.time() - start
|
| 68 |
|
| 69 |
+
def load_with_pyarrow(file_path):
|
| 70 |
start = time.time()
|
| 71 |
+
# CORRECTION: Active newlines_in_values pour gérer les sauts de ligne dans les cellules
|
| 72 |
+
parse_options = pv.ParseOptions(newlines_in_values=True)
|
| 73 |
+
table = pv.read_csv(file_path, parse_options=parse_options)
|
| 74 |
df = table.to_pandas()
|
| 75 |
return df, time.time() - start
|
| 76 |
|
| 77 |
+
# === INITIALISATION SESSION STATE ===
|
| 78 |
+
if 'file_path' not in st.session_state:
|
| 79 |
+
st.session_state.file_path = None
|
| 80 |
+
if 'file_name' not in st.session_state:
|
| 81 |
+
st.session_state.file_name = None
|
| 82 |
+
if 'temp_file' not in st.session_state:
|
| 83 |
+
st.session_state.temp_file = None
|
| 84 |
+
|
| 85 |
+
# === SIDEBAR AVEC TOUS LES BOUTONS ===
|
| 86 |
st.sidebar.markdown("# ⚡ Speed Benchmark")
|
| 87 |
st.sidebar.markdown("### 🧪 Fichiers de test (~30 Mo)")
|
| 88 |
|
|
|
|
| 93 |
if os.path.exists("faker_text.csv"):
|
| 94 |
st.session_state.file_path = "faker_text.csv"
|
| 95 |
st.session_state.file_name = "faker_text.csv"
|
| 96 |
+
st.rerun()
|
| 97 |
else:
|
| 98 |
+
st.sidebar.error("❌ faker_text.csv manquant")
|
| 99 |
|
| 100 |
with col2:
|
| 101 |
if st.button("🔢 Numeric\nOnly", use_container_width=True, type="secondary"):
|
| 102 |
if os.path.exists("numeric_only.csv"):
|
| 103 |
st.session_state.file_path = "numeric_only.csv"
|
| 104 |
st.session_state.file_name = "numeric_only.csv"
|
| 105 |
+
st.rerun()
|
| 106 |
else:
|
| 107 |
+
st.sidebar.error("❌ numeric_only.csv manquant")
|
| 108 |
|
| 109 |
st.sidebar.markdown("---")
|
| 110 |
|
| 111 |
+
# Uploader dans sidebar
|
| 112 |
uploaded_file = st.sidebar.file_uploader(
|
| 113 |
"📁 Ou chargez votre fichier",
|
| 114 |
type=["csv", "parquet", "txt"],
|
|
|
|
| 116 |
)
|
| 117 |
|
| 118 |
if uploaded_file is not None:
|
| 119 |
+
try:
|
| 120 |
+
bytes_data = uploaded_file.read()
|
| 121 |
+
suffix = os.path.splitext(uploaded_file.name)[1]
|
| 122 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
|
| 123 |
+
tmp.write(bytes_data)
|
| 124 |
+
st.session_state.file_path = tmp.name
|
| 125 |
+
st.session_state.file_name = uploaded_file.name
|
| 126 |
+
st.session_state.temp_file = tmp.name
|
| 127 |
+
st.sidebar.success(f"✅ Chargé : {uploaded_file.name} ({uploaded_file.size / (1024*1024):.1f} Mo)")
|
| 128 |
+
st.rerun()
|
| 129 |
+
except Exception as e:
|
| 130 |
+
st.sidebar.error(f"❌ Erreur upload : {str(e)}")
|
| 131 |
+
|
| 132 |
+
# === MAIN CONTENT ===
|
| 133 |
st.title("⚡ Comparaison de vitesse de chargement")
|
| 134 |
+
st.markdown("**Pandas vs Polars vs DuckDB vs PyArrow** - Qui gagne en 2025 ?")
|
| 135 |
|
| 136 |
+
if st.session_state.file_path is None:
|
| 137 |
+
st.info("👈 **Choisissez un fichier** dans la barre latérale (boutons de test ou upload)")
|
| 138 |
st.stop()
|
| 139 |
|
| 140 |
file_path = st.session_state.file_path
|
| 141 |
file_name = st.session_state.file_name
|
| 142 |
|
| 143 |
+
st.markdown(f"### 📊 Fichier actif : `{file_name}`")
|
| 144 |
|
| 145 |
+
# === BOUTONS DE LANCEMENT DANS LA SIDEBAR ===
|
| 146 |
+
st.sidebar.markdown("### 🚀 Lancer le test")
|
| 147 |
+
run_benchmark = st.sidebar.button("⚡ Benchmark Complet", use_container_width=True, type="primary", help="Teste tous les moteurs")
|
| 148 |
|
| 149 |
+
if run_benchmark:
|
| 150 |
+
st.markdown("### ⏱️ Résultats en direct")
|
| 151 |
+
|
| 152 |
results = []
|
| 153 |
+
errors = []
|
| 154 |
+
|
| 155 |
# === 1. Pandas ===
|
| 156 |
+
with st.spinner("🐼 Pandas (baseline)..."):
|
| 157 |
+
try:
|
| 158 |
+
df, t = load_with_pandas(file_path)
|
| 159 |
+
results.append(("🐼 Pandas", t, len(df)))
|
| 160 |
+
st.success(f"✅ Pandas → {t:.3f}s | {len(df):,} lignes")
|
| 161 |
+
except Exception as e:
|
| 162 |
+
errors.append(("🐼 Pandas", str(e)))
|
| 163 |
+
st.error(f"❌ Pandas : {str(e)}")
|
| 164 |
|
| 165 |
# === 2. Polars ===
|
| 166 |
+
with st.spinner("⚡ Polars (le challenger)..."):
|
| 167 |
+
try:
|
| 168 |
+
df, t = load_with_polars(file_path)
|
| 169 |
+
results.append(("⚡ Polars", t, len(df)))
|
| 170 |
+
st.success(f"✅ Polars → {t:.3f}s | {len(df):,} lignes")
|
| 171 |
+
except Exception as e:
|
| 172 |
+
errors.append(("⚡ Polars", str(e)))
|
| 173 |
+
st.error(f"❌ Polars : {str(e)}")
|
| 174 |
|
| 175 |
# === 3. DuckDB ===
|
| 176 |
+
with st.spinner("🦆 DuckDB (SQL magic)..."):
|
| 177 |
+
try:
|
| 178 |
+
df, t = load_with_duckdb(file_path)
|
| 179 |
+
results.append(("🦆 DuckDB", t, len(df)))
|
| 180 |
+
st.success(f"✅ DuckDB → {t:.3f}s | {len(df):,} lignes")
|
| 181 |
+
except Exception as e:
|
| 182 |
+
errors.append(("🦆 DuckDB", str(e)))
|
| 183 |
+
st.error(f"❌ DuckDB : {str(e)}")
|
| 184 |
|
| 185 |
# === 4. PyArrow ===
|
| 186 |
+
with st.spinner("🏹 PyArrow (C++ power)..."):
|
| 187 |
+
try:
|
| 188 |
+
df, t = load_with_pyarrow(file_path)
|
| 189 |
+
results.append(("🏹 PyArrow", t, len(df)))
|
| 190 |
+
st.success(f"✅ PyArrow → {t:.3f}s | {len(df):,} lignes")
|
| 191 |
+
except Exception as e:
|
| 192 |
+
errors.append(("🏹 PyArrow", str(e)))
|
| 193 |
+
st.error(f"❌ PyArrow : {str(e)}")
|
| 194 |
+
|
| 195 |
+
# === NETTOYAGE TEMP FILE ===
|
| 196 |
+
if st.session_state.temp_file:
|
| 197 |
try:
|
| 198 |
os.unlink(st.session_state.temp_file)
|
| 199 |
+
st.session_state.temp_file = None
|
| 200 |
except:
|
| 201 |
pass
|
| 202 |
|
| 203 |
+
# === AFFICHAGE ERREURS SI IL Y EN A ===
|
| 204 |
+
if errors:
|
| 205 |
+
st.error("⚠️ Erreurs rencontrées :")
|
| 206 |
+
for lib, err in errors:
|
| 207 |
+
st.write(f"**{lib}** : {err}")
|
| 208 |
+
|
| 209 |
+
# === GRAPHIQUE FINAL (SEULEMENT SI RÉSULTATS VALIDES) ===
|
| 210 |
+
if results:
|
| 211 |
+
results_df = pd.DataFrame(results, columns=["Moteur", "Temps (s)", "Lignes"]).sort_values("Temps (s)")
|
| 212 |
+
|
| 213 |
+
col1, col2 = st.columns(2)
|
| 214 |
+
with col1:
|
| 215 |
+
st.metric("🏆 Vainqueur", results_df.iloc[0]["Moteur"])
|
| 216 |
+
st.metric("Temps min", f"{results_df.iloc[0]['Temps (s)']:.3f}s")
|
| 217 |
+
|
| 218 |
+
with col2:
|
| 219 |
+
st.metric("📊 Fichier", f"{len(results_df.iloc[0]['Lignes']):,} lignes")
|
| 220 |
+
st.metric("Moteurs testés", len(results_df))
|
| 221 |
+
|
| 222 |
+
fig, ax = plt.subplots(figsize=(10, 6))
|
| 223 |
+
colors = ["#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4"]
|
| 224 |
+
bars = ax.barh(results_df["Moteur"], results_df["Temps (s)"], color=colors)
|
| 225 |
+
|
| 226 |
+
max_time = results_df["Temps (s)"].max()
|
| 227 |
+
for i, bar in enumerate(bars):
|
| 228 |
+
width = bar.get_width()
|
| 229 |
+
ax.text(width + max_time * 0.01, bar.get_y() + bar.get_height()/2,
|
| 230 |
+
f'{width:.3f}s', va='center', fontweight='bold', fontsize=12)
|
| 231 |
+
|
| 232 |
+
ax.set_xlabel("Temps de chargement (secondes)", fontsize=12)
|
| 233 |
+
ax.set_title(f"🏆 {results_df.iloc[0]['Moteur']} domine ! ({results_df.iloc[0]['Temps (s)']:.3f}s)",
|
| 234 |
+
fontsize=16, fontweight="bold", color="#1A5F7A")
|
| 235 |
+
ax.invert_yaxis()
|
| 236 |
+
ax.grid(axis='x', alpha=0.3)
|
| 237 |
+
|
| 238 |
+
st.pyplot(fig)
|
| 239 |
+
plt.close(fig)
|
| 240 |
+
|
| 241 |
+
# === BALLOONS POUR LA JOIE ===
|
| 242 |
+
st.balloons()
|
| 243 |
+
|
| 244 |
+
st.markdown("### 🔥 **Insights 2025 : Polars explose souvent Pandas ×3-5 !**")
|
| 245 |
+
|
| 246 |
+
# === FOOTER ===
|
| 247 |
+
st.markdown("---")
|
| 248 |
+
st.markdown("*App benchmarkée sur Hugging Face Spaces - Décembre 2025*")
|