|
2 | 2 | import kaleido |
3 | 3 | from pathlib import Path |
4 | 4 |
|
| 5 | +from vuecore.constants import OutputFileFormat |
| 6 | + |
5 | 7 |
|
6 | 8 | def save(fig: go.Figure, filepath: str) -> None: |
7 | 9 | """ |
@@ -33,34 +35,53 @@ def save(fig: go.Figure, filepath: str) -> None: |
33 | 35 | suffix = path.suffix.lower() |
34 | 36 |
|
35 | 37 | try: |
36 | | - if suffix in [".png", ".jpg", ".jpeg", ".webp", ".svg", ".pdf"]: |
| 38 | + # Define static suffixes from the OutputFileFormat enum |
| 39 | + image_suffixes = [ |
| 40 | + OutputFileFormat.PNG.value_with_dot, |
| 41 | + OutputFileFormat.JPG.value_with_dot, |
| 42 | + OutputFileFormat.JPEG.value_with_dot, |
| 43 | + OutputFileFormat.WEBP.value_with_dot, |
| 44 | + OutputFileFormat.SVG.value_with_dot, |
| 45 | + OutputFileFormat.PDF.value_with_dot, |
| 46 | + ] |
| 47 | + |
| 48 | + if suffix in image_suffixes: |
37 | 49 | try: |
38 | 50 | fig.write_image(filepath) |
39 | 51 | except RuntimeError as e: |
| 52 | + # Handle specific Kaleido errors for Chrome installation |
40 | 53 | if "Kaleido requires Google Chrome" in str(e): |
41 | 54 | print( |
42 | 55 | "[VueCore] Chrome not found. Attempting automatic install using `kaleido.get_chrome_sync()`..." |
43 | 56 | ) |
44 | 57 | try: |
45 | 58 | kaleido.get_chrome_sync() |
46 | | - fig.write_image(filepath) # Retry after installing Chrome |
| 59 | + # Retry after installing Chrome |
| 60 | + fig.write_image(filepath) |
47 | 61 | except Exception as install_error: |
48 | 62 | raise RuntimeError( |
49 | 63 | "[VueCore] Failed to install Chrome automatically. " |
50 | 64 | "Please install it manually or run `plotly_get_chrome`." |
51 | 65 | ) from install_error |
52 | 66 | else: |
53 | | - raise |
54 | | - elif suffix == ".html": |
| 67 | + raise # Re-raise other RuntimeError exceptions |
| 68 | + elif suffix == OutputFileFormat.HTML.value_with_dot: |
55 | 69 | fig.write_html(filepath, include_plotlyjs="cdn") |
56 | | - elif suffix == ".json": |
57 | | - fig.write_json(filepath, pretty=True) |
| 70 | + elif suffix == OutputFileFormat.JSON.value_with_dot: |
| 71 | + fig.write_json( |
| 72 | + filepath, pretty=True |
| 73 | + ) # Added pretty=True for readable JSON output |
58 | 74 | else: |
| 75 | + # Generate a dynamic list of supported formats for the error message |
| 76 | + supported_suffixes = ", ".join( |
| 77 | + [f"'{f.value_with_dot}'" for f in OutputFileFormat] |
| 78 | + ) |
59 | 79 | raise ValueError( |
60 | 80 | f"Unsupported file format: '{suffix}'. " |
61 | | - "Supported formats: .png, .jpg, .jpeg, .webp, .svg, .pdf, .html, .json" |
| 81 | + f"Supported formats: {supported_suffixes}" |
62 | 82 | ) |
63 | 83 | except Exception as e: |
| 84 | + # Catch any exceptions during the saving process and re-raise as a RuntimeError |
64 | 85 | raise RuntimeError(f"[VueCore] Failed to save plot: {filepath}") from e |
65 | 86 |
|
66 | 87 | print(f"[VueCore] Plot saved to {filepath}") |
0 commit comments