figpack 0.1.1__py3-none-any.whl → 0.1.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of figpack might be problematic. Click here for more details.

figpack/__init__.py CHANGED
@@ -1,5 +1,5 @@
1
1
  """
2
- figpack - A Python package for creating interactive visualizations
2
+ figpack - A Python package for creating shareable, interactive visualizations in the browser
3
3
  """
4
4
 
5
5
  __version__ = "0.1.0"
@@ -6,7 +6,9 @@ from .figpack_view import FigpackView
6
6
  thisdir = pathlib.Path(__file__).parent.resolve()
7
7
 
8
8
 
9
- def prepare_figure_bundle(view: FigpackView, tmpdir: str) -> None:
9
+ def prepare_figure_bundle(
10
+ view: FigpackView, tmpdir: str, *, title: str = None, description: str = None
11
+ ) -> None:
10
12
  """
11
13
  Prepare a figure bundle in the specified temporary directory.
12
14
 
@@ -18,6 +20,8 @@ def prepare_figure_bundle(view: FigpackView, tmpdir: str) -> None:
18
20
  Args:
19
21
  view: The figpack view to prepare
20
22
  tmpdir: The temporary directory to prepare the bundle in
23
+ title: Optional title for the figure
24
+ description: Optional description for the figure (markdown supported)
21
25
  """
22
26
  html_dir = thisdir / ".." / "figpack-gui-dist"
23
27
  if not os.path.exists(html_dir):
@@ -43,4 +47,10 @@ def prepare_figure_bundle(view: FigpackView, tmpdir: str) -> None:
43
47
  )
44
48
  view._write_to_zarr_group(zarr_group)
45
49
 
50
+ # Add title and description as attributes on the top-level zarr group
51
+ if title is not None:
52
+ zarr_group.attrs["title"] = title
53
+ if description is not None:
54
+ zarr_group.attrs["description"] = description
55
+
46
56
  zarr.consolidate_metadata(zarr_group.store)
@@ -12,6 +12,7 @@ from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
12
12
 
13
13
  from .figpack_view import FigpackView
14
14
  from ._bundle_utils import prepare_figure_bundle
15
+ from ._upload_bundle import _upload_bundle
15
16
 
16
17
  thisdir = pathlib.Path(__file__).parent.resolve()
17
18
 
@@ -22,16 +23,41 @@ def _show_view(
22
23
  open_in_browser: bool = False,
23
24
  port: Union[int, None] = None,
24
25
  allow_origin: Union[str, None] = None,
26
+ upload: bool = False,
27
+ title: Union[str, None] = None,
28
+ description: Union[str, None] = None,
25
29
  ):
26
30
  with tempfile.TemporaryDirectory(prefix="figpack_") as tmpdir:
27
- prepare_figure_bundle(view, tmpdir)
28
-
29
- serve_files(
30
- tmpdir,
31
- port=port,
32
- open_in_browser=open_in_browser,
33
- allow_origin=allow_origin,
34
- )
31
+ prepare_figure_bundle(view, tmpdir, title=title, description=description)
32
+
33
+ if upload:
34
+ # Check for required environment variable
35
+ passcode = os.environ.get("FIGPACK_UPLOAD_PASSCODE")
36
+ if not passcode:
37
+ raise EnvironmentError(
38
+ "FIGPACK_UPLOAD_PASSCODE environment variable must be set to upload views."
39
+ )
40
+
41
+ # Upload the bundle
42
+ print("Starting upload...")
43
+ figure_url = _upload_bundle(tmpdir, passcode)
44
+
45
+ if open_in_browser:
46
+ webbrowser.open(figure_url)
47
+ print(f"Opening {figure_url} in browser.")
48
+ # wait until user presses Enter
49
+ input("Press Enter to continue...")
50
+ else:
51
+ print(f"View the figure at: {figure_url}")
52
+
53
+ return figure_url
54
+ else:
55
+ serve_files(
56
+ tmpdir,
57
+ port=port,
58
+ open_in_browser=open_in_browser,
59
+ allow_origin=allow_origin,
60
+ )
35
61
 
36
62
 
37
63
  class CORSRequestHandler(SimpleHTTPRequestHandler):
@@ -1,62 +1,18 @@
1
- import os
2
1
  import time
3
2
  import json
4
3
  import uuid
5
- import tempfile
6
4
  import pathlib
7
5
  import requests
8
6
  import threading
7
+ import hashlib
8
+ from .. import __version__
9
9
  from concurrent.futures import ThreadPoolExecutor, as_completed
10
10
  from datetime import datetime, timedelta, timezone
11
11
 
12
- from .figpack_view import FigpackView
13
- from ._bundle_utils import prepare_figure_bundle
14
-
15
12
  thisdir = pathlib.Path(__file__).parent.resolve()
16
13
 
17
14
  FIGPACK_API_BASE_URL = "https://figpack-api.vercel.app"
18
- TEMPORY_BASE_URL = "https://tempory.net/figpack/figures"
19
-
20
-
21
- def _upload_view(view: FigpackView) -> str:
22
- """
23
- Upload a figpack view to the cloud
24
-
25
- Args:
26
- view: The figpack view to upload
27
-
28
- Returns:
29
- str: URL where the uploaded figure can be viewed
30
-
31
- Raises:
32
- EnvironmentError: If FIGPACK_UPLOAD_PASSCODE is not set
33
- Exception: If upload fails
34
- """
35
- # Check for required environment variable
36
- passcode = os.environ.get("FIGPACK_UPLOAD_PASSCODE")
37
- if not passcode:
38
- raise EnvironmentError(
39
- "FIGPACK_UPLOAD_PASSCODE environment variable must be set"
40
- )
41
-
42
- # Generate random figure ID
43
- figure_id = str(uuid.uuid4())
44
- print(f"Generated figure ID: {figure_id}")
45
-
46
- with tempfile.TemporaryDirectory(prefix="figpack_upload_") as tmpdir:
47
- # Prepare the figure bundle (reuse logic from _show_view)
48
- print("Preparing figure bundle...")
49
- prepare_figure_bundle(view, tmpdir)
50
-
51
- # Upload the bundle
52
- print("Starting upload...")
53
- _upload_bundle(tmpdir, figure_id, passcode)
54
-
55
- # Return the final URL
56
- figure_url = f"{TEMPORY_BASE_URL}/{figure_id}/index.html"
57
- print(f"Upload completed successfully!")
58
- print(f"Figure available at: {figure_url}")
59
- return figure_url
15
+ TEMPORY_BASE_URL = "https://tempory.net/figpack/default/figures"
60
16
 
61
17
 
62
18
  def _upload_single_file(
@@ -83,12 +39,121 @@ def _upload_single_file(
83
39
  MAX_WORKERS_FOR_UPLOAD = 16
84
40
 
85
41
 
86
- def _upload_bundle(tmpdir: str, figure_id: str, passcode: str) -> None:
42
+ def _compute_deterministic_figure_id(tmpdir_path: pathlib.Path) -> str:
43
+ """
44
+ Compute a deterministic figure ID based on SHA1 hashes of all files
45
+
46
+ Returns:
47
+ str: 40-character SHA1 hash representing the content of all files
48
+ """
49
+ file_hashes = []
50
+
51
+ # Collect all files and their hashes
52
+ for file_path in sorted(tmpdir_path.rglob("*")):
53
+ if file_path.is_file():
54
+ relative_path = file_path.relative_to(tmpdir_path)
55
+
56
+ # Compute SHA1 hash of file content
57
+ sha1_hash = hashlib.sha1()
58
+ with open(file_path, "rb") as f:
59
+ for chunk in iter(lambda: f.read(4096), b""):
60
+ sha1_hash.update(chunk)
61
+
62
+ # Include both the relative path and content hash to ensure uniqueness
63
+ file_info = f"{relative_path}:{sha1_hash.hexdigest()}"
64
+ file_hashes.append(file_info)
65
+
66
+ # Create final hash from all file hashes
67
+ combined_hash = hashlib.sha1()
68
+ for file_hash in file_hashes:
69
+ combined_hash.update(file_hash.encode("utf-8"))
70
+
71
+ return combined_hash.hexdigest()
72
+
73
+
74
+ def _check_existing_figure(figure_id: str) -> dict:
75
+ """
76
+ Check if a figure already exists and return its status
77
+
78
+ Returns:
79
+ dict: Contains 'exists' (bool) and 'status' (str) if exists
80
+ """
81
+ figpack_url = f"{TEMPORY_BASE_URL}/{figure_id}/figpack.json"
82
+
83
+ try:
84
+ response = requests.get(figpack_url, timeout=10)
85
+ if response.ok:
86
+ figpack_data = response.json()
87
+ return {"exists": True, "status": figpack_data.get("status", "unknown")}
88
+ else:
89
+ return {"exists": False}
90
+ except Exception:
91
+ return {"exists": False}
92
+
93
+
94
+ def _find_available_figure_id(base_figure_id: str) -> tuple:
95
+ """
96
+ Find an available figure ID by checking base_figure_id, then base_figure_id-1, base_figure_id-2, etc.
97
+
98
+ Returns:
99
+ tuple: (figure_id_to_use, completed_figure_id) where:
100
+ - figure_id_to_use is None if upload should be skipped
101
+ - completed_figure_id is the ID of the completed figure if one exists
102
+ """
103
+ # First check the base figure ID
104
+ result = _check_existing_figure(base_figure_id)
105
+ if not result["exists"]:
106
+ return (base_figure_id, None)
107
+ elif result["status"] == "completed":
108
+ print(
109
+ f"Figure {base_figure_id} already exists and is completed. Skipping upload."
110
+ )
111
+ return (None, base_figure_id) # Signal to skip upload, return completed ID
112
+
113
+ # If exists but not completed, try with suffixes
114
+ suffix = 1
115
+ while True:
116
+ candidate_id = f"{base_figure_id}-{suffix}"
117
+ result = _check_existing_figure(candidate_id)
118
+
119
+ if not result["exists"]:
120
+ print(f"Using figure ID: {candidate_id}")
121
+ return (candidate_id, None)
122
+ elif result["status"] == "completed":
123
+ print(
124
+ f"Figure {candidate_id} already exists and is completed. Skipping upload."
125
+ )
126
+ return (None, candidate_id) # Signal to skip upload, return completed ID
127
+
128
+ suffix += 1
129
+ if suffix > 100: # Safety limit
130
+ raise Exception(
131
+ "Too many existing figure variants, unable to find available ID"
132
+ )
133
+
134
+
135
+ def _upload_bundle(tmpdir: str, passcode: str) -> None:
87
136
  """
88
137
  Upload the prepared bundle to the cloud using parallel uploads
89
138
  """
90
139
  tmpdir_path = pathlib.Path(tmpdir)
91
140
 
141
+ # Compute deterministic figure ID based on file contents
142
+ print("Computing deterministic figure ID...")
143
+ base_figure_id = _compute_deterministic_figure_id(tmpdir_path)
144
+ print(f"Base figure ID: {base_figure_id}")
145
+
146
+ # Find available figure ID (check for existing uploads)
147
+ figure_id, completed_figure_id = _find_available_figure_id(base_figure_id)
148
+
149
+ # If figure_id is None, it means we found a completed upload and should skip
150
+ if figure_id is None:
151
+ figure_url = f"{TEMPORY_BASE_URL}/{completed_figure_id}/index.html"
152
+ print(f"Figure already exists at: {figure_url}")
153
+ return figure_url
154
+
155
+ print(f"Using figure ID: {figure_id}")
156
+
92
157
  # First, upload initial figpack.json with "uploading" status
93
158
  print("Uploading initial status...")
94
159
  figpack_json = {
@@ -96,6 +161,7 @@ def _upload_bundle(tmpdir: str, figure_id: str, passcode: str) -> None:
96
161
  "upload_started": datetime.now(timezone.utc).isoformat(),
97
162
  "upload_updated": datetime.now(timezone.utc).isoformat(),
98
163
  "figure_id": figure_id,
164
+ "figpack_version": __version__,
99
165
  }
100
166
  _upload_small_file(
101
167
  figure_id, "figpack.json", json.dumps(figpack_json, indent=2), passcode
@@ -179,8 +245,27 @@ def _upload_bundle(tmpdir: str, figure_id: str, passcode: str) -> None:
179
245
  print(f"Failed to upload {relative_path}: {e}")
180
246
  raise # Re-raise the exception to stop the upload process
181
247
 
248
+ # Create and upload manifest.json
249
+ print("Creating manifest.json...")
250
+ manifest = {
251
+ "timestamp": datetime.now(timezone.utc).isoformat(),
252
+ "files": [],
253
+ "total_size": 0,
254
+ "total_files": len(files_to_upload),
255
+ }
256
+
257
+ for rel_path, file_path in files_to_upload:
258
+ file_size = file_path.stat().st_size
259
+ manifest["files"].append({"path": rel_path, "size": file_size})
260
+ manifest["total_size"] += file_size
261
+
262
+ _upload_small_file(
263
+ figure_id, "manifest.json", json.dumps(manifest, indent=2), passcode
264
+ )
265
+ print("Uploaded manifest.json")
266
+ print(f"Total size: {manifest['total_size'] / (1024 * 1024):.2f} MB")
267
+
182
268
  # Finally, upload completion status
183
- print("Uploading completion status...")
184
269
  figpack_json = {
185
270
  **figpack_json,
186
271
  "status": "completed",
@@ -188,10 +273,16 @@ def _upload_bundle(tmpdir: str, figure_id: str, passcode: str) -> None:
188
273
  "expiration": (datetime.now(timezone.utc) + timedelta(days=1)).isoformat(),
189
274
  "figure_id": figure_id,
190
275
  "total_files": len(all_files),
276
+ "total_size": manifest["total_size"],
277
+ "figpack_version": __version__,
191
278
  }
192
279
  _upload_small_file(
193
280
  figure_id, "figpack.json", json.dumps(figpack_json, indent=2), passcode
194
281
  )
282
+ print("Upload completed successfully")
283
+
284
+ figure_url = f"{TEMPORY_BASE_URL}/{figure_id}/index.html"
285
+ return figure_url
195
286
 
196
287
 
197
288
  def _determine_file_type(file_path: str) -> str:
@@ -18,38 +18,46 @@ class FigpackView:
18
18
  port: Union[int, None] = None,
19
19
  open_in_browser: bool = False,
20
20
  allow_origin: Union[str, None] = None,
21
+ upload: bool = False,
22
+ _dev: bool = False,
23
+ title: Union[str, None] = None,
24
+ description: Union[str, None] = None,
21
25
  ):
22
26
  """
23
27
  Display the visualization component
24
- """
25
- from ._show_view import _show_view
26
-
27
- _show_view(
28
- self, port=port, open_in_browser=open_in_browser, allow_origin=allow_origin
29
- )
30
28
 
31
- def upload(self) -> str:
29
+ Args:
30
+ port: Port number for local server
31
+ open_in_browser: Whether to open in browser automatically
32
+ allow_origin: CORS allow origin header
33
+ upload: Whether to upload the figure
34
+ _dev: Development mode flag
35
+ title: Title for the browser tab and figure
36
+ description: Description text (markdown supported) for the figure
32
37
  """
33
- Upload the visualization to the cloud
34
-
35
- Returns:
36
- str: URL where the uploaded figure can be viewed
38
+ from ._show_view import _show_view
37
39
 
38
- Raises:
39
- EnvironmentError: If FIGPACK_UPLOAD_PASSCODE is not set
40
- Exception: If upload fails
41
- """
42
- from ._upload_view import _upload_view
40
+ if _dev:
41
+ if port is None:
42
+ port = 3004
43
+ if allow_origin is not None:
44
+ raise ValueError("Cannot set allow_origin when _dev is True.")
45
+ allow_origin = "http://localhost:5173"
46
+ if upload:
47
+ raise ValueError("Cannot upload when _dev is True.")
43
48
 
44
- return _upload_view(self)
49
+ print(
50
+ f"For development, run figpack-gui in dev mode and use http://localhost:5173?data=http://localhost:{port}/data.zarr"
51
+ )
45
52
 
46
- def dev(self):
47
- port = 3004
48
- print(
49
- f"For development, run figpack-gui in dev mode and use http://localhost:5173?data=http://localhost:{port}/data.zarr"
50
- )
51
- self.show(
52
- port=port, open_in_browser=False, allow_origin="http://localhost:5173"
53
+ _show_view(
54
+ self,
55
+ port=port,
56
+ open_in_browser=open_in_browser,
57
+ allow_origin=allow_origin,
58
+ upload=upload,
59
+ title=title,
60
+ description=description,
53
61
  )
54
62
 
55
63
  def _write_to_zarr_group(self, group: zarr.Group) -> None:
@@ -0,0 +1 @@
1
+ :root{font-family:system-ui,Avenir,Helvetica,Arial,sans-serif;line-height:1.5;font-weight:400;font-synthesis:none;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}a{font-weight:500;color:#646cff;text-decoration:inherit}a:hover{color:#535bf2}body{margin:0;overflow:hidden}h1{font-size:3.2em;line-height:1.1}button{border-radius:8px;border:1px solid transparent;padding:.6em 1.2em;font-size:1em;font-weight:500;font-family:inherit;background-color:#1a1a1a;cursor:pointer;transition:border-color .25s}button:hover{border-color:#646cff}button:focus,button:focus-visible{outline:4px auto -webkit-focus-ring-color}.status-bar{position:fixed;bottom:0;left:0;right:0;height:30px;background-color:#2a2a2a;color:#fff;display:flex;align-items:center;padding:0 12px;font-size:12px;border-top:1px solid #444;z-index:1000}.status-bar.warning{background-color:#ff9800;color:#000}.status-bar.error{background-color:#f44336;color:#fff}.status-bar.expired{background-color:#d32f2f;color:#fff}.manage-button{background-color:#444;color:#fff;border:none;padding:4px 8px;border-radius:4px;cursor:pointer;font-size:11px;height:22px;margin-left:12px;transition:background-color .2s}.manage-button:hover{background-color:#666}.about-button{background-color:#444;color:#fff;border:none;padding:4px 8px;border-radius:4px;cursor:pointer;font-size:11px;height:22px;margin-left:12px;transition:background-color .2s}.about-button:hover{background-color:#666}.about-dialog-overlay{position:fixed;inset:0;background-color:#00000080;display:flex;justify-content:center;align-items:center;z-index:2000}.about-dialog{background-color:#2a2a2a;color:#fff;border-radius:8px;max-width:600px;max-height:80vh;width:90%;box-shadow:0 4px 20px #0000004d;overflow:hidden}.about-dialog-header{display:flex;justify-content:space-between;align-items:center;padding:16px 20px;border-bottom:1px solid #444}.about-dialog-header h2{margin:0;font-size:18px;font-weight:600}.about-dialog-close{background:none;border:none;color:#fff;font-size:24px;cursor:pointer;padding:0;width:30px;height:30px;display:flex;align-items:center;justify-content:center;border-radius:4px;transition:background-color .2s}.about-dialog-close:hover{background-color:#444}.about-dialog-content{padding:20px;overflow-y:auto;max-height:calc(80vh - 80px)}.about-dialog-description{line-height:1.6}.about-dialog-description h1,.about-dialog-description h2,.about-dialog-description h3{margin-top:0;margin-bottom:12px}.about-dialog-description p{margin-bottom:12px}.about-dialog-description code{background-color:#444;padding:2px 4px;border-radius:3px;font-family:Courier New,monospace;font-size:.9em}.about-dialog-description pre{background-color:#444;padding:12px;border-radius:4px;overflow-x:auto;margin-bottom:12px}.about-dialog-description ul,.about-dialog-description ol{margin-bottom:12px;padding-left:20px}.about-dialog-description blockquote{border-left:4px solid #666;padding-left:16px;margin:12px 0;font-style:italic}@media (prefers-color-scheme: light){:root{color:#213547;background-color:#fff}a:hover{color:#747bff}button{background-color:#f9f9f9}.status-bar{background-color:#f5f5f5;color:#333;border-top:1px solid #ddd}.status-bar.warning{background-color:#fff3cd;color:#856404;border-top:1px solid #ffeaa7}.status-bar.error,.status-bar.expired{background-color:#f8d7da;color:#721c24;border-top:1px solid #f5c6cb}.manage-button{background-color:#e0e0e0;color:#333;border:1px solid #ccc}.manage-button:hover{background-color:#d0d0d0}.about-button{background-color:#e0e0e0;color:#333;border:1px solid #ccc}.about-button:hover{background-color:#d0d0d0}.about-dialog{background-color:#fff;color:#333;box-shadow:0 4px 20px #00000026}.about-dialog-header{border-bottom:1px solid #ddd}.about-dialog-close{color:#333}.about-dialog-close:hover{background-color:#f0f0f0}.about-dialog-description code,.about-dialog-description pre{background-color:#f5f5f5;color:#333}.about-dialog-description blockquote{border-left:4px solid #ccc}}