Spaces:
Runtime error
Runtime error
Download frontend/web/modules/data_converter.py from DesarrolloTT/DataSuitePro: direct link, hf CLI and curl.
- Browser
- Download file 32.1 kB
-
https://huggingface.co/spaces/DesarrolloTT/DataSuitePro/resolve/main/frontend/web/modules/data_converter.py
- Command line
-
hf download hf://spaces/DesarrolloTT/DataSuitePro/frontend/web/modules/data_converter.py
-
curl -L -o data_converter.py https://huggingface.co/spaces/DesarrolloTT/DataSuitePro/resolve/main/frontend/web/modules/data_converter.py
32.1 kB
| import streamlit as st | |
| import pandas as pd | |
| import json | |
| import io | |
| import sqlite3 | |
| import tempfile | |
| import os | |
| import numpy as np | |
| from datetime import datetime | |
| import re | |
| from metrics_dashboard import MetricsDashboard | |
| # CREAR LA INSTANCIA: | |
| metrics_dashboard = MetricsDashboard() | |
| def get_dataframe(uploaded_file): | |
| """Lee el archivo manteniendo los formatos originales como texto""" | |
| try: | |
| if uploaded_file.name.endswith(('.xlsx', '.xls')): | |
| # Leer Excel como texto puro sin inferencia | |
| df = pd.read_excel(uploaded_file, dtype=str, engine='openpyxl') | |
| # Reemplazar NaN con strings vacíos | |
| df = df.fillna('') | |
| return df | |
| elif uploaded_file.name.endswith('.csv'): | |
| # Leer CSV como texto puro | |
| df = pd.read_csv(uploaded_file, dtype=str, encoding='utf-8') | |
| df = df.fillna('') | |
| return df | |
| elif uploaded_file.name.endswith('.json'): | |
| # Para JSON, cargar y convertir todo a string | |
| df = pd.read_json(uploaded_file) | |
| # Convertir todas las columnas a string | |
| for col in df.columns: | |
| df[col] = df[col].astype(str) | |
| return df | |
| except Exception as e: | |
| st.error(f"Error leyendo archivo: {str(e)}") | |
| return None | |
| def generate_json_output(df, json_format, minify=False, force_ascii=True, limit=None): | |
| """Genera salida JSON formateada correctamente""" | |
| try: | |
| indent = None if minify else 2 | |
| # Limitar datos para vista previa si se especifica | |
| preview_df = df.head(limit) if limit else df | |
| if json_format == "records-web": | |
| # Formato especial records-web - similar a records pero optimizado | |
| json_str = preview_df.to_json(orient="records", force_ascii=force_ascii, indent=indent) | |
| else: | |
| json_str = preview_df.to_json(orient=json_format, force_ascii=force_ascii, indent=indent) | |
| # Si está minificado, intentar formatearlo para mejor legibilidad | |
| if minify: | |
| try: | |
| # Parsear y reformatear para consistencia | |
| parsed_json = json.loads(json_str) | |
| json_str = json.dumps(parsed_json, separators=(',', ':'), ensure_ascii=force_ascii) | |
| except: | |
| # Si falla el parsing, mantener el original | |
| pass | |
| return json_str | |
| except Exception as e: | |
| return f"Error generando JSON: {str(e)}" | |
| def normalize_column_names(df): | |
| """Normaliza nombres de columnas""" | |
| df_clean = df.copy() | |
| df_clean.columns = [str(col).strip().lower().replace(' ', '_').replace('.', '_') for col in df_clean.columns] | |
| return df_clean | |
| def handle_missing_values(df, strategy='drop'): | |
| """Maneja valores faltantes según la estrategia seleccionada""" | |
| df_clean = df.copy() | |
| if strategy == 'drop': | |
| df_clean = df_clean.dropna() | |
| elif strategy == 'fill_zero': | |
| df_clean = df_clean.fillna(0) | |
| elif strategy == 'fill_mean': | |
| numeric_cols = df_clean.select_dtypes(include=[np.number]).columns | |
| df_clean[numeric_cols] = df_clean[numeric_cols].fillna(df_clean[numeric_cols].mean()) | |
| elif strategy == 'fill_median': | |
| numeric_cols = df_clean.select_dtypes(include=[np.number]).columns | |
| df_clean[numeric_cols] = df_clean[numeric_cols].fillna(df_clean[numeric_cols].median()) | |
| return df_clean | |
| def clean_and_convert_value(value, col_name): | |
| """Limpia y convierte un valor basado en el nombre de la columna - VERSIÓN MEJORADA""" | |
| if value is None or value == '' or str(value).lower() in ['nan', 'null', 'none']: | |
| return '' | |
| str_value = str(value).strip() | |
| col_lower = col_name.lower() | |
| # Limpiar caracteres problemáticos | |
| cleaned = re.sub(r'[,"\']', '', str_value) | |
| # MEJORA: Para columnas de fecha, detectar y preservar formatos de fecha | |
| if any(keyword in col_lower for keyword in ['fecha', 'date']): | |
| # Intentar detectar si es un timestamp numérico grande | |
| if cleaned.isdigit() and len(cleaned) > 10: | |
| try: | |
| # Si es un número muy grande, podría ser timestamp en milisegundos o nanosegundos | |
| timestamp = int(cleaned) | |
| # Si es mayor a 1e12, probablemente esté en nanosegundos, convertir a milisegundos | |
| if timestamp > 1e12: | |
| timestamp = timestamp // 1000000 # Convertir nanosegundos a milisegundos | |
| # Convertir timestamp a datetime | |
| dt = datetime.fromtimestamp(timestamp / 1000.0) | |
| return dt.strftime('%Y-%m-%d %H:%M:%S') | |
| except (ValueError, OSError, OverflowError): | |
| # Si falla la conversión, mantener el valor original | |
| return cleaned | |
| # Si ya tiene formato de fecha, mantenerlo | |
| date_patterns = [ | |
| r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}', | |
| r'\d{4}-\d{2}-\d{2}', | |
| r'\d{2}/\d{2}/\d{4}', | |
| r'\d{2}-\d{2}-\d{4}' | |
| ] | |
| for pattern in date_patterns: | |
| if re.match(pattern, cleaned): | |
| return cleaned | |
| # Para otros valores de fecha, devolver limpio | |
| return cleaned | |
| # Para columnas numéricas, extraer solo números | |
| if any(keyword in col_lower for keyword in ['dni', 'id', 'cedula', 'documento', 'cp', 'codigo_postal', 'zip', 'edad', 'age']): | |
| # Extraer solo dígitos | |
| numbers = re.findall(r'\d+', cleaned) | |
| if numbers: | |
| return int(''.join(numbers)) | |
| return 0 | |
| elif any(keyword in col_lower for keyword in ['limite', 'credito', 'monto', 'valor', 'saldo', 'volumen_compra']): | |
| # Para montos, permitir decimales | |
| numbers = re.findall(r'\d+\.?\d*', cleaned) | |
| if numbers: | |
| return float(numbers[0]) | |
| return 0.0 | |
| elif any(keyword in col_lower for keyword in ['primera_compra', 'activo', 'estado']): | |
| # Para booleanos - MEJORADO: no convertir 'estado' textual como CDMX | |
| if col_lower == 'estado': | |
| # Para columna 'estado', mantener valores textuales | |
| return cleaned | |
| if str(cleaned).lower() in ['1', 'true', 'si', 'sí', 'yes', 'verdadero']: | |
| return 1 | |
| return 0 | |
| else: | |
| # Para texto, devolver limpio | |
| return cleaned | |
| def force_exact_types(df): | |
| """Fuerza tipos exactos basándose en nombres de columnas - VERSIÓN MEJORADA""" | |
| df_clean = df.copy() | |
| # Aplicar limpieza y conversión a cada celda | |
| for col in df_clean.columns: | |
| df_clean[col] = df_clean[col].apply(lambda x: clean_and_convert_value(x, col)) | |
| return df_clean | |
| def get_data_quality_report(df): | |
| """Genera reporte de calidad de datos""" | |
| total_cells = df.size | |
| missing_cells = df.isna().sum().sum() | |
| duplicate_rows = df.duplicated().sum() | |
| # Detectar columnas constantes | |
| constant_columns = [] | |
| for col in df.columns: | |
| if df[col].nunique() <= 1: | |
| constant_columns.append(col) | |
| # Calcular puntuación de calidad (simplificado) | |
| quality_score = max(0, 100 - (missing_cells / total_cells * 100) - (duplicate_rows / len(df) * 100)) | |
| return { | |
| 'quality_score': round(quality_score, 1), | |
| 'missing_cells': missing_cells, | |
| 'total_rows': len(df), | |
| 'total_columns': len(df.columns), | |
| 'missing_percentage': round((missing_cells / total_cells) * 100, 2), | |
| 'total_cells': total_cells, | |
| 'duplicate_rows': duplicate_rows, | |
| 'constant_columns': constant_columns, | |
| 'problems_detected': len(constant_columns) + (1 if missing_cells > 0 else 0) + (1 if duplicate_rows > 0 else 0) | |
| } | |
| def process_sql_file(uploaded_file): | |
| """Procesa archivos SQL/SQLite y extrae datos para conversión""" | |
| try: | |
| if uploaded_file.name.endswith(('.db', '.sqlite')): | |
| # Es una base de datos SQLite | |
| with tempfile.NamedTemporaryFile(delete=False, suffix='.db') as tmp_file: | |
| tmp_file.write(uploaded_file.read()) | |
| tmp_path = tmp_file.name | |
| # Conectar y extraer datos | |
| conn = sqlite3.connect(tmp_path) | |
| cursor = conn.cursor() | |
| # Obtener lista de tablas | |
| cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") | |
| tables = cursor.fetchall() | |
| if tables: | |
| # Usar la primera tabla por defecto | |
| table_name = tables[0][0] | |
| df = pd.read_sql_query(f"SELECT * FROM {table_name}", conn) | |
| st.session_state.global_uploaded_file = uploaded_file | |
| st.session_state.global_df = df | |
| st.session_state.global_data = df.to_dict('records') | |
| st.session_state.sql_tables = [table[0] for table in tables] | |
| st.session_state.current_sql_table = table_name | |
| st.success(f"✅ Base de datos cargada: {len(tables)} tablas encontradas") | |
| st.info(f"📊 Mostrando datos de la tabla: **{table_name}**") | |
| # Selector para cambiar de tabla | |
| if len(tables) > 1: | |
| selected_table = st.selectbox( | |
| "Seleccionar tabla:", | |
| st.session_state.sql_tables, | |
| index=st.session_state.sql_tables.index(table_name) | |
| ) | |
| if selected_table != st.session_state.current_sql_table: | |
| df = pd.read_sql_query(f"SELECT * FROM {selected_table}", conn) | |
| st.session_state.global_df = df | |
| st.session_state.global_data = df.to_dict('records') | |
| st.session_state.current_sql_table = selected_table | |
| st.rerun() | |
| conn.close() | |
| os.unlink(tmp_path) # Limpiar archivo temporal | |
| elif uploaded_file.name.endswith('.sql'): | |
| # Es un archivo SQL con sentencias | |
| sql_content = uploaded_file.read().decode('utf-8') | |
| st.session_state.sql_content = sql_content | |
| st.info("📝 Archivo SQL cargado. Usa la conversión 'SQL a ...' para exportar") | |
| except Exception as e: | |
| st.error(f"❌ Error procesando archivo SQL: {str(e)}") | |
| def convert_to_format(df, conversion_type): | |
| """Convierte DataFrame a diferentes formatos""" | |
| output = None | |
| filename = f"converted_data_{pd.Timestamp.now().strftime('%Y%m%d_%H%M%S')}" | |
| try: | |
| if conversion_type == "CSV a Excel": | |
| output_buffer = io.BytesIO() | |
| with pd.ExcelWriter(output_buffer, engine='xlsxwriter') as writer: | |
| df.to_excel(writer, index=False, sheet_name='Datos') | |
| output = output_buffer.getvalue() | |
| filename += ".xlsx" | |
| mime_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" | |
| elif conversion_type == "Excel a CSV": | |
| output = df.to_csv(index=False) | |
| filename += ".csv" | |
| mime_type = "text/csv" | |
| elif conversion_type == "JSON a CSV": | |
| output = df.to_csv(index=False) | |
| filename += ".csv" | |
| mime_type = "text/csv" | |
| elif conversion_type == "JSON a Excel": | |
| output_buffer = io.BytesIO() | |
| with pd.ExcelWriter(output_buffer, engine='xlsxwriter') as writer: | |
| df.to_excel(writer, index=False, sheet_name='Datos') | |
| output = output_buffer.getvalue() | |
| filename += ".xlsx" | |
| mime_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" | |
| elif conversion_type == "CSV a JSON": | |
| output = df.to_json(orient="records", indent=2) | |
| filename += ".json" | |
| mime_type = "application/json" | |
| elif conversion_type == "Excel a JSON": | |
| output = df.to_json(orient="records", indent=2) | |
| filename += ".json" | |
| mime_type = "application/json" | |
| elif conversion_type in ["SQL a CSV", "SQL a Excel", "SQL a JSON"]: | |
| # Para conversiones desde SQL, el DataFrame ya está cargado | |
| if conversion_type == "SQL a CSV": | |
| output = df.to_csv(index=False) | |
| filename += ".csv" | |
| mime_type = "text/csv" | |
| elif conversion_type == "SQL a Excel": | |
| output_buffer = io.BytesIO() | |
| with pd.ExcelWriter(output_buffer, engine='xlsxwriter') as writer: | |
| df.to_excel(writer, index=False, sheet_name='Datos') | |
| output = output_buffer.getvalue() | |
| filename += ".xlsx" | |
| mime_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" | |
| elif conversion_type == "SQL a JSON": | |
| output = df.to_json(orient="records", indent=2) | |
| filename += ".json" | |
| mime_type = "application/json" | |
| if output is not None: | |
| st.session_state.conversion_output = output | |
| st.session_state.conversion_filename = filename | |
| st.session_state.conversion_mime = mime_type | |
| st.session_state.conversion_type = conversion_type | |
| return output | |
| except Exception as e: | |
| st.error(f"Error en conversión: {str(e)}") | |
| return None | |
| def show_detailed_dataset_info(df, filename): | |
| """Muestra información detallada del dataset en formato JSON expandible""" | |
| # Construir objeto JSON con la información | |
| info_json = { | |
| "Nombre del Archivo": filename, | |
| "Columnas Detectadas": {i: str(col) for i, col in enumerate(df.columns)}, | |
| "Tipos de Datos": {col: str(dtype) for col, dtype in df.dtypes.items()}, | |
| "Filas": len(df), | |
| "Columnas": len(df.columns), | |
| "Celdas Totales": df.size, | |
| "Memoria Usada (MB)": round(df.memory_usage(deep=True).sum() / 1024 / 1024, 2), | |
| "Filas Duplicadas": int(df.duplicated().sum()), | |
| "Celdas Faltantes": int(df.isna().sum().sum()) | |
| } | |
| # Agregar información de fechas si existen columnas datetime | |
| date_columns = df.select_dtypes(include=['datetime64']).columns | |
| if len(date_columns) > 0: | |
| date_ranges = {} | |
| for col in date_columns: | |
| if df[col].notna().any(): | |
| min_date = df[col].min() | |
| max_date = df[col].max() | |
| date_ranges[col] = f"{min_date} to {max_date}" | |
| if date_ranges: | |
| info_json["Intervalo de Fechas"] = date_ranges | |
| # Agregar valores únicos por columna | |
| unique_counts = {col: int(df[col].nunique()) for col in df.columns} | |
| info_json["Valores Únicos por Columna"] = unique_counts | |
| # Agregar memoria por columna | |
| memory_by_col = {col: round(df[col].memory_usage(deep=True) / 1024 / 1024, 4) for col in df.columns} | |
| info_json["Memoria por Columna (MB)"] = memory_by_col | |
| # Mostrar en un expander con JSON formateado | |
| with st.expander("📋 Información Detallada del Dataset", expanded=False): | |
| st.json(info_json) | |
| def show_data_quality_report(df): | |
| """Muestra reporte de calidad de datos""" | |
| quality_report = get_data_quality_report(df) | |
| st.subheader("📊 Reporte de Calidad de Datos") | |
| # Métricas principales | |
| col1, col2, col3, col4 = st.columns(4) | |
| with col1: | |
| st.metric("Puntuación de Calidad", f"{quality_report['quality_score']}%") | |
| with col2: | |
| st.metric("Celdas Faltantes", quality_report['missing_cells']) | |
| with col3: | |
| st.metric("Total Filas", quality_report['total_rows']) | |
| with col4: | |
| st.metric("Total Columnas", quality_report['total_columns']) | |
| # Información adicional | |
| col5, col6 = st.columns(2) | |
| with col5: | |
| st.metric("Porcentaje Faltante", f"{quality_report['missing_percentage']}%") | |
| st.metric("Celdas Totales", quality_report['total_cells']) | |
| with col6: | |
| st.metric("Filas Duplicadas", quality_report['duplicate_rows']) | |
| st.metric("Problemas Detectados", quality_report['problems_detected']) | |
| # Problemas específicos | |
| if quality_report['constant_columns']: | |
| st.warning(f"**Columnas constantes:** {', '.join(quality_report['constant_columns'])}") | |
| if quality_report['missing_cells'] > 0: | |
| st.warning("**Valores faltantes detectados**") | |
| if quality_report['duplicate_rows'] > 0: | |
| st.warning("**Filas duplicadas detectadas**") | |
| def show_dataframe_info(df, filename): | |
| """Muestra información completa del DataFrame con todas las funcionalidades""" | |
| st.subheader("📊 Información Completa del Dataset") | |
| tab1, tab2, tab3, tab4, tab5, tab6 = st.tabs([ | |
| "Estructura", "Tipos de Datos", "Estadísticas", "Valores Únicos", "Calidad", "Muestras" | |
| ]) | |
| with tab1: | |
| show_detailed_dataset_info(df, filename) | |
| with tab2: | |
| dtype_info = pd.DataFrame({ | |
| 'Columna': df.columns, | |
| 'Tipo de Dato': df.dtypes.values, | |
| 'No Nulos': df.notna().sum().values, | |
| 'Nulos': df.isna().sum().values, | |
| 'Únicos': [df[col].nunique() for col in df.columns] | |
| }) | |
| st.dataframe(dtype_info, width='stretch', hide_index=True) | |
| with tab3: | |
| if df.select_dtypes(include=['number']).shape[1] > 0: | |
| st.dataframe(df.describe(), width='stretch') | |
| else: | |
| st.info("No hay columnas numéricas para mostrar estadísticas") | |
| with tab4: | |
| for col in df.columns: | |
| unique_vals = df[col].nunique() | |
| with st.expander(f"**{col}** - {unique_vals} valores únicos"): | |
| if unique_vals <= 20: | |
| value_counts = df[col].value_counts() | |
| st.dataframe(value_counts, width='stretch') | |
| else: | |
| st.write(f"Demasiados valores únicos ({unique_vals}) para mostrar") | |
| st.write("Top 10 valores:") | |
| top_values = df[col].value_counts().head(10) | |
| st.dataframe(top_values, width='stretch') | |
| with tab5: | |
| show_data_quality_report(df) | |
| with tab6: | |
| st.markdown("**Muestras Rápidas en Diferentes Formatos:**") | |
| sample_col1, sample_col2 = st.columns(2) | |
| with sample_col1: | |
| # Obtener formato JSON actual de session_state | |
| current_json_format = st.session_state.get('json_format', 'records') | |
| current_minify = st.session_state.get('json_minify', False) | |
| current_force_ascii = st.session_state.get('json_force_ascii', True) | |
| st.markdown(f"**JSON ({current_json_format}):**") | |
| sample_json = generate_json_output( | |
| df.head(2), # LIMITADO A 2 ELEMENTOS | |
| current_json_format, | |
| current_minify, | |
| current_force_ascii | |
| ) | |
| st.code(sample_json, language='json') | |
| with sample_col2: | |
| st.markdown("**CSV:**") | |
| sample_csv = df.head(2).to_csv(index=False) # LIMITADO A 2 ELEMENTOS | |
| st.code(sample_csv, language='text') | |
| st.markdown("**Excel Info:**") | |
| st.write(f"**Formato:** XLSX") | |
| st.write(f"**Filas:** {len(df)}") | |
| st.write(f"**Columnas:** {len(df.columns)}") | |
| def show(): | |
| st.header("📊 Conversor de Datos Completo") | |
| # Inicializar session_state si no existe | |
| if 'conversion_output' not in st.session_state: | |
| st.session_state.conversion_output = None | |
| if 'conversion_filename' not in st.session_state: | |
| st.session_state.conversion_filename = None | |
| if 'conversion_mime' not in st.session_state: | |
| st.session_state.conversion_mime = None | |
| if 'conversion_type' not in st.session_state: | |
| st.session_state.conversion_type = None | |
| if 'json_output' not in st.session_state: | |
| st.session_state.json_output = None | |
| if 'json_filename' not in st.session_state: | |
| st.session_state.json_filename = None | |
| # Layout de dos columnas | |
| col1, col2 = st.columns([1, 1]) | |
| with col1: | |
| st.subheader("📤 Información del Dataset") | |
| # Usar datos globales en lugar de cargar archivo nuevo | |
| if st.session_state.global_df is not None: | |
| df = st.session_state.global_df | |
| filename = st.session_state.global_filename | |
| st.success(f"✅ **{filename}** cargado desde el sistema global") | |
| # Mostrar info del dataset | |
| col_info1, col_info2, col_info3 = st.columns(3) | |
| with col_info1: | |
| st.metric("Filas", len(df)) | |
| with col_info2: | |
| st.metric("Columnas", len(df.columns)) | |
| with col_info3: | |
| st.metric("Tamaño", f"{df.memory_usage(deep=True).sum() / 1024 / 1024:.2f} MB") | |
| # OPCIONES AVANZADAS DE PROCESAMIENTO EN EXPANDER | |
| with st.expander("⚙️ Opciones Avanzadas de Procesamiento", expanded=False): | |
| adv_col1, adv_col2 = st.columns(2) | |
| with adv_col1: | |
| normalize_cols = st.checkbox("Normalizar nombres de columnas", value=True) | |
| remove_duplicates = st.checkbox("Eliminar filas duplicadas", value=True) | |
| with adv_col2: | |
| force_exact_types_option = st.checkbox("Forzar tipos exactos", value=True, | |
| help="Convierte DNI, CP, edades, montos a sus tipos correctos. MEJORADO: Maneja fechas correctamente") | |
| handle_missing = st.checkbox("Manejar valores faltantes", value=False) | |
| if handle_missing: | |
| missing_strategy = st.selectbox( | |
| "Estrategia para valores faltantes:", | |
| ["drop", "fill_zero", "fill_mean", "fill_median"] | |
| ) | |
| # Aplicar procesamiento | |
| processed_df = df.copy() | |
| if normalize_cols: | |
| processed_df = normalize_column_names(processed_df) | |
| if remove_duplicates: | |
| processed_df = processed_df.drop_duplicates() | |
| if force_exact_types_option: | |
| processed_df = force_exact_types(processed_df) | |
| if handle_missing: | |
| processed_df = handle_missing_values(processed_df, missing_strategy) | |
| # Guardar datos procesados para conversión | |
| st.session_state.df = processed_df | |
| st.session_state.data = processed_df.to_dict('records') | |
| # Vista previa de datos | |
| with st.expander("👀 Vista Previa de Datos", expanded=True): | |
| st.dataframe(processed_df.head(10), width='stretch') | |
| else: | |
| st.info("📤 Carga un archivo en la barra lateral para comenzar") | |
| return | |
| with col2: | |
| st.subheader("🔄 Opciones de Conversión") | |
| if st.session_state.get('df') is not None: | |
| df = st.session_state.df | |
| conversion_type = st.selectbox( | |
| "Selecciona el tipo de conversión:", | |
| [ | |
| "CSV a Excel", | |
| "CSV a JSON", | |
| "Excel a CSV", | |
| "Excel a JSON", | |
| "JSON a CSV", | |
| "JSON a Excel", | |
| "SQL a CSV", | |
| "SQL a Excel", | |
| "SQL a JSON" | |
| ] | |
| ) | |
| # OPCIONES PARA JSON (VISTA PREVIA LIMITADA) | |
| if "JSON" in conversion_type: | |
| st.markdown("**🎯 Formato JSON:**") | |
| json_col1, json_col2 = st.columns(2) | |
| with json_col1: | |
| json_format = st.selectbox( | |
| "Estructura:", | |
| ["records", "records-web", "split", "index", "values", "table"], | |
| key="json_format" | |
| ) | |
| with json_col2: | |
| minify = st.checkbox("Minificar", key="json_minify", value=False) | |
| force_ascii = st.checkbox("Forzar ASCII", key="json_force_ascii", value=True) | |
| # LEYENDAS DE FORMATOS JSON | |
| format_descriptions = { | |
| "records": "**Para APIs REST** - Lista de objetos, cada uno representa una fila", | |
| "records-web": "**Para proyectos web** - Como records pero optimizado para JavaScript", | |
| "split": "**Para metadatos** - Separa índices, columnas y datos", | |
| "index": "**Para datos indexados** - Índices como claves principales", | |
| "values": "**Minimalista** - Solo valores sin estructura", | |
| "table": "**Para esquemas** - Incluye schema y datos completos" | |
| } | |
| st.info(format_descriptions.get(json_format, "Selecciona un formato JSON")) | |
| # VISTA PREVIA EN TIEMPO REAL DE JSON (LIMITADA) | |
| st.markdown("**👁️ Vista Previa en Tiempo Real (2 elementos):**") | |
| try: | |
| json_output = generate_json_output( | |
| df, | |
| json_format, | |
| minify, | |
| force_ascii, | |
| limit=2 # LIMITAR VISTA PREVIA | |
| ) | |
| st.code(json_output, language='json') | |
| # Guardar versión completa para descarga | |
| st.session_state.json_output = generate_json_output( | |
| df, | |
| json_format, | |
| minify, | |
| force_ascii | |
| ) | |
| st.session_state.json_filename = f"converted_data_{pd.Timestamp.now().strftime('%Y%m%d_%H%M%S')}.json" | |
| except Exception as e: | |
| st.error(f"Error generando JSON: {str(e)}") | |
| # BOTONES DE DESCARGA PARA JSON - MÉTODO SIMPLE Y CORRECTO | |
| if "JSON" in conversion_type and st.session_state.get('json_output'): | |
| def register_json_metric(): | |
| """Función para registrar métrica de JSON""" | |
| try: | |
| file_size = len(st.session_state.json_output.encode('utf-8')) | |
| metrics_dashboard.record_download( | |
| module_type="conversor", | |
| file_type="json", | |
| file_size=file_size | |
| ) | |
| st.toast("✅ Descarga registrada en estadísticas", icon="📊") | |
| except Exception as e: | |
| st.error(f"Error registrando métrica: {e}") | |
| # UN SOLO BOTÓN que hace ambas cosas | |
| st.download_button( | |
| label="💾 Descargar JSON Completo", | |
| data=st.session_state.json_output, | |
| file_name=st.session_state.json_filename, | |
| mime="application/json", | |
| use_container_width=True, | |
| on_click=register_json_metric, # ✅ Esto registra la métrica | |
| key="download_json_simple" | |
| ) | |
| # CONVERSIÓN PARA FORMATOS NO-JSON | |
| elif "JSON" not in conversion_type: | |
| if st.button("🔄 Convertir", type="primary", use_container_width=True): | |
| with st.spinner("Convirtiendo datos..."): | |
| try: | |
| output = convert_to_format(df, conversion_type) | |
| if output: | |
| st.success("✅ Conversión completada!") | |
| except Exception as e: | |
| st.error(f"❌ Error en conversión: {str(e)}") | |
| # VISTA PREVIA DE SALIDA PARA FORMATOS BINARIOS (Excel) | |
| if st.session_state.get('conversion_output') is not None: | |
| if st.session_state.conversion_type in ["Excel a CSV", "JSON a CSV", "SQL a CSV"]: | |
| st.markdown("**👁️ Vista Previa de Salida (limitada):**") | |
| # Mostrar como texto plano (limitado) | |
| if isinstance(st.session_state.conversion_output, bytes): | |
| output_text = st.session_state.conversion_output.decode('utf-8') | |
| else: | |
| output_text = st.session_state.conversion_output | |
| # Mostrar solo primeras líneas para vista previa | |
| lines = output_text.split('\n') | |
| preview_lines = lines[:10] # Mostrar primeras 10 líneas | |
| preview_text = '\n'.join(preview_lines) | |
| st.code(preview_text, language='text') | |
| st.info(f"Mostrando 10 de {len(lines)} líneas. Descarga para ver completo.") | |
| # BOTÓN DE DESCARGA - MÉTODO SIMPLE Y CORRECTO | |
| def register_conversion_metric(): | |
| """Función para registrar métrica de conversión""" | |
| try: | |
| file_type = st.session_state.conversion_filename.split('.')[-1].lower() | |
| if isinstance(st.session_state.conversion_output, bytes): | |
| file_size = len(st.session_state.conversion_output) | |
| else: | |
| file_size = len(st.session_state.conversion_output.encode('utf-8')) | |
| metrics_dashboard.record_download( | |
| module_type="conversor", | |
| file_type=file_type, | |
| file_size=file_size | |
| ) | |
| st.toast("✅ Descarga registrada en estadísticas", icon="📊") | |
| except Exception as e: | |
| st.error(f"Error registrando métrica: {e}") | |
| # UN SOLO BOTÓN que hace ambas cosas | |
| st.download_button( | |
| label="💾 Descargar Archivo Convertido", | |
| data=st.session_state.conversion_output, | |
| file_name=st.session_state.conversion_filename, | |
| mime=st.session_state.conversion_mime, | |
| use_container_width=True, | |
| on_click=register_conversion_metric, # ✅ Esto registra la métrica | |
| key="download_converted_simple" | |
| ) | |
| else: | |
| st.info("📤 Carga un archivo en la barra lateral para comenzar") | |
| # SECCIÓN ADICIONAL: INFORMACIÓN COMPLETA DEL DATASET | |
| if st.session_state.get('df') is not None and st.session_state.global_filename is not None: | |
| st.markdown("---") | |
| show_dataframe_info(st.session_state.df, st.session_state.global_filename) | |
| if __name__ == "__main__": | |
| show() | |