Files
Visualizaciones/Bavisiter_example.py
egutierrez 46573ccc8e Add drawing and visualization applications with Marimo framework
- Implement dibujar.py for drawing functionality with base64 and PIL image rendering.
- Create dibujar_retropaint.py for retro painting features using the Paint widget.
- Develop draw_data.py to visualize data with Scatter and Bar widgets, including lazy installation of dependencies.
- Add layout configuration for graphical representations in layouts/Graficos_plotly.grid.json.
- Enhance shell interaction with mejora_shell_mowidget.py, allowing local library imports and script execution.
- Introduce primera_prueba_shell_mowidget.py for testing shell commands and user input handling.
- Create prueba_de_embeddings.py for embedding visualizations using Sentence Transformers and dimensionality reduction techniques.
- Implement pygwalker_visualizaciones.py for interactive data exploration and visualization using Pygwalker.
- Add a sample bash script for user input and ping functionality in scripts/mi_script.sh.
2025-09-02 23:53:01 +02:00

133 lines
3.8 KiB
Python

import marimo
__generated_with = "0.15.2"
app = marimo.App(width="medium")
@app.cell
def _():
import marimo as mo
import os, sys, importlib, subprocess, shutil
def _have(mod: str) -> bool:
try:
importlib.import_module(mod)
return True
except Exception:
return False
def _install_with_uv(spec: str) -> bool:
uv = shutil.which("uv")
if uv:
subprocess.check_call([uv, "pip", "install", spec])
return True
return False
def _install_with_pip(spec: str) -> bool:
# intenta habilitar pip si no existe
try:
import ensurepip # noqa: F401
ensurepip.bootstrap()
except Exception:
pass
pip_exe = shutil.which("pip") or shutil.which("pip3")
if pip_exe:
subprocess.check_call([pip_exe, "install", spec])
return True
# último recurso: python -m pip
try:
subprocess.check_call([sys.executable, "-m", "pip", "install", spec])
return True
except Exception:
return False
def ensure_pkg(spec: str, module: str | None = None):
module = module or spec
if _have(module):
return
if _install_with_uv(spec):
return
if _install_with_pip(spec):
return
raise RuntimeError(
f"No pude instalar {spec}. Instálalo manualmente con `uv pip install {spec}`."
)
# --- instala dependencias ---
# bavisitter desde PyPI; si falla, cae al repo de GitHub
try:
ensure_pkg("bavisitter", "bavisitter")
except Exception:
ensure_pkg("git+https://github.com/jiwnchoi/Bavisitter.git", "bavisitter")
for spec in [("pandas","pandas"), ("altair","altair"), ("vega_datasets","vega_datasets")]:
ensure_pkg(spec[0], spec[1])
import pandas as pd
import altair as alt
from vega_datasets import data
return data, mo, os
@app.cell
def _(mo):
# Cell 2
api_key_input = mo.ui.text(value="", label="OPENAI_API_KEY (opcional aquí; si ya está en el entorno, deja vacío)", full_width=True)
model_dd = mo.ui.dropdown(
options=["gpt-4o", "gpt-4o-mini", "gpt-4.1", "gpt-4o-reasoning"],
value="gpt-4o",
label="Modelo"
)
theme_dd = mo.ui.radio(options=["light", "dark"], value="light", label="Tema de Bavisitter")
launch_btn = mo.ui.run_button(label="Lanzar Bavisitter")
mo.vstack([api_key_input, mo.hstack([model_dd, theme_dd]), launch_btn])
return api_key_input, launch_btn, model_dd, theme_dd
@app.cell
def _(data, mo):
movies_df = data.movies()
# Se muestra automáticamente como tabla si es la última expresión:
mo.ui.dataframe(movies_df)
return (movies_df,)
@app.cell
def _(api_key_input, launch_btn, mo, model_dd, movies_df, os, theme_dd):
# Cell 4
from bavisitter import Bavisitter
# Si se pulsa el botón, configuramos la API key (si el usuario la introdujo)
if api_key_input.value:
os.environ["OPENAI_API_KEY"] = api_key_input.value
# Validaciones mínimas
has_key = bool(os.environ.get("OPENAI_API_KEY", "").strip())
mo.stop(not launch_btn.value, mo.md("Pulsa **Lanzar Bavisitter** para iniciar."))
mo.stop(not has_key, mo.md("Falta **OPENAI_API_KEY**. Escríbela en la celda de arriba o expórtala en el entorno."))
# Instanciar Bavisitter con el dataset de ejemplo y los parámetros elegidos
app = Bavisitter(
movies_df,
model=model_dd.value,
color_mode=theme_dd.value
)
app # Bavisitter renderiza su interfaz; úsala para pedir gráficos, detectar y resolver problemas de diseño
return
@app.cell
def _(os):
os.environ["OPENAI_API_KEY"]
return
if __name__ == "__main__":
app.run()