Spaces:
Runtime error
Runtime error
Download frontend/web/utils/common.py from DesarrolloTT/DataSuitePro: direct link, hf CLI and curl.
- Browser
- Download file 6.14 kB
-
https://huggingface.co/spaces/DesarrolloTT/DataSuitePro/resolve/main/frontend/web/utils/common.py
- Command line
-
hf download hf://spaces/DesarrolloTT/DataSuitePro/frontend/web/utils/common.py
-
curl -L -o common.py https://huggingface.co/spaces/DesarrolloTT/DataSuitePro/resolve/main/frontend/web/utils/common.py
6.14 kB
| import streamlit as st | |
| import pandas as pd | |
| import json | |
| import io | |
| def get_dataframe(uploaded_file): | |
| """ | |
| Convierte un archivo subido a DataFrame con detección mejorada de tipos | |
| """ | |
| try: | |
| # Resetear posición del archivo para múltiples lecturas | |
| uploaded_file.seek(0) | |
| if uploaded_file.name.endswith('.csv'): | |
| # Para CSV, leer manteniendo strings para columnas problemáticas | |
| df = pd.read_csv(uploaded_file, dtype={ | |
| 'dni': str, | |
| 'cp': str, | |
| 'limite_credito': str, | |
| 'volumen_compra': str, | |
| 'edad': str | |
| }) | |
| # Conversión manual de columnas numéricas | |
| numeric_columns = ['dni', 'cp', 'limite_credito', 'volumen_compra', 'edad', 'primera_compra'] | |
| for col in numeric_columns: | |
| if col in df.columns: | |
| try: | |
| df[col] = pd.to_numeric(df[col], errors='ignore') | |
| except: | |
| pass | |
| elif uploaded_file.name.endswith(('.xlsx', '.xls')): | |
| # Para Excel, leer manteniendo formato original | |
| df = pd.read_excel(uploaded_file) | |
| # Conversión inteligente de tipos | |
| for col in df.columns: | |
| # Si la columna parece ser numérica pero tiene valores grandes | |
| if df[col].dtype == 'object': | |
| try: | |
| # Intentar convertir a numérico | |
| converted = pd.to_numeric(df[col], errors='ignore') | |
| if converted.dtype != 'object': # Si se pudo convertir | |
| df[col] = converted | |
| except: | |
| pass | |
| # Intentar convertir a datetime | |
| try: | |
| df[col] = pd.to_datetime(df[col], errors='ignore') | |
| except: | |
| pass | |
| elif uploaded_file.name.endswith('.json'): | |
| # Intentar diferentes orientaciones JSON | |
| try: | |
| df = pd.read_json(uploaded_file) | |
| except: | |
| uploaded_file.seek(0) | |
| json_data = json.load(uploaded_file) | |
| df = pd.DataFrame(json_data) | |
| else: | |
| st.error(f"Formato {uploaded_file.name.split('.')[-1]} no soportado") | |
| return None | |
| return df | |
| except Exception as e: | |
| st.error(f"Error procesando archivo: {str(e)}") | |
| return None | |
| def validate_dataframe(df): | |
| """Valida que el DataFrame sea usable""" | |
| return df is not None and not df.empty | |
| def get_file_preview(df, max_rows=10): | |
| """Genera vista previa del DataFrame""" | |
| return df.head(max_rows) | |
| def convert_to_json(df, orient='records'): | |
| """Convierte DataFrame a JSON con diferentes formatos""" | |
| return df.to_json(orient=orient, indent=2, force_ascii=False) | |
| def get_dataframe_stats(df): | |
| """Obtiene estadísticas completas del DataFrame""" | |
| stats = { | |
| 'filas': len(df), | |
| 'columnas': len(df.columns), | |
| 'celdas': len(df) * len(df.columns), | |
| 'memoria_mb': df.memory_usage(deep=True).sum() / 1024 / 1024, | |
| 'tipos_datos': df.dtypes.value_counts().to_dict(), | |
| 'nulos_totales': df.isna().sum().sum() | |
| } | |
| return stats | |
| def get_json_preview(df, format_type, minify=False, force_ascii=True): | |
| """ | |
| Genera vista previa de JSON en diferentes formatos | |
| """ | |
| try: | |
| if format_type == "records-web": | |
| # Formato especial records-web (optimizado para web) | |
| return df.to_json(orient="records", force_ascii=False, indent=None if minify else 2) | |
| else: | |
| return df.to_json(orient=format_type, force_ascii=force_ascii, indent=None if minify else 2) | |
| except Exception as e: | |
| return f"Error generando JSON: {str(e)}" | |
| def convert_df_to_sql(df, table_name, sql_format="INSERT"): | |
| """ | |
| Convierte un DataFrame a sentencias SQL INSERT. | |
| """ | |
| if sql_format == "INSERT": | |
| sql_lines = [] | |
| for index, row in df.iterrows(): | |
| columns = ', '.join([f'"{col}"' for col in df.columns]) | |
| # CORRECCIÓN: Separar la lógica para evitar problemas de comillas | |
| values_list = [] | |
| for value in row: | |
| if isinstance(value, str): | |
| # Escapar comillas dobles duplicándolas | |
| escaped_value = str(value).replace('"', '""') | |
| values_list.append(f'"{escaped_value}"') | |
| else: | |
| values_list.append(str(value)) | |
| values = ', '.join(values_list) | |
| sql_lines.append(f'INSERT INTO {table_name} ({columns}) VALUES ({values});') | |
| return '\n'.join(sql_lines) | |
| else: | |
| raise ValueError(f"Formato SQL no soportado: {sql_format}") | |
| def reset_session_state(): | |
| """Reinicia el session_state""" | |
| keys_to_keep = ['theme', 'max_file_size'] # Mantener configuraciones | |
| new_state = {k: st.session_state[k] for k in keys_to_keep if k in st.session_state} | |
| for key in list(st.session_state.keys()): | |
| del st.session_state[key] | |
| # Restaurar configuraciones | |
| for k, v in new_state.items(): | |
| st.session_state[k] = v | |
| def safe_string_convert(value): | |
| """Convierte valores a string de forma segura para SQL""" | |
| if pd.isna(value): | |
| return "NULL" | |
| elif isinstance(value, (int, float)): | |
| return str(value) | |
| else: | |
| # Escapar comillas simples para SQL | |
| escaped_val = str(value).replace("'", "''") | |
| return f"'{escaped_val}'" | |
| def get_safe_global_df(): | |
| """ | |
| Devuelve el DataFrame global desde Streamlit session_state de forma segura. | |
| Si no existe o no es un DataFrame válido, devuelve un DataFrame vacío. | |
| """ | |
| import streamlit as st | |
| import pandas as pd | |
| if "df" in st.session_state and isinstance(st.session_state.df, pd.DataFrame): | |
| return st.session_state.df | |
| else: | |
| return pd.DataFrame() | |