Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bugfix] Remove svg export #6476

Merged
merged 10 commits into from
Jun 3, 2024
Merged
14 changes: 8 additions & 6 deletions cli/openbb_cli/controllers/base_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -743,13 +743,15 @@ def parse_known_args_and_warn(

if export_allowed == "raw_data_only":
choices_export = ["csv", "json", "xlsx"]
help_export = "Export raw data into csv, json, xlsx"
help_export = "Export raw data into csv, json or xlsx."
elif export_allowed == "figures_only":
choices_export = ["png", "jpg", "svg"]
help_export = "Export figure into png, jpg, svg "
choices_export = ["png", "jpg"]
help_export = "Export figure into png or jpg."
else:
choices_export = ["csv", "json", "xlsx", "png", "jpg", "svg"]
help_export = "Export raw data into csv, json, xlsx and figure into png, jpg, svg "
choices_export = ["csv", "json", "xlsx", "png", "jpg"]
help_export = (
"Export raw data into csv, json, xlsx and figure into png or jpg."
)

parser.add_argument(
"--export",
Expand Down Expand Up @@ -823,7 +825,7 @@ def parse_known_args_and_warn(
"raw_data_and_figures",
]:
ns_parser.is_image = any(
ext in ns_parser.export for ext in ["png", "svg", "jpg"]
ext in ns_parser.export for ext in ["png", "jpg"]
)

except SystemExit:
Expand Down
2 changes: 1 addition & 1 deletion cli/openbb_cli/controllers/base_platform_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ def method(self, other_args: List[str], translator=translator):

obbject = translator.execute_func(parsed_args=ns_parser)
df: pd.DataFrame = pd.DataFrame()
fig: OpenBBFigure = None
fig: Optional[OpenBBFigure] = None
title = f"{self.PATH}{translator.func.__name__}"

if obbject:
Expand Down
10 changes: 5 additions & 5 deletions cli/openbb_cli/controllers/choices.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,14 @@ def __mock_parse_known_args_and_warn(

if export_allowed == "raw_data_only":
choices_export = ["csv", "json", "xlsx"]
help_export = "Export raw data into csv, json, xlsx"
help_export = "Export raw data into csv, json or xlsx."
elif export_allowed == "figures_only":
choices_export = ["png", "jpg", "svg"]
help_export = "Export figure into png, jpg, svg "
choices_export = ["png", "jpg"]
help_export = "Export figure into png or jpg."
else:
choices_export = ["csv", "json", "xlsx", "png", "jpg", "svg"]
choices_export = ["csv", "json", "xlsx", "png", "jpg"]
help_export = (
"Export raw data into csv, json, xlsx and figure into png, jpg, svg "
"Export raw data into csv, json, xlsx and figure into png or jpg."
)

parser.add_argument(
Expand Down
2 changes: 1 addition & 1 deletion cli/openbb_cli/controllers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -901,7 +901,7 @@ def export_data(
else:
save_to_excel(df, saved_path, sheet_name)

elif saved_path.suffix in [".jpg", ".png", ".svg"]:
elif saved_path.suffix in [".jpg", ".png"]:
if figure is None:
Session().console.print("No plot to export.")
continue
Expand Down
7 changes: 5 additions & 2 deletions cli/openbb_cli/models/settings.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
"""Settings model"""
"""Settings model."""

from typing import Any

from dotenv import dotenv_values, set_key
from openbb_cli.config.constants import ENV_FILE_SETTINGS
from openbb_core.app.version import get_package_version
from pydantic import BaseModel, ConfigDict, model_validator

VERSION = get_package_version("openbb-cli")


class Settings(BaseModel):
"""Settings model."""

# Platform CLI version
VERSION: str = "1.0.0"
VERSION: str = VERSION

# DEVELOPMENT FLAGS
TEST_MODE: bool = False
Expand Down
2 changes: 0 additions & 2 deletions cli/tests/test_models_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
def test_default_values():
"""Test the default values of the settings model."""
settings = Settings()
assert settings.VERSION == "1.0.0"
assert settings.TEST_MODE is False
assert settings.DEBUG_MODE is False
assert settings.DEV_BACKEND is False
Expand Down Expand Up @@ -43,7 +42,6 @@ def test_repr():
settings = Settings()
repr_str = settings.__repr__() # pylint: disable=C2801
assert "Settings\n\n" in repr_str
assert "VERSION: 1.0.0" in repr_str


# Test loading from environment variables
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -554,3 +554,16 @@ def table(
ipython_display.display(ipython_display.HTML(data_as_df.to_html()))
else:
warn("IPython.display is not available.")

def url(
self,
url: str,
title: str = "",
width: Optional[int] = None,
height: Optional[int] = None,
):
"""Return the URL of the chart."""
try:
self._backend.send_url(url=url, title=title, width=width, height=height)
except Exception as e: # pylint: disable=W0718
warn(f"Failed to show figure with backend. {e}")
Original file line number Diff line number Diff line change
Expand Up @@ -201,21 +201,18 @@ def send_figure(
if self.charting_settings.chart_style == "dark"
else "rgba(255,255,255,0)"
)

title = "Interactive Chart"

fig.layout.title.text = re.sub(
r"<[^>]*>", "", fig.layout.title.text if fig.layout.title.text else title
)

fig.layout.height += 69

if export_image and isinstance(export_image, str):
export_image = Path(export_image).resolve()
export_image = Path(export_image).resolve() if export_image else None

json_data = json.loads(fig.to_json())
json_data.update(self.get_json_update(command_location))
json_data["layout"]["paper_bgcolor"] = paper_bg

outgoing = dict(
html=self.get_plotly_html(),
json_data=json_data,
Expand All @@ -224,7 +221,7 @@ def send_figure(
)
self.send_outgoing(outgoing)

if export_image and isinstance(export_image, Path):
if export_image:
if self.loop.is_closed(): # type: ignore[has-type]
# Create a new event loop
self.loop = asyncio.new_event_loop()
Expand Down Expand Up @@ -404,75 +401,6 @@ def close(self, reset: bool = False):

super().close()

async def get_results(self, description: str) -> dict:
"""Wait for completion of interactive task and return the data.

Parameters
----------
description : str
Description of the task to console print while waiting.

Returns
-------
dict
The data returned from pywry backend.
"""
warnings.warn(
f"[green]{description}[/]\n\n"
"[yellow]If the window is closed you can continue by pressing Ctrl+C.[/]"
)
while True:
try:
data: dict = self.recv.get(block=False) or {}
if data.get("result", False):
return json.loads(data["result"])
except Exception: # pylint: disable=W0703
await asyncio.sleep(0.1)

await asyncio.sleep(1)

def call_hub(self, login: bool = True) -> Optional[dict]:
"""Call the hub to login or logout.

Parameters
----------
login : bool, optional
Whether to login or logout, by default True

Returns
-------
Optional[dict]
The user data if login was successful, None otherwise.
"""
self.check_backend()
endpoint = {True: "login", False: "logout"}[login]

outgoing = dict(
json_data=dict(url=f"https://my.openbb.co/{endpoint}?pywry=true"),
**self.get_kwargs(endpoint.title()),
width=900,
height=800,
)
self.send_outgoing(outgoing)

messages_dict = dict(
login=dict(
message="Welcome to OpenBB Terminal! Please login to continue.",
interrupt="Window closed without authentication. Please proceed below.",
),
logout=dict(
message="Sending logout request", interrupt="Please login to continue."
),
)

try:
return self.loop.run_until_complete(
self.get_results(messages_dict[endpoint]["message"])
)
except KeyboardInterrupt:
warnings.warn(f"\n[red]{messages_dict[endpoint]['interrupt']}[/red]")
return None


async def download_plotly_js():
"""Download or updates plotly.js to the assets folder."""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -464,24 +464,6 @@ def _validate_x(data: Union[np.ndarray, pd.Series, type[TimeSeriesT]]):

self.update_layout(barmode="overlay", bargap=0.01, bargroupgap=0)

def is_image_export(self, export: Optional[str] = "") -> bool:
"""Check if the export format is an image format.

Parameters
----------
export : `str`
Export format

Returns
-------
`bool`
True if the export format is an image format, False otherwise
"""
if not export:
return False

return any(ext in export for ext in ["jpg", "png", "svg"])

def set_title(
self, title: str, wrap: bool = False, wrap_width: int = 80, **kwargs
) -> "OpenBBFigure":
Expand Down Expand Up @@ -917,7 +899,7 @@ def show( # noqa: PLR0915
self._exported = True

# We send the figure to the backend to be displayed
return self._backend.send_figure(self, export_image)
return self._backend.send_figure(fig=self, export_image=export_image)
except Exception as e:
# If the backend fails, we just show the figure normally
# This is a very rare case, but it's better to have a fallback
Expand Down
2 changes: 1 addition & 1 deletion website/content/cli/data-sources.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ options:
--adjustment {splits_and_dividends,unadjusted,splits_only}
The adjustment factor to apply. Default is splits only. (provider: polygon, yfinance)
-h, --help show this help message
--export EXPORT Export raw data into csv, json, xlsx and figure into png, jpg, svg
--export EXPORT Export raw data into csv, json, xlsx and figure into png or jpg
--sheet-name SHEET_NAME [SHEET_NAME ...]
Name of excel sheet to save data to. Only valid for .xlsx files.

Expand Down
2 changes: 1 addition & 1 deletion website/content/cli/quickstart.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ options:
no default.
--country COUNTRY Country of the event. (provider: nasdaq, tradingeconomics)
-h, --help show this help message
--export EXPORT Export raw data into csv, json, xlsx and figure into png, jpg, svg
--export EXPORT Export raw data into csv, json, xlsx and figure into png or jpg
--sheet-name SHEET_NAME [SHEET_NAME ...]
Name of excel sheet to save data to. Only valid for .xlsx files.

Expand Down
Loading