"""API routes for the Visual Notebook.""" from __future__ import annotations import uuid from pathlib import Path from typing import Any import polars as pl from fastapi import APIRouter, Depends, HTTPException, Request, UploadFile, File from fastapi.responses import FileResponse, JSONResponse from visual_notebook.config import settings from visual_notebook.data.csv_loader import register_csv, read_csv_sample, export_to_csv from visual_notebook.data.schema import infer_schema_duckdb from visual_notebook.domain.dataframe import DataFrameRef from visual_notebook.domain.history import History from visual_notebook.domain.operations import OPERATIONS from visual_notebook.domain.checkpoints import save_checkpoint, list_checkpoints from visual_notebook.api.deps import get_session, get_current_ref, get_history, get_duckdb_con from visual_notebook.api.schemas import ( ApplyOpRequest, ApplyOpResponse, ChartRequest, ChartResponse, CheckpointResponse, ColumnInfo, ExportResponse, HistoryResponse, OperationsListResponse, OperationInfo, SchemaResponse, UploadResponse, UndoRedoResponse, ) from visual_notebook.session import Session from visual_notebook.viz.histogram import compute_histogram from visual_notebook.viz.scatter import compute_scatter from visual_notebook.viz.bar_topn import compute_bar_topn from visual_notebook.viz.timeline import compute_timeline from visual_notebook.viz.heatmap import compute_heatmap from visual_notebook.viz.map import compute_map from visual_notebook.viz.pie import compute_pie from visual_notebook.viz.line import compute_line from visual_notebook.viz.boxplot import compute_boxplot from visual_notebook.viz.area import compute_area from visual_notebook.viz.violin import compute_violin from visual_notebook.viz.treemap import compute_treemap from visual_notebook.viz.radar import compute_radar from visual_notebook.viz.stacked_bar import compute_stacked_bar router = APIRouter() @router.post("/upload/csv", response_model=UploadResponse) async def upload_csv( file: UploadFile = File(...), session: Session = Depends(get_session), con=Depends(get_duckdb_con), ): """Upload a CSV file and register it in DuckDB.""" if not file.filename.endswith(".csv"): raise HTTPException(status_code=400, detail="Only CSV files are supported") dataset_id = uuid.uuid4().hex[:8] safe_name = file.filename.replace(" ", "_").replace("/", "_") save_path = Path(settings.data_dir) / f"{dataset_id}_{safe_name}" save_path.parent.mkdir(parents=True, exist_ok=True) content = await file.read() if len(content) > settings.max_upload_size: raise HTTPException(status_code=413, detail="File too large") with open(save_path, "wb") as f: f.write(content) table_name = f"ds_{dataset_id}" meta = register_csv(con, table_name, str(save_path)) ref = DataFrameRef( backend="duckdb", name=table_name, con=con, source_path=str(save_path), ) session.current_table = table_name session.current_ref = ref session.history = History() session.history.commit(ref, operation="upload", params={"filename": file.filename}) schema = infer_schema_duckdb(con, table_name) response = UploadResponse( dataset_id=dataset_id, table_name=table_name, row_count=meta["row_count"], columns=[ColumnInfo(**c) for c in schema], session_id=session.id, ) resp = JSONResponse(content=response.model_dump()) resp.set_cookie("session_id", session.id, httponly=True, max_age=86400 * 7, samesite="none", secure=True) return resp @router.get("/schema", response_model=SchemaResponse) async def get_schema( session: Session = Depends(get_session), ): """Get schema for the current dataset.""" if not session.current_ref or not session.current_ref.name: raise HTTPException(status_code=400, detail="No dataset loaded") ref = session.current_ref schema = infer_schema_duckdb(ref.con, ref.name) row_count = ref.row_count() return SchemaResponse( table_name=ref.name, row_count=row_count, columns=[ColumnInfo(**c) for c in schema], ) @router.get("/rows") async def get_rows( offset: int = 0, limit: int = 50, session: Session = Depends(get_session), ): """Get paginated rows from the current dataset.""" if not session.current_ref: raise HTTPException(status_code=400, detail="No dataset loaded") ref = session.current_ref df = ref.head(limit, offset) return { "rows": df.to_dicts(), "columns": df.columns, "offset": offset, "limit": limit, "total": ref.row_count(), } @router.get("/ops", response_model=OperationsListResponse) async def list_operations(): """List all available operations.""" ops = [] for key, op in OPERATIONS.items(): ops.append(OperationInfo( key=op.key, label=op.label, description=op.description, param_schema=op.param_schema, )) return OperationsListResponse(operations=ops) @router.post("/ops/{op_key}", response_model=ApplyOpResponse) async def apply_operation( op_key: str, req: ApplyOpRequest, session: Session = Depends(get_session), ): """Apply an operation to the current dataset.""" if op_key not in OPERATIONS: raise HTTPException(status_code=404, detail=f"Operation '{op_key}' not found") if not session.current_ref: raise HTTPException(status_code=400, detail="No dataset loaded") op = OPERATIONS[op_key] ref = session.current_ref schema = infer_schema_duckdb(ref.con, ref.name) if ref.backend == "duckdb" else [] try: validated_params = op.validate(req.params, schema) except ValueError as e: raise HTTPException(status_code=422, detail=str(e)) try: new_ref = op.apply(ref, validated_params) except Exception as e: raise HTTPException(status_code=500, detail=f"Operation failed: {str(e)}") # If Polars backend, materialize back to DuckDB for consistent querying if new_ref.backend == "polars" and session.current_ref.backend == "duckdb": new_table_name = f"_op_{uuid.uuid4().hex[:6]}" new_ref = new_ref.materialize_to_duckdb(new_table_name, ref.con) session.current_ref = new_ref session.current_table = new_ref.name state = session.history.commit(new_ref, operation=op_key, params=validated_params) new_schema = infer_schema_duckdb(new_ref.con, new_ref.name) if new_ref.backend == "duckdb" else [] sample = new_ref.head(10) return ApplyOpResponse( state_id=state.state_id, columns_schema=[ColumnInfo(**c) for c in new_schema], row_count=new_ref.row_count(), sample_rows=sample.to_dicts(), ) @router.post("/history/undo", response_model=UndoRedoResponse) async def undo(session: Session = Depends(get_session)): if not session.history.can_undo(): raise HTTPException(status_code=400, detail="Cannot undo") state = session.history.undo() if state: session.current_ref = state.ref session.current_table = state.ref.name if state.ref else None schema = infer_schema_duckdb(state.ref.con, state.ref.name) if state.ref and state.ref.backend == "duckdb" else [] return UndoRedoResponse( state_id=state.state_id, operation=state.operation, columns_schema=[ColumnInfo(**c) for c in schema], row_count=state.ref.row_count() if state.ref else 0, ) raise HTTPException(status_code=400, detail="Undo failed") @router.post("/history/redo", response_model=UndoRedoResponse) async def redo(session: Session = Depends(get_session)): if not session.history.can_redo(): raise HTTPException(status_code=400, detail="Cannot redo") state = session.history.redo() if state: session.current_ref = state.ref session.current_table = state.ref.name if state.ref else None schema = infer_schema_duckdb(state.ref.con, state.ref.name) if state.ref and state.ref.backend == "duckdb" else [] return UndoRedoResponse( state_id=state.state_id, operation=state.operation, columns_schema=[ColumnInfo(**c) for c in schema], row_count=state.ref.row_count() if state.ref else 0, ) raise HTTPException(status_code=400, detail="Redo failed") @router.post("/history/branch") async def branch( state_id: str, session: Session = Depends(get_session), ): state = session.history.branch(state_id) if state: session.current_ref = state.ref session.current_table = state.ref.name if state.ref else None return {"state_id": state.state_id, "operation": state.operation} raise HTTPException(status_code=404, detail="State not found") @router.get("/history", response_model=HistoryResponse) async def get_history(session: Session = Depends(get_session)): tree = session.history.to_tree() return HistoryResponse(**tree) @router.post("/viz/chart", response_model=ChartResponse) async def create_chart( req: ChartRequest, session: Session = Depends(get_session), ): if not session.current_ref: raise HTTPException(status_code=400, detail="No dataset loaded") ref = session.current_ref if ref.backend != "duckdb" or not ref.name or not ref.con: raise HTTPException(status_code=400, detail="Chart requires DuckDB backend") con = ref.con table = ref.name params = req.params try: if req.chart_type == "histogram": spec = compute_histogram(con, table, params["column"], params.get("bins", 20)) elif req.chart_type == "scatter": spec = compute_scatter(con, table, params["x_col"], params["y_col"], params.get("color_col")) elif req.chart_type == "bar_topn": spec = compute_bar_topn(con, table, params["category_col"], params.get("value_col"), params.get("n", 15), params.get("sort_desc", True)) elif req.chart_type == "timeline": spec = compute_timeline(con, table, params["date_col"], params["value_col"], params.get("agg", "sum")) elif req.chart_type == "heatmap": spec = compute_heatmap(con, table, params["x_col"], params["y_col"], params["value_col"], params.get("agg", "mean")) elif req.chart_type == "map": spec = compute_map(con, table, params["lat_col"], params["lon_col"], params.get("label_col")) elif req.chart_type == "pie": spec = compute_pie(con, table, params["category_col"], params.get("value_col"), params.get("n", 10)) elif req.chart_type == "line": spec = compute_line(con, table, params["x_col"], params["y_col"], params.get("agg", "sum")) elif req.chart_type == "boxplot": spec = compute_boxplot(con, table, params["column"], params.get("group_col")) elif req.chart_type == "area": spec = compute_area(con, table, params["x_col"], params["y_col"], params.get("agg", "sum")) elif req.chart_type == "violin": spec = compute_violin(con, table, params["column"], params.get("group_col")) elif req.chart_type == "treemap": spec = compute_treemap(con, table, params["category_col"], params.get("value_col"), params.get("agg", "sum")) elif req.chart_type == "radar": spec = compute_radar(con, table, params["columns"], params.get("group_col"), params.get("agg", "mean")) elif req.chart_type == "stacked_bar": spec = compute_stacked_bar( con, table, params["category_col"], params["value_col"], params.get("group_col"), params.get("agg", "sum"), params.get("n", 20), ) else: raise HTTPException(status_code=400, detail=f"Unknown chart type: {req.chart_type}") except KeyError as e: raise HTTPException(status_code=422, detail=f"Missing parameter: {e}") except Exception as e: raise HTTPException(status_code=500, detail=f"Chart computation failed: {str(e)}") return ChartResponse(chart_type=req.chart_type, spec=spec) @router.get("/export/csv") async def export_csv( session: Session = Depends(get_session), ): if not session.current_ref: raise HTTPException(status_code=400, detail="No dataset loaded") ref = session.current_ref output_path = Path(settings.data_dir) / f"export_{uuid.uuid4().hex[:8]}.csv" if ref.backend == "duckdb" and ref.name and ref.con: export_to_csv(ref.con, ref.name, str(output_path)) else: df = ref.to_polars_df() df.write_csv(str(output_path)) return FileResponse( path=str(output_path), filename=f"{ref.name or 'data'}.csv", media_type="text/csv", ) @router.post("/checkpoint", response_model=CheckpointResponse) async def create_checkpoint(session: Session = Depends(get_session)): tree = session.history.to_tree() path = save_checkpoint(session.id, tree, session.duckdb_con, session.current_ref) current_state = session.history.current return CheckpointResponse( path=path, timestamp=tree.get("nodes", [{}])[0].get("metadata", {}).get("timestamp", "now"), state_id=current_state.state_id if current_state else None, ) @router.get("/checkpoints") async def get_checkpoints(session: Session = Depends(get_session)): return list_checkpoints(session.id) @router.post("/export/notebook") async def export_notebook(session: Session = Depends(get_session)): """Generate a Jupyter Notebook (.ipynb) with Python code cells. Produces clean, idiomatic pandas code with descriptive comments. Only imports matplotlib if chart operations are present in the history. """ if not session.current_ref: raise HTTPException(status_code=400, detail="No dataset loaded") # Build notebook from history history = session.history nodes = history.to_tree().get("nodes", []) # Determine which operations are in the history ops_in_history = [n.get("operation") for n in nodes if n.get("operation")] has_charts = any(op == "chart" for op in ops_in_history) # Figure out the source CSV filename from the upload node source_filename = "data.csv" for node in nodes: if node.get("operation") == "upload": source_filename = node.get("params", {}).get("filename", "data.csv") break cells = [] # --- Markdown title cell --- cells.append({ "cell_type": "markdown", "metadata": {}, "source": [ "# Visual Notebook Export\n", "\n", "Auto-generated from a Visual Notebook analysis session.\n", "Each cell below corresponds to one operation applied to the data.", ] }) # --- Import cell --- import_lines = [ "import pandas as pd\n", "import duckdb\n", ] if has_charts: import_lines.append("import matplotlib.pyplot as plt\n") cells.append({ "cell_type": "code", "metadata": {}, "source": import_lines, "execution_count": None, "outputs": [] }) # --- Data load cell --- cells.append({ "cell_type": "code", "metadata": {}, "source": [ f"# Load the source CSV into a DuckDB in-memory database\n", f"con = duckdb.connect()\n", f"con.execute('CREATE TABLE raw_data AS SELECT * FROM read_csv_auto(\"{source_filename}\")')\n", f"\n", f"# Preview the first 10 rows\n", f"df = con.execute('SELECT * FROM raw_data LIMIT 10').df()\n", f"df", ], "execution_count": None, "outputs": [] }) # --- Operation cells from history --- for node in nodes: op = node.get("operation") params = node.get("params", {}) if op and op not in ("upload",): code = _op_to_code(op, params) cells.append({ "cell_type": "code", "metadata": {}, "source": [code], "execution_count": None, "outputs": [] }) # --- Final preview cell --- cells.append({ "cell_type": "code", "metadata": {}, "source": [ "# Final data preview\n", "df = con.execute('SELECT * FROM raw_data LIMIT 50').df()\n", "df", ], "execution_count": None, "outputs": [] }) notebook = { "nbformat": 4, "nbformat_minor": 5, "metadata": { "kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"}, "language_info": {"name": "python", "version": "3.11.0"} }, "cells": cells } return JSONResponse( content=notebook, media_type="application/json", headers={"Content-Disposition": "attachment; filename=notebook.ipynb"} ) def _op_to_code(op: str, params: dict) -> str: """Convert operation + params to idiomatic Python/pandas code string.""" if op == "filter": column = params.get("column", "") operator = params.get("operator", "==") value = params.get("value") op_map = { "eq": "=", "neq": "!=", "gt": ">", "lt": "<", "gte": ">=", "lte": "<=", } if operator in op_map: sql_op = op_map[operator] return ( f"# Filter: keep rows where {column} {sql_op} {value!r}\n" f"con.execute('DELETE FROM raw_data WHERE \"{column}\" != {{}}').fetchall() # placeholder\n" f"df = con.execute('SELECT * FROM raw_data WHERE \"{column}\" {sql_op} {{}}').df()\n" f"con.execute('CREATE OR REPLACE TABLE raw_data AS SELECT * FROM raw_data WHERE \"{column}\" {sql_op} {{}}')\n" f"print(f\"Rows after filter: {{len(df)}}\")" ) elif operator == "contains": return ( f"# Filter: keep rows where {column} contains {value!r}\n" f"df = con.execute('SELECT * FROM raw_data WHERE CAST(\"{column}\" AS VARCHAR) LIKE \\'%{value}%\\' ').df()\n" f"con.execute('CREATE OR REPLACE TABLE raw_data AS SELECT * FROM raw_data WHERE CAST(\"{column}\" AS VARCHAR) LIKE \\'%{value}%\\' ')\n" f"print(f\"Rows after filter: {{len(df)}}\")" ) elif operator == "is_null": return ( f"# Filter: keep rows where {column} is NULL\n" f"df = con.execute('SELECT * FROM raw_data WHERE \"{column}\" IS NULL').df()\n" f"con.execute('CREATE OR REPLACE TABLE raw_data AS SELECT * FROM raw_data WHERE \"{column}\" IS NULL')\n" f"print(f\"Rows after filter: {{len(df)}}\")" ) elif operator == "is_not_null": return ( f"# Filter: keep rows where {column} is NOT NULL\n" f"df = con.execute('SELECT * FROM raw_data WHERE \"{column}\" IS NOT NULL').df()\n" f"con.execute('CREATE OR REPLACE TABLE raw_data AS SELECT * FROM raw_data WHERE \"{column}\" IS NOT NULL')\n" f"print(f\"Rows after filter: {{len(df)}}\")" ) return f"# Filter\n# params: {params}" elif op == "sort": column = params.get("column", "") ascending = not params.get("descending", False) order = "ASC" if ascending else "DESC" return ( f"# Sort by {column} ({'ascending' if ascending else 'descending'})\n" f"con.execute('CREATE OR REPLACE TABLE raw_data AS SELECT * FROM raw_data ORDER BY \"{column}\" {order}')\n" f"con.execute('SELECT * FROM raw_data LIMIT 5').df()" ) elif op == "select": columns = params.get("columns", []) cols_sql = ", ".join(f'"{c}"' for c in columns) return ( f"# Select columns: {columns}\n" f"con.execute('CREATE OR REPLACE TABLE raw_data AS SELECT {cols_sql} FROM raw_data')\n" f"con.execute('SELECT * FROM raw_data LIMIT 5').df()" ) elif op == "rename": mapping = params.get("mapping", {}) # Build SQL aliases alias_parts = [f'"{old}" AS "{new}"' for old, new in mapping.items()] aliases_sql = ", ".join(alias_parts) return ( f"# Rename columns: {mapping}\n" f"con.execute('CREATE OR REPLACE TABLE raw_data AS SELECT *, {aliases_sql} FROM raw_data')\n" f"# Note: SELECT * keeps old columns too; a proper rename uses all column names\n" f"con.execute('SELECT * FROM raw_data LIMIT 5').df()" ) elif op == "groupby": group_by = params.get("group_by", []) aggregations = params.get("aggregations", {}) agg_parts = [] for col, funcs in aggregations.items(): if isinstance(funcs, str): funcs = [funcs] for func in funcs: agg_parts.append(f'{func}("{col}") AS "{col}_{func}"') group_cols = ", ".join(f'"{c}"' for c in group_by) agg_sql = ", ".join(agg_parts) return ( f"# Group by {group_by} with aggregations\n" f"con.execute('CREATE OR REPLACE TABLE raw_data AS SELECT {group_cols}, {agg_sql} FROM raw_data GROUP BY {group_cols}')\n" f"con.execute('SELECT * FROM raw_data LIMIT 10').df()" ) elif op == "fill_nulls": strategy = params.get("strategy", "forward") strategy_map = { "forward": "Use LAG window function", "backward": "Use LEAD window function", "zero": "COALESCE(col, 0)", "mean": "COALESCE(col, avg)", "constant": "COALESCE(col, value)", } hint = strategy_map.get(strategy, strategy) return ( f"# Fill null values (strategy: {strategy} — {hint})\n" f"df = con.execute('SELECT * FROM raw_data').df()\n" f"df = df.fillna(method='{strategy if strategy in ('ffill', 'bfill') else None}'" f"{', value=0' if strategy == 'zero' else ''})\n" f"con.execute('CREATE OR REPLACE TABLE raw_data AS SELECT * FROM df')" ) elif op == "clip": column = params.get("column", "") lower = params.get("lower") upper = params.get("upper") return ( f"# Clip values in {column} to [{lower}, {upper}]\n" f"df = con.execute('SELECT * FROM raw_data').df()\n" f'df["{column}"] = df["{column}"].clip({lower}, {upper})\n' f"con.execute('CREATE OR REPLACE TABLE raw_data AS SELECT * FROM df')" ) elif op == "drop_columns": columns = params.get("columns", []) return ( f"# Drop columns: {columns}\n" f"df = con.execute('SELECT * FROM raw_data').df()\n" f"df = df.drop(columns={columns})\n" f"con.execute('CREATE OR REPLACE TABLE raw_data AS SELECT * FROM df')" ) elif op == "cast_type": column = params.get("column", "") new_type = params.get("new_type", "varchar") pandas_type = {"integer": "int", "float": "float", "varchar": "str", "boolean": "bool", "date": "datetime64[ns]", "timestamp": "datetime64[ns]"} pt = pandas_type.get(new_type, new_type) return ( f"# Cast {column} to {new_type}\n" f"df = con.execute('SELECT * FROM raw_data').df()\n" f'df["{column}"] = df["{column}"].astype("{pt}")\n' f"con.execute('CREATE OR REPLACE TABLE raw_data AS SELECT * FROM df')" ) elif op == "replace_values": column = params.get("column", "") old_value = params.get("old_value") new_value = params.get("new_value") return ( f"# Replace {old_value!r} with {new_value!r} in {column}\n" f"df = con.execute('SELECT * FROM raw_data').df()\n" f'df["{column}"] = df["{column}"].replace({old_value!r}, {new_value!r})\n' f"con.execute('CREATE OR REPLACE TABLE raw_data AS SELECT * FROM df')" ) elif op == "sample": n = params.get("n") frac = params.get("fraction") if frac: return ( f"# Random sample (fraction={frac})\n" f"df = con.execute('SELECT * FROM raw_data').df()\n" f"df = df.sample(frac={frac})\n" f"con.execute('CREATE OR REPLACE TABLE raw_data AS SELECT * FROM df')" ) return ( f"# Random sample (n={n or 100})\n" f"df = con.execute('SELECT * FROM raw_data').df()\n" f"df = df.sample(n={n or 100})\n" f"con.execute('CREATE OR REPLACE TABLE raw_data AS SELECT * FROM df')" ) elif op == "distinct": cols = params.get("columns") if cols: return ( f"# Remove duplicate rows (subset={cols})\n" f"df = con.execute('SELECT * FROM raw_data').df()\n" f"df = df.drop_duplicates(subset={cols})\n" f"con.execute('CREATE OR REPLACE TABLE raw_data AS SELECT * FROM df')" ) return ( "# Remove all duplicate rows\n" "df = con.execute('SELECT * FROM raw_data').df()\n" "df = df.drop_duplicates()\n" "con.execute('CREATE OR REPLACE TABLE raw_data AS SELECT * FROM df')" ) elif op == "describe": return ( "# Generate summary statistics\n" "df = con.execute('SELECT * FROM raw_data').df()\n" "df.describe()" ) elif op == "pivot_table": index = params.get("index", []) columns = params.get("columns", []) values = params.get("values") agg_func = params.get("agg_func", "sum") return ( f"# Pivot table: index={index}, columns={columns}, values={values}, agg={agg_func}\n" f"df = con.execute('SELECT * FROM raw_data').df()\n" f"df = pd.pivot_table(df, index={index}, columns={columns}" f"{', values=' + repr(values) if values else ''}" f"{', aggfunc=' + repr(agg_func) if agg_func != 'sum' else ''})\n" f"con.execute('CREATE OR REPLACE TABLE raw_data AS SELECT * FROM df')\n" f"df" ) elif op == "compute_column": new_column = params.get("new_column", "") expression = params.get("expression", "") return ( f"# Compute new column: {new_column} = {expression}\n" f"con.execute('CREATE OR REPLACE TABLE raw_data AS SELECT *, {expression} AS \"{new_column}\" FROM raw_data')\n" f"con.execute('SELECT * FROM raw_data LIMIT 5').df()" ) elif op == "lag_lead": column = params.get("column", "") shift_type = params.get("shift_type", "lag") offset = params.get("offset", 1) new_col = params.get("new_column_name") or f"{column}_{shift_type}_{offset}" window_fn = "LAG" if shift_type == "lag" else "LEAD" return ( f"# Add {shift_type}({offset}) of {column} as {new_col}\n" f"con.execute('CREATE OR REPLACE TABLE raw_data AS SELECT *, {window_fn}(\"{column}\", {int(offset)}) OVER (ORDER BY ROW_NUMBER() OVER ()) AS \"{new_col}\" FROM raw_data')\n" f"con.execute('SELECT * FROM raw_data LIMIT 5').df()" ) elif op == "rolling_agg": column = params.get("column", "") window_size = params.get("window_size", 3) agg_func = params.get("agg_func", "mean") new_col = params.get("new_column_name") or f"{column}_rolling_{agg_func}_{window_size}" agg_sql_map = {"mean": "AVG", "sum": "SUM", "min": "MIN", "max": "MAX"} sql_agg = agg_sql_map.get(agg_func, "AVG") half = int(window_size) // 2 preceding = half following = half if int(window_size) % 2 == 1 else half - 1 return ( f"# Rolling {agg_func} (window={window_size}) of {column} as {new_col}\n" f"con.execute('CREATE OR REPLACE TABLE raw_data AS SELECT *, {sql_agg}(\"{column}\") OVER (ORDER BY ROW_NUMBER() OVER () ROWS BETWEEN {preceding} PRECEDING AND {following} FOLLOWING) AS \"{new_col}\" FROM raw_data')\n" f"con.execute('SELECT * FROM raw_data LIMIT 10').df()" ) elif op == "correlation": column_x = params.get("column_x", "") column_y = params.get("column_y", "") return ( f"# Correlation between {column_x} and {column_y}\n" f"df = con.execute('SELECT * FROM raw_data').df()\n" f'corr = df["{column_x}"].corr(df["{column_y}"])\n' f'print(f"Pearson correlation ({column_x}, {column_y}): {{corr:.4f}}")' ) elif op == "value_counts": column = params.get("column", "") top_n = params.get("top_n", 20) return ( f"# Value counts for {column} (top {top_n})\n" f"df = con.execute('SELECT * FROM raw_data').df()\n" f'df["{column}"].value_counts().head({int(top_n)})' ) elif op == "add_row": values = params.get("values", {}) return ( f"# Add a new row: {values}\n" f"df = con.execute('SELECT * FROM raw_data').df()\n" f"new_row = pd.DataFrame([{values}])\n" f"df = pd.concat([df, new_row], ignore_index=True)\n" f"con.execute('CREATE OR REPLACE TABLE raw_data AS SELECT * FROM df')\n" f"print(f'Total rows: {{len(df)}}')" ) elif op == "remove_nulls": columns = params.get("columns") how = params.get("how", "any") if columns: return ( f"# Remove rows with nulls in {columns} (how={how})\n" f"df = con.execute('SELECT * FROM raw_data').df()\n" f"df = df.dropna(subset={columns}, how='{how}')\n" f"con.execute('CREATE OR REPLACE TABLE raw_data AS SELECT * FROM df')\n" f"print(f'Rows after removing nulls: {{len(df)}}')" ) return ( f"# Remove rows with any null values\n" f"df = con.execute('SELECT * FROM raw_data').df()\n" f"df = df.dropna(how='{how}')\n" f"con.execute('CREATE OR REPLACE TABLE raw_data AS SELECT * FROM df')\n" f"print(f'Rows after removing nulls: {{len(df)}}')" ) elif op == "edit_cell": row_index = params.get("row_index", 0) column = params.get("column", "") new_value = params.get("new_value", "") return ( f"# Edit cell: row {row_index}, column {column} -> {new_value!r}\n" f"df = con.execute('SELECT * FROM raw_data').df()\n" f'df.loc[{row_index}, "{column}"] = {new_value!r}\n' f"con.execute('CREATE OR REPLACE TABLE raw_data AS SELECT * FROM df')" ) elif op == "chart": return ( "# Generate a chart\n" "df = con.execute('SELECT * FROM raw_data').df()\n" "df.plot()" ) # Fallback for unknown operations return f"# Operation: {op}\n# Parameters: {params}" @router.put("/edit/cell") async def edit_cell( row_index: int, column: str, new_value: str, session: Session = Depends(get_session), ): """Update a single cell value in the current dataset.""" if not session.current_ref: raise HTTPException(status_code=400, detail="No dataset loaded") ref = session.current_ref # Get current data as Polars DataFrame df = ref.to_polars_df() # Update the cell try: df = df.with_columns( pl.when(pl.arange(0, df.height) == row_index) .then(pl.lit(new_value)) .otherwise(pl.col(column)) .alias(column) ) except Exception as e: raise HTTPException(status_code=500, detail=f"Edit failed: {str(e)}") # Re-register in DuckDB new_table_name = f"_edit_{uuid.uuid4().hex[:6]}" arrow_tbl = df.to_arrow() ref.con.register("_edit_df", arrow_tbl) ref.con.execute(f'CREATE OR REPLACE TABLE "{new_table_name}" AS SELECT * FROM _edit_df') ref.con.unregister("_edit_df") new_ref = DataFrameRef( backend="duckdb", name=new_table_name, con=ref.con, source_path=ref.source_path, ) session.current_ref = new_ref session.current_table = new_table_name session.history.commit(new_ref, operation="edit_cell", params={"row_index": row_index, "column": column, "new_value": new_value}) return {"success": True, "row_index": row_index, "column": column, "new_value": new_value}