Skip to content

Commit 400ea07

Browse files
committed
Revert "refactor: move code to plaintext file and add checks"
This reverts commit 593f9ae.
1 parent 593f9ae commit 400ea07

File tree

3 files changed

+73
-127
lines changed

3 files changed

+73
-127
lines changed

bigframes/dataframe.py

Lines changed: 3 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -796,7 +796,9 @@ def __repr__(self) -> str:
796796
)
797797

798798
self._set_internal_query_job(query_job)
799-
return self._create_text_representation(pandas_df, row_count)
799+
from bigframes.display import html
800+
801+
return html.create_text_representation(self, pandas_df, row_count)
800802

801803
def _get_display_df_and_blob_cols(self) -> tuple[DataFrame, list[str]]:
802804
"""Process blob columns for display."""
@@ -824,40 +826,6 @@ def _repr_mimebundle_(self, include=None, exclude=None):
824826

825827
return html.repr_mimebundle(self, include=include, exclude=exclude)
826828

827-
def _create_text_representation(
828-
self,
829-
pandas_df: pandas.DataFrame,
830-
total_rows: typing.Optional[int],
831-
) -> str:
832-
"""Create a text representation of the DataFrame."""
833-
opts = bigframes.options.display
834-
with display_options.pandas_repr(opts):
835-
import pandas.io.formats
836-
837-
to_string_kwargs = (
838-
pandas.io.formats.format.get_dataframe_repr_params() # type: ignore
839-
)
840-
if not self._has_index:
841-
to_string_kwargs.update({"index": False})
842-
to_string_kwargs.update({"show_dimensions": False})
843-
repr_string = pandas_df.to_string(**to_string_kwargs)
844-
845-
lines = repr_string.split("\n")
846-
is_truncated = total_rows is not None and total_rows > len(pandas_df)
847-
848-
if is_truncated:
849-
lines.append("...")
850-
lines.append("") # Add empty line for spacing only if truncated
851-
column_count = len(self.columns)
852-
lines.append(f"[{total_rows or '?'} rows x {column_count} columns]")
853-
else:
854-
# For non-truncated DataFrames, we still need to add dimensions if show_dimensions was False
855-
column_count = len(self.columns)
856-
lines.append("")
857-
lines.append(f"[{total_rows or '?'} rows x {column_count} columns]")
858-
859-
return "\n".join(lines)
860-
861829
def _create_html_representation(
862830
self,
863831
pandas_df: pandas.DataFrame,

bigframes/display/html.py

Lines changed: 66 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,16 @@
1818

1919
import html
2020
import traceback
21+
import typing
2122
from typing import Any, Union
2223
import warnings
2324

2425
import pandas as pd
2526
import pandas.api.types
2627

2728
import bigframes
28-
from bigframes._config import options
29+
from bigframes._config import display_options, options
2930
import bigframes.dataframe
30-
from bigframes.display import plaintext
31-
import bigframes.formatting_helpers
3231
import bigframes.series
3332

3433

@@ -100,6 +99,53 @@ def render_html(
10099
return "\n".join(table_html)
101100

102101

102+
def create_text_representation(
103+
obj: Union[bigframes.dataframe.DataFrame, bigframes.series.Series],
104+
pandas_df: pd.DataFrame,
105+
total_rows: typing.Optional[int],
106+
) -> str:
107+
"""Create a text representation of the DataFrame or Series."""
108+
opts = bigframes.options.display
109+
with display_options.pandas_repr(opts):
110+
if isinstance(obj, bigframes.series.Series):
111+
pd_series = pandas_df.iloc[:, 0]
112+
if len(obj._block.index_columns) == 0:
113+
repr_string = pd_series.to_string(
114+
length=False, index=False, name=True, dtype=True
115+
)
116+
else:
117+
repr_string = pd_series.to_string(length=False, name=True, dtype=True)
118+
else:
119+
import pandas.io.formats
120+
121+
to_string_kwargs = (
122+
pandas.io.formats.format.get_dataframe_repr_params() # type: ignore
123+
)
124+
if not obj._has_index:
125+
to_string_kwargs.update({"index": False})
126+
to_string_kwargs.update({"show_dimensions": False})
127+
repr_string = pandas_df.to_string(**to_string_kwargs)
128+
129+
lines = repr_string.split("\n")
130+
is_truncated = total_rows is not None and total_rows > len(pandas_df)
131+
132+
if is_truncated:
133+
lines.append("...")
134+
lines.append("") # Add empty line for spacing only if truncated
135+
if isinstance(obj, bigframes.series.Series):
136+
lines.append(f"[{total_rows} rows]")
137+
else:
138+
column_count = len(obj.columns)
139+
lines.append(f"[{total_rows or '?'} rows x {column_count} columns]")
140+
elif isinstance(obj, bigframes.dataframe.DataFrame):
141+
# For non-truncated DataFrames, we still need to add dimensions if show_dimensions was False
142+
column_count = len(obj.columns)
143+
lines.append("")
144+
lines.append(f"[{total_rows or '?'} rows x {column_count} columns]")
145+
146+
return "\n".join(lines)
147+
148+
103149
def create_html_representation(
104150
obj: Union[bigframes.dataframe.DataFrame, bigframes.series.Series],
105151
pandas_df: pd.DataFrame,
@@ -108,9 +154,17 @@ def create_html_representation(
108154
blob_cols: list[str],
109155
) -> str:
110156
"""Create an HTML representation of the DataFrame or Series."""
111-
return obj._create_html_representation(
112-
pandas_df, total_rows, total_columns, blob_cols
113-
)
157+
if isinstance(obj, bigframes.series.Series):
158+
pd_series = pandas_df.iloc[:, 0]
159+
try:
160+
html_string = pd_series._repr_html_()
161+
except AttributeError:
162+
html_string = f"<pre>{pd_series.to_string()}</pre>"
163+
else:
164+
html_string = obj._create_html_representation(
165+
pandas_df, total_rows, total_columns, blob_cols
166+
)
167+
return html_string
114168

115169

116170
def get_anywidget_bundle(
@@ -152,19 +206,19 @@ def get_anywidget_bundle(
152206
total_columns,
153207
blob_cols if "blob_cols" in locals() else [],
154208
)
155-
widget_repr["text/plain"] = plaintext.create_text_representation(
156-
obj, cached_pd, total_rows
157-
)
209+
widget_repr["text/plain"] = create_text_representation(obj, cached_pd, total_rows)
158210

159211
return widget_repr, widget_metadata
160212

161213

162-
def repr_mimebundle_head(
214+
def repr_mimebundle(
163215
obj: Union[bigframes.dataframe.DataFrame, bigframes.series.Series],
164216
include=None,
165217
exclude=None,
166218
):
167-
"""Mimebundle display for the start of the data."""
219+
"""
220+
Custom display method for IPython/Jupyter environments.
221+
"""
168222
opts = bigframes.options.display
169223
if opts.repr_mode == "anywidget":
170224
try:
@@ -195,37 +249,6 @@ def repr_mimebundle_head(
195249
obj, pandas_df, row_count, column_count, blob_cols
196250
)
197251

198-
text_representation = plaintext.create_text_representation(
199-
obj, pandas_df, row_count
200-
)
252+
text_representation = create_text_representation(obj, pandas_df, row_count)
201253

202254
return {"text/html": html_string, "text/plain": text_representation}
203-
204-
205-
def repr_mimebundle_deferred(
206-
obj: Union[bigframes.dataframe.DataFrame, bigframes.series.Series],
207-
include=None,
208-
exclude=None,
209-
):
210-
"""Mimebundle display for deferred execution mode."""
211-
# We don't need the mimetype for the deferred case, but we need to match
212-
# the signature of the other repr_mimebundle_* methods.
213-
# TODO(swast): Add an HTML representation for deferred queries that simply
214-
# prints the SQL.
215-
query_job = obj._compute_dry_run()
216-
text_representation = bigframes.formatting_helpers.repr_query_job(query_job)
217-
return {"text/plain": text_representation}
218-
219-
220-
def repr_mimebundle(
221-
obj: Union[bigframes.dataframe.DataFrame, bigframes.series.Series],
222-
include=None,
223-
exclude=None,
224-
):
225-
"""
226-
Custom display method for IPython/Jupyter environments.
227-
"""
228-
if options.display.repr_mode == "deferred":
229-
return repr_mimebundle_deferred(obj, include=include, exclude=exclude)
230-
else:
231-
return repr_mimebundle_head(obj, include=include, exclude=exclude)

bigframes/series.py

Lines changed: 4 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -577,54 +577,6 @@ def _repr_mimebundle_(self, include=None, exclude=None):
577577

578578
return html.repr_mimebundle(self, include=include, exclude=exclude)
579579

580-
def _create_text_representation(
581-
self,
582-
pandas_df: pandas.DataFrame,
583-
total_rows: typing.Optional[int],
584-
) -> str:
585-
"""Create a text representation of the Series."""
586-
opts = bigframes.options.display
587-
with bigframes._config.display_options.pandas_repr(opts):
588-
pd_series = pandas_df.iloc[:, 0]
589-
if len(self._block.index_columns) == 0:
590-
repr_string = pd_series.to_string(
591-
length=False, index=False, name=True, dtype=True
592-
)
593-
else:
594-
repr_string = pd_series.to_string(length=False, name=True, dtype=True)
595-
596-
lines = repr_string.split("\n")
597-
is_truncated = total_rows is not None and total_rows > len(pandas_df)
598-
599-
if is_truncated:
600-
lines.append("...")
601-
lines.append("") # Add empty line for spacing only if truncated
602-
lines.append(f"[{total_rows} rows]")
603-
604-
return "\n".join(lines)
605-
606-
def _create_html_representation(
607-
self,
608-
pandas_df: pandas.DataFrame,
609-
total_rows: int,
610-
total_columns: int,
611-
blob_cols: typing.List[str],
612-
) -> str:
613-
"""Create an HTML representation of the Series."""
614-
pd_series = pandas_df.iloc[:, 0]
615-
try:
616-
# Not all pandas Series have a _repr_html_ method, so we fall back
617-
# to a simple text representation in an HTML <pre> tag.
618-
html_string = pd_series._repr_html_()
619-
except AttributeError:
620-
html_string = f"<pre>{pd_series.to_string()}</pre>"
621-
622-
is_truncated = total_rows is not None and total_rows > len(pandas_df)
623-
if is_truncated:
624-
html_string += f"<p>... [{total_rows} rows in total]</p>"
625-
626-
return html_string
627-
628580
def __repr__(self) -> str:
629581
# Protect against errors with uninitialized Series. See:
630582
# https://github.com/googleapis/python-bigquery-dataframes/issues/728
@@ -635,11 +587,14 @@ def __repr__(self) -> str:
635587
if opts.repr_mode == "deferred":
636588
return formatter.repr_query_job(self._compute_dry_run())
637589

590+
self._cached()
638591
pandas_df, row_count, query_job = self._block.retrieve_repr_request_results(
639592
opts.max_rows
640593
)
641594
self._set_internal_query_job(query_job)
642-
return self._create_text_representation(pandas_df, row_count)
595+
from bigframes.display import html
596+
597+
return html.create_text_representation(self, pandas_df, row_count)
643598

644599
def astype(
645600
self,

0 commit comments

Comments
 (0)