Skip to content

Commit

Permalink
Remove view and replace with table
Browse files Browse the repository at this point in the history
  • Loading branch information
shivam-singhal committed Feb 18, 2025
1 parent b7b5297 commit 67e00b7
Show file tree
Hide file tree
Showing 8 changed files with 34 additions and 38 deletions.
8 changes: 4 additions & 4 deletions examples/earthquakes/hello.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import pandas as pd
import plotly.express as px

from preswald import connect, get_df, plotly, slider, text, view
from preswald import connect, get_df, plotly, slider, table, text


# Title
Expand Down Expand Up @@ -47,8 +47,8 @@
# c_data = query("SELECT * FROM earthquakes LIMIT 50;", "eq_clickhouse")
# d_data = query(query_string, "eq_clickhouse")

# view(c_data)
# view(d_data)
# table(c_data)
# table(d_data)
# ---

# Slider for filtering magnitude
Expand All @@ -62,7 +62,7 @@
filtered_data = data[data["Magnitude"] >= min_magnitude]

# View the filtered data
view(filtered_data)
table(filtered_data)

# Summary statistics
text(f"### Total Earthquakes with Magnitude ≥ {min_magnitude}: {len(filtered_data)}")
Expand Down
4 changes: 2 additions & 2 deletions examples/health/hello.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import duckdb
import plotly.express as px

from preswald import plotly, text, view
from preswald import plotly, table, text


# ----------------------------------------------------------------------------
Expand Down Expand Up @@ -68,4 +68,4 @@
# ----------------------------------------------------------------------------
# 4. Render the final display in Preswald
# ----------------------------------------------------------------------------
view(df)
table(df)
4 changes: 2 additions & 2 deletions examples/network/hello.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import pandas as pd
import plotly.graph_objects as go

from preswald import plotly, text, view
from preswald import plotly, table, text


text("# Network Topology Visualizer")
text("Visualize the topology of a network.")

df = pd.read_csv("data.csv")
view(df)
table(df)

# Create a list of devices
devices = df["Device Name"].unique()
Expand Down
4 changes: 2 additions & 2 deletions examples/voice/hello.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import pandas as pd
import plotly.express as px

from preswald import plotly, slider, text, view
from preswald import plotly, slider, table, text


# 📌 Color Configuration
Expand Down Expand Up @@ -489,4 +489,4 @@
"Below is the final dataset after merging ASR transcriptions, intent classifications, and AI responses."
)

view(merged_logs, limit=20)
table(merged_logs, limit=20)
3 changes: 2 additions & 1 deletion preswald/interfaces/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,12 @@
selectbox,
separator,
slider,
table,
text,
text_input,
workflow_dag,
)
from .data import connect, get_df, query, view
from .data import connect, get_df, query
from .workflow import RetryPolicy, Workflow, WorkflowAnalyzer


Expand Down
14 changes: 11 additions & 3 deletions preswald/interfaces/components.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,12 +327,17 @@ def spinner(label: str, size: float = 1.0):
return component


def table(data: pd.DataFrame, title: Optional[str] = None) -> Dict: # noqa: C901
def table( # noqa: C901
data: pd.DataFrame, title: Optional[str] = None, limit: Optional[int] = None
) -> Dict:
"""Create a table component that renders data using TableViewerWidget.
Args:
data: List of dictionaries or pandas DataFrame to display
data: Pandas DataFrame or list of dictionaries to display
title: Optional title for the table
Returns:
Dict: Component metadata and processed data
"""
id = generate_id("table")
logger.debug(f"Creating table component with id {id}")
Expand All @@ -341,9 +346,10 @@ def table(data: pd.DataFrame, title: Optional[str] = None) -> Dict: # noqa: C90
try:
# Convert pandas DataFrame to list of dictionaries if needed
if hasattr(data, "to_dict"):
# Reset index and drop it to avoid index column in output
if isinstance(data, pd.DataFrame):
data = data.reset_index(drop=True)
if limit is not None:
data = data.head(limit)
data = data.to_dict("records")

# Ensure data is a list
Expand All @@ -358,6 +364,7 @@ def table(data: pd.DataFrame, title: Optional[str] = None) -> Dict: # noqa: C90
for key, value in row.items():
# Convert key to string to ensure it's serializable
key_str = str(key)

# Handle special cases and convert value
if pd.isna(value):
processed_row[key_str] = None
Expand All @@ -380,6 +387,7 @@ def table(data: pd.DataFrame, title: Optional[str] = None) -> Dict: # noqa: C90
# If row is not a dict, convert it to a simple dict
processed_data.append({"value": str(row)})

# Create the component structure
component = {
"type": "table",
"id": id,
Expand Down
13 changes: 0 additions & 13 deletions preswald/interfaces/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@

from preswald.engine.service import PreswaldService

from .components import table


# Configure logging
logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -51,14 +49,3 @@ def get_df(source_name: str, table_name: Optional[str] = None) -> pd.DataFrame:
return df_result
except Exception as e:
logger.error(f"Error getting a dataframe from data source: {e}")


def view(df: pd.DataFrame, limit: int = 100):
"""
Render a preview of the data using the table component.
Args:
data_or_connection_name: Either a pandas DataFrame or a connection name string.
limit (int): Maximum number of rows to display in the table.
"""
return table(df.head(limit))
22 changes: 11 additions & 11 deletions preswald/tutorial/hello.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
selectbox,
separator,
slider,
table,
text,
view,
workflow_dag,
)

Expand Down Expand Up @@ -38,25 +38,25 @@
)

# --- LOADING DATA ---
text("## 2. Viewing Data with `view()`")
text("Let's load a sample dataset and display it using the `view()` component.")
text("## 2. Viewing Data with `table()`")
text("Let's load a sample dataset and display it using the `table()` component.")

# Load the sample CSV
connect()
df = get_df("sample_csv")

# Displaying the data with `view`
view(df, limit=10) # Display first 10 rows
# Displaying the data with `table`
table(df, limit=10) # Display first 10 rows

text(
"""
The `view()` component displays data in a tabular format.
The `table()` component displays data in a tabular format.
**Example:**
```python
from preswald import view
view(df, limit=10)
from preswald import table
table(df, limit=10)
```
- **limit**: Use this parameter to control how many rows to display.
Expand Down Expand Up @@ -116,7 +116,7 @@
)

# Display the selected number of rows
view(df.head(num_rows))
table(df.head(num_rows))

text(
"""
Expand Down Expand Up @@ -185,14 +185,14 @@

# Display some content
text("### Section 1: Original Data")
view(df.head(5))
table(df.head(5))

# Add a separator to visually break content
separator()

# Display more content after the separator
text("### Section 2: Data Summary")
view(df.describe())
table(df.describe())

text(
"""
Expand Down

0 comments on commit 67e00b7

Please sign in to comment.