Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,45 +2,50 @@ import streamlit as st
|
|
| 2 |
import pandas as pd
|
| 3 |
import duckdb
|
| 4 |
import polars as pl
|
| 5 |
-
import matplotlib.pyplot as plt
|
| 6 |
-
import numpy as np
|
| 7 |
import time
|
| 8 |
import os
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
#
|
| 11 |
st.set_page_config(
|
| 12 |
page_title="Comparaison de vitesse de chargement des données",
|
| 13 |
layout="wide"
|
| 14 |
)
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
# --- FONCTION DE CHARGEMENT TECHNIQUE ---
|
| 17 |
def load_file_and_measure_time(file_path, library, file_ext, read_kwargs):
|
| 18 |
try:
|
| 19 |
start_time = time.time()
|
| 20 |
df = None
|
| 21 |
-
|
| 22 |
# --- PARQUET ---
|
| 23 |
if file_ext == '.parquet':
|
| 24 |
-
if library == 'pandas':
|
| 25 |
df = pd.read_parquet(file_path)
|
| 26 |
-
elif library == 'modin':
|
| 27 |
-
import modin.pandas as mpd
|
| 28 |
-
df = mpd.read_parquet(file_path)
|
| 29 |
elif library == 'duckdb':
|
| 30 |
con = duckdb.connect()
|
| 31 |
df = con.execute(f"SELECT * FROM read_parquet('{file_path}')").fetchdf()
|
| 32 |
con.close()
|
| 33 |
-
elif library == 'polars':
|
| 34 |
df = pl.read_parquet(file_path)
|
| 35 |
|
| 36 |
# --- EXCEL ---
|
| 37 |
elif file_ext in ['.xlsx', '.xls']:
|
| 38 |
sheet_idx = read_kwargs.get('sheet_idx', 0)
|
| 39 |
header = 0 if read_kwargs.get('header') else None
|
| 40 |
-
if library
|
| 41 |
-
|
| 42 |
-
df = lib.read_excel(file_path, sheet_name=sheet_idx, header=header)
|
| 43 |
elif library == 'duckdb':
|
|
|
|
| 44 |
df = pd.read_excel(file_path, sheet_name=sheet_idx, header=header)
|
| 45 |
elif library == 'polars':
|
| 46 |
df = pl.read_excel(file_path, sheet_id=sheet_idx + 1)
|
|
@@ -48,9 +53,8 @@ def load_file_and_measure_time(file_path, library, file_ext, read_kwargs):
|
|
| 48 |
# --- CSV ---
|
| 49 |
else:
|
| 50 |
header_val = 0 if read_kwargs.get('header') else None
|
| 51 |
-
if library
|
| 52 |
-
|
| 53 |
-
df = lib_read(file_path, sep=None, engine='python', header=header_val)
|
| 54 |
elif library == 'duckdb':
|
| 55 |
con = duckdb.connect()
|
| 56 |
header_flag = "TRUE" if read_kwargs.get('header') else "FALSE"
|
|
@@ -64,102 +68,164 @@ def load_file_and_measure_time(file_path, library, file_ext, read_kwargs):
|
|
| 64 |
except Exception as e:
|
| 65 |
return f"Erreur: {e}", 0
|
| 66 |
|
| 67 |
-
# ---
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
if
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import pandas as pd
|
| 3 |
import duckdb
|
| 4 |
import polars as pl
|
|
|
|
|
|
|
| 5 |
import time
|
| 6 |
import os
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
import numpy as np
|
| 9 |
|
| 10 |
+
# Configuration de la page Streamlit
|
| 11 |
st.set_page_config(
|
| 12 |
page_title="Comparaison de vitesse de chargement des données",
|
| 13 |
layout="wide"
|
| 14 |
)
|
| 15 |
|
| 16 |
+
# --- AVERTISSEMENT MODIN/RAY ---
|
| 17 |
+
st.sidebar.info("""
|
| 18 |
+
⚠️ **Note sur Modin/Ray** : Ces librairies nécessitent un cluster multi-machines
|
| 19 |
+
pour être efficaces. Sur Hugging Face Spaces (2 CPU, 16GB RAM), elles seraient
|
| 20 |
+
**plus lentes** que Pandas à cause de leur overhead. Cette version compare donc
|
| 21 |
+
**Pandas, DuckDB et Polars** qui sont optimisés pour une seule machine.
|
| 22 |
+
""")
|
| 23 |
+
|
| 24 |
# --- FONCTION DE CHARGEMENT TECHNIQUE ---
|
| 25 |
def load_file_and_measure_time(file_path, library, file_ext, read_kwargs):
|
| 26 |
try:
|
| 27 |
start_time = time.time()
|
| 28 |
df = None
|
| 29 |
+
|
| 30 |
# --- PARQUET ---
|
| 31 |
if file_ext == '.parquet':
|
| 32 |
+
if library == 'pandas':
|
| 33 |
df = pd.read_parquet(file_path)
|
|
|
|
|
|
|
|
|
|
| 34 |
elif library == 'duckdb':
|
| 35 |
con = duckdb.connect()
|
| 36 |
df = con.execute(f"SELECT * FROM read_parquet('{file_path}')").fetchdf()
|
| 37 |
con.close()
|
| 38 |
+
elif library == 'polars':
|
| 39 |
df = pl.read_parquet(file_path)
|
| 40 |
|
| 41 |
# --- EXCEL ---
|
| 42 |
elif file_ext in ['.xlsx', '.xls']:
|
| 43 |
sheet_idx = read_kwargs.get('sheet_idx', 0)
|
| 44 |
header = 0 if read_kwargs.get('header') else None
|
| 45 |
+
if library == 'pandas':
|
| 46 |
+
df = pd.read_excel(file_path, sheet_name=sheet_idx, header=header)
|
|
|
|
| 47 |
elif library == 'duckdb':
|
| 48 |
+
# DuckDB utilise pandas pour Excel
|
| 49 |
df = pd.read_excel(file_path, sheet_name=sheet_idx, header=header)
|
| 50 |
elif library == 'polars':
|
| 51 |
df = pl.read_excel(file_path, sheet_id=sheet_idx + 1)
|
|
|
|
| 53 |
# --- CSV ---
|
| 54 |
else:
|
| 55 |
header_val = 0 if read_kwargs.get('header') else None
|
| 56 |
+
if library == 'pandas':
|
| 57 |
+
df = pd.read_csv(file_path, sep=None, engine='python', header=header_val)
|
|
|
|
| 58 |
elif library == 'duckdb':
|
| 59 |
con = duckdb.connect()
|
| 60 |
header_flag = "TRUE" if read_kwargs.get('header') else "FALSE"
|
|
|
|
| 68 |
except Exception as e:
|
| 69 |
return f"Erreur: {e}", 0
|
| 70 |
|
| 71 |
+
# --- GESTION DU FICHIER CIBLE DANS LE SESSION STATE ---
|
| 72 |
+
if 'target_file' not in st.session_state:
|
| 73 |
+
st.session_state.target_file = None
|
| 74 |
+
if 'file_ext' not in st.session_state:
|
| 75 |
+
st.session_state.file_ext = None
|
| 76 |
+
|
| 77 |
+
st.title("⚡ Comparaison de vitesse de chargement des données")
|
| 78 |
+
st.markdown("Téléchargez un fichier **CSV, Excel ou Parquet** pour comparer **Pandas**, **DuckDB** et **Polars**.")
|
| 79 |
+
|
| 80 |
+
# --- SIDEBAR ---
|
| 81 |
+
st.sidebar.header("⚙️ Paramètres du fichier")
|
| 82 |
+
|
| 83 |
+
# Boutons de démo
|
| 84 |
+
st.sidebar.subheader("🧪 Fichiers de test (30Mo)")
|
| 85 |
+
c1, c2 = st.sidebar.columns(2)
|
| 86 |
+
if c1.button("📄 Faker Text"):
|
| 87 |
+
st.session_state.target_file = "faker_text.csv"
|
| 88 |
+
st.session_state.file_ext = ".csv"
|
| 89 |
+
if c2.button("📊 Numeric Only"):
|
| 90 |
+
st.session_state.target_file = "numeric_only.csv"
|
| 91 |
+
st.session_state.file_ext = ".csv"
|
| 92 |
+
|
| 93 |
+
# Uploader manuel
|
| 94 |
+
uploaded_file = st.sidebar.file_uploader("Ou choisissez un fichier", type=["csv", "parquet", "xlsx", "xls"])
|
| 95 |
+
if uploaded_file is not None:
|
| 96 |
+
file_ext = os.path.splitext(uploaded_file.name)[1].lower()
|
| 97 |
+
temp_path = f"temp_upload{file_ext}"
|
| 98 |
+
with open(temp_path, "wb") as f:
|
| 99 |
+
f.write(uploaded_file.getbuffer())
|
| 100 |
+
st.session_state.target_file = temp_path
|
| 101 |
+
st.session_state.file_ext = file_ext
|
| 102 |
+
|
| 103 |
+
# --- ACTIONS ET AFFICHAGE ---
|
| 104 |
+
if st.session_state.target_file is not None:
|
| 105 |
+
st.sidebar.success(f"Actif : **{st.session_state.target_file}**")
|
| 106 |
+
|
| 107 |
+
has_header = st.sidebar.radio("Ligne de titres en première ligne ?", ["Oui", "Non"], index=0) == "Oui"
|
| 108 |
+
read_kwargs = {'header': has_header}
|
| 109 |
+
|
| 110 |
+
if st.session_state.file_ext in ['.xlsx', '.xls']:
|
| 111 |
+
sheet_num = st.sidebar.number_input("Numéro de l'onglet (1 = premier)", min_value=1, value=1)
|
| 112 |
+
read_kwargs['sheet_idx'] = sheet_num - 1
|
| 113 |
+
|
| 114 |
+
run_comparison = st.sidebar.button("⚡ Lancer la comparaison")
|
| 115 |
+
|
| 116 |
+
if run_comparison:
|
| 117 |
+
st.subheader("⏱️ Résultats de la vitesse de chargement")
|
| 118 |
+
|
| 119 |
+
# Librairies optimisées pour une seule machine
|
| 120 |
+
libraries = {
|
| 121 |
+
'Pandas (Baseline)': 'pandas',
|
| 122 |
+
'DuckDB': 'duckdb',
|
| 123 |
+
'Polars': 'polars'
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
results = []
|
| 127 |
+
|
| 128 |
+
for lib_name, lib_key in libraries.items():
|
| 129 |
+
with st.spinner(f"Test en cours : **{lib_name}**..."):
|
| 130 |
+
load_time, row_count = load_file_and_measure_time(
|
| 131 |
+
st.session_state.target_file,
|
| 132 |
+
lib_key,
|
| 133 |
+
st.session_state.file_ext,
|
| 134 |
+
read_kwargs
|
| 135 |
+
)
|
| 136 |
+
results.append({
|
| 137 |
+
'Librairie': lib_name,
|
| 138 |
+
'Temps de chargement (s)': load_time,
|
| 139 |
+
'Nombre de lignes': row_count
|
| 140 |
+
})
|
| 141 |
+
|
| 142 |
+
results_df = pd.DataFrame(results)
|
| 143 |
+
|
| 144 |
+
valid_counts = results_df[results_df['Nombre de lignes'] > 0]['Nombre de lignes']
|
| 145 |
+
if not valid_counts.empty:
|
| 146 |
+
st.markdown(f"**Nombre de lignes détectées :** **{int(valid_counts.iloc[0]):,}**".replace(',', ' '))
|
| 147 |
+
|
| 148 |
+
chart_data = results_df[results_df['Temps de chargement (s)'].apply(lambda x: isinstance(x, (int, float)))]
|
| 149 |
+
|
| 150 |
+
if not chart_data.empty:
|
| 151 |
+
chart_data = chart_data.sort_values(by='Temps de chargement (s)', ascending=True)
|
| 152 |
+
|
| 153 |
+
# Affichage du tableau
|
| 154 |
+
st.dataframe(
|
| 155 |
+
chart_data[['Librairie', 'Temps de chargement (s)']].style.format({
|
| 156 |
+
'Temps de chargement (s)': '{:.4f}s'
|
| 157 |
+
}),
|
| 158 |
+
use_container_width=True,
|
| 159 |
+
hide_index=True
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
# Graphique
|
| 163 |
+
fig, ax = plt.subplots(figsize=(8, 3))
|
| 164 |
+
colors = ['#4CAF50', '#FFC107', '#E91E63']
|
| 165 |
+
bars = ax.barh(
|
| 166 |
+
chart_data['Librairie'],
|
| 167 |
+
chart_data['Temps de chargement (s)'],
|
| 168 |
+
color=colors[:len(chart_data)]
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
max_time = chart_data['Temps de chargement (s)'].max()
|
| 172 |
+
ax.set_xlim(right=max_time * 1.35)
|
| 173 |
+
|
| 174 |
+
for bar in bars:
|
| 175 |
+
ax.text(
|
| 176 |
+
bar.get_width() + (max_time * 0.03),
|
| 177 |
+
bar.get_y() + bar.get_height()/2,
|
| 178 |
+
f'{bar.get_width():.4f}s',
|
| 179 |
+
va='center',
|
| 180 |
+
fontsize=10,
|
| 181 |
+
fontweight='bold'
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
ax.set_xlabel('Temps (secondes)', fontsize=11)
|
| 185 |
+
ax.set_title('Comparaison de vitesse de chargement', fontsize=12, fontweight='bold')
|
| 186 |
+
ax.grid(axis='x', alpha=0.3, linestyle='--')
|
| 187 |
+
|
| 188 |
+
st.pyplot(fig)
|
| 189 |
+
plt.close(fig)
|
| 190 |
+
|
| 191 |
+
# Insights
|
| 192 |
+
fastest = chart_data.iloc[0]
|
| 193 |
+
slowest = chart_data.iloc[-1]
|
| 194 |
+
speedup = slowest['Temps de chargement (s)'] / fastest['Temps de chargement (s)']
|
| 195 |
+
|
| 196 |
+
st.success(f"""
|
| 197 |
+
🏆 **{fastest['Librairie']}** est le plus rapide avec **{fastest['Temps de chargement (s)']:.4f}s**
|
| 198 |
+
|
| 199 |
+
📈 Amélioration : **{speedup:.2f}x plus rapide** que {slowest['Librairie']}
|
| 200 |
+
""")
|
| 201 |
+
|
| 202 |
+
else:
|
| 203 |
+
st.info("👈 Veuillez charger un fichier ou utiliser un bouton de test à gauche.")
|
| 204 |
+
|
| 205 |
+
# Documentation
|
| 206 |
+
with st.expander("📚 À propos des librairies testées"):
|
| 207 |
+
st.markdown("""
|
| 208 |
+
### Pandas
|
| 209 |
+
- **Baseline** standard pour le traitement de données en Python
|
| 210 |
+
- Excellent pour datasets moyens (<1GB)
|
| 211 |
+
- API très riche et mature
|
| 212 |
+
|
| 213 |
+
### DuckDB
|
| 214 |
+
- Base de données analytique **ultra-rapide**
|
| 215 |
+
- Optimisé pour les requêtes SQL sur CSV/Parquet
|
| 216 |
+
- Très efficace sur les fichiers colonnes
|
| 217 |
+
|
| 218 |
+
### Polars
|
| 219 |
+
- Framework **moderne** écrit en Rust
|
| 220 |
+
- Parallélisation automatique sur CPU
|
| 221 |
+
- Excellentes performances sur gros volumes
|
| 222 |
+
|
| 223 |
+
---
|
| 224 |
+
|
| 225 |
+
**Pourquoi pas Modin/Ray/Dask ?**
|
| 226 |
+
|
| 227 |
+
Ces librairies nécessitent un **cluster multi-machines** pour être efficaces.
|
| 228 |
+
Sur une machine unique (comme HF Spaces), leur overhead les rend **plus lentes**
|
| 229 |
+
que Pandas. Elles excellent sur des datasets de plusieurs TB distribués sur
|
| 230 |
+
dizaines de machines avec GPU.
|
| 231 |
+
""")
|