arrayview 0.25.0__py3-none-any.whl → 0.26.0__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.
arrayview/__init__.py CHANGED
@@ -1,4 +1,4 @@
1
- __version__ = "0.20.0"
1
+ __version__ = "0.25.1"
2
2
 
3
3
  __all__ = [
4
4
  "TrainingMonitor",
arrayview/_io.py CHANGED
@@ -67,7 +67,7 @@ def list_mat_keys(filepath):
67
67
  for k, v in mat.items():
68
68
  if k.startswith("_"):
69
69
  continue
70
- if isinstance(v, np.ndarray) and v.ndim >= 1:
70
+ if isinstance(v, np.ndarray) and v.ndim >= 1 and v.dtype.kind in ("b", "i", "u", "f", "c"):
71
71
  keys.append({"key": k, "shape": list(v.shape), "dtype": str(v.dtype)})
72
72
  return keys
73
73
  except NotImplementedError:
@@ -77,7 +77,7 @@ def list_mat_keys(filepath):
77
77
  keys = []
78
78
  for k in f.keys():
79
79
  ds = f[k]
80
- if isinstance(ds, h5py.Dataset) and len(ds.shape) >= 1:
80
+ if isinstance(ds, h5py.Dataset) and len(ds.shape) >= 1 and ds.dtype.kind in ("b", "i", "u", "f", "c"):
81
81
  keys.append({"key": k, "shape": list(ds.shape), "dtype": str(ds.dtype)})
82
82
  f.close()
83
83
  return keys
arrayview/_launcher.py CHANGED
@@ -448,6 +448,17 @@ def _open_webview_cli(
448
448
  Returns True once the child has imported pywebview and created the window.
449
449
  Returns False if it crashed; in that case the caller should fall back to browser.
450
450
  """
451
+ opened, _proc = _open_webview_cli_tracked(url, win_w, win_h, shell_port=shell_port)
452
+ return opened
453
+
454
+
455
+ def _open_webview_cli_tracked(
456
+ url: str,
457
+ win_w: int,
458
+ win_h: int,
459
+ shell_port: int | None = None,
460
+ ) -> tuple[bool, subprocess.Popen | None]:
461
+ """Launch pywebview and return the child process when startup succeeds."""
451
462
  import tempfile
452
463
 
453
464
  _vprint("[ArrayView] Launching native window (PyWebView)...", flush=True)
@@ -483,21 +494,64 @@ def _open_webview_cli(
483
494
  )
484
495
  if stderr_out:
485
496
  _vprint(f"[ArrayView] webview stderr: {stderr_out}", flush=True)
486
- return False
497
+ return False, None
487
498
  if os.path.exists(ready_file):
488
499
  try:
489
500
  os.unlink(ready_file)
490
501
  except OSError:
491
502
  pass
492
503
  _vprint("[ArrayView] Native window started successfully", flush=True)
493
- return True
504
+ return True, proc
494
505
  time.sleep(0.02)
495
506
  try:
496
507
  os.unlink(ready_file)
497
508
  except OSError:
498
509
  pass
499
510
  _vprint("[ArrayView] Native window started successfully", flush=True)
500
- return True
511
+ return True, proc
512
+
513
+
514
+ def _server_viewer_connections_seen(port: int, timeout: float = 0.5) -> int:
515
+ """Return the daemon's monotonic viewer WebSocket connection count."""
516
+ url = f"http://{_LOOPBACK_HOST}:{port}/ping"
517
+ try:
518
+ with urllib.request.urlopen(url, timeout=timeout) as resp:
519
+ if resp.status != 200:
520
+ return 0
521
+ payload = json.loads(resp.read().decode("utf-8"))
522
+ if payload.get("ok") is True and payload.get("service") == "arrayview":
523
+ return int(
524
+ payload.get("viewer_connections_seen")
525
+ or payload.get("viewer_sockets")
526
+ or 0
527
+ )
528
+ except Exception:
529
+ pass
530
+ return 0
531
+
532
+
533
+ def _wait_for_viewer_connection(
534
+ port: int,
535
+ *,
536
+ before: int,
537
+ timeout: float = 8.0,
538
+ ) -> bool:
539
+ """Wait until the backend has accepted a new viewer WebSocket connection."""
540
+ deadline = time.monotonic() + timeout
541
+ while time.monotonic() < deadline:
542
+ if _server_viewer_connections_seen(port, timeout=0.3) > before:
543
+ return True
544
+ time.sleep(0.1)
545
+ return False
546
+
547
+
548
+ def _terminate_native_process(proc: subprocess.Popen | None) -> None:
549
+ if proc is None or proc.poll() is not None:
550
+ return
551
+ try:
552
+ proc.terminate()
553
+ except Exception:
554
+ return
501
555
 
502
556
 
503
557
  # ── Server Port Utilities ─────────────────────────────────────────
@@ -809,7 +863,15 @@ def _open_cli_existing_server_view(
809
863
  return
810
864
  if notify_webview and not notified:
811
865
  url_shell = _shell_url(port, sid, name, compare_sids=compare_sids)
812
- if not _open_webview_cli(url_shell, 1200, 800):
866
+ seen_before = _server_viewer_connections_seen(port)
867
+ opened, proc = _open_webview_cli_tracked(url_shell, 1200, 800)
868
+ if not opened or not _wait_for_viewer_connection(port, before=seen_before):
869
+ if opened:
870
+ _vprint(
871
+ "[ArrayView] Native window did not connect to the backend; falling back to browser",
872
+ flush=True,
873
+ )
874
+ _terminate_native_process(proc)
813
875
  _vprint("[ArrayView] Falling back to browser", flush=True)
814
876
  _print_viewer_location(url)
815
877
  _open_browser(
@@ -993,7 +1055,9 @@ def _handle_cli_spawned_daemon(
993
1055
  )
994
1056
 
995
1057
  early_webview_opened = False
1058
+ early_webview_proc = None
996
1059
  early_webview_notified = False
1060
+ early_webview_connected = False
997
1061
  if (
998
1062
  use_webview
999
1063
  and not is_remote
@@ -1001,7 +1065,7 @@ def _handle_cli_spawned_daemon(
1001
1065
  and not compare_files
1002
1066
  ):
1003
1067
  url_shell_early = _shell_url(port, sid, name)
1004
- early_webview_opened = _open_webview_cli(
1068
+ early_webview_opened, early_webview_proc = _open_webview_cli_tracked(
1005
1069
  url_shell_early, 1400, 900, shell_port=port
1006
1070
  )
1007
1071
 
@@ -1019,6 +1083,7 @@ def _handle_cli_spawned_daemon(
1019
1083
  sys.exit(1)
1020
1084
 
1021
1085
  if early_webview_opened:
1086
+ seen_before = _server_viewer_connections_seen(port)
1022
1087
  try:
1023
1088
  notify_result = _notify_existing_session(
1024
1089
  port,
@@ -1030,6 +1095,21 @@ def _handle_cli_spawned_daemon(
1030
1095
  early_webview_notified = bool(notify_result.get("notified"))
1031
1096
  except Exception:
1032
1097
  early_webview_notified = False
1098
+ if early_webview_notified:
1099
+ early_webview_connected = _wait_for_viewer_connection(
1100
+ port,
1101
+ before=seen_before,
1102
+ )
1103
+ if not early_webview_connected:
1104
+ _vprint(
1105
+ "[ArrayView] Native window did not connect to the backend; falling back to browser",
1106
+ flush=True,
1107
+ )
1108
+ _terminate_native_process(early_webview_proc)
1109
+
1110
+ should_retry_webview = use_webview and not (
1111
+ early_webview_opened and not early_webview_connected
1112
+ )
1033
1113
 
1034
1114
  _open_cli_spawned_view(
1035
1115
  port=port,
@@ -1037,14 +1117,14 @@ def _handle_cli_spawned_daemon(
1037
1117
  compare_sids=compare_sids,
1038
1118
  overlay_sid=overlay_sid,
1039
1119
  dims_override=dims_override,
1040
- use_webview=use_webview,
1120
+ use_webview=should_retry_webview,
1041
1121
  name=name,
1042
1122
  base_file=base_file,
1043
1123
  watch=watch,
1044
1124
  window_mode=window_mode,
1045
1125
  floating=floating,
1046
1126
  is_remote=is_remote,
1047
- webview_already_opened=early_webview_opened,
1127
+ webview_already_opened=early_webview_connected,
1048
1128
  )
1049
1129
 
1050
1130
 
@@ -1075,7 +1155,15 @@ def _open_cli_spawned_view(
1075
1155
  if webview_already_opened:
1076
1156
  return
1077
1157
  url_shell = _shell_url(port, sid, name, compare_sids=compare_sids)
1078
- if not _open_webview_cli(url_shell, 1400, 900):
1158
+ seen_before = _server_viewer_connections_seen(port)
1159
+ opened, proc = _open_webview_cli_tracked(url_shell, 1400, 900)
1160
+ if not opened or not _wait_for_viewer_connection(port, before=seen_before):
1161
+ if opened:
1162
+ _vprint(
1163
+ "[ArrayView] Native window did not connect to the backend; falling back to browser",
1164
+ flush=True,
1165
+ )
1166
+ _terminate_native_process(proc)
1079
1167
  _vprint("[ArrayView] Falling back to browser", flush=True)
1080
1168
  _print_viewer_location(url)
1081
1169
  _open_browser(
@@ -2621,7 +2709,16 @@ def _serve_daemon(
2621
2709
  from arrayview._io import load_data, load_data_with_meta, list_array_keys
2622
2710
 
2623
2711
  try:
2624
- data, spatial_meta = load_data_with_meta(filepath)
2712
+ # Multi-array .npz/.mat: load the first array so the session is
2713
+ # created, then store keys so the viewer can show a picker.
2714
+ _array_keys = None
2715
+ if (filepath.endswith(".npz") or filepath.endswith(".mat")) and not cleanup:
2716
+ try:
2717
+ _array_keys = list_array_keys(filepath)
2718
+ except Exception:
2719
+ pass
2720
+ _load_key = _array_keys[0]["key"] if _array_keys and len(_array_keys) > 1 else None
2721
+ data, spatial_meta = load_data_with_meta(filepath, key=_load_key)
2625
2722
  if cleanup:
2626
2723
  try:
2627
2724
  os.unlink(filepath)
@@ -2632,15 +2729,9 @@ def _serve_daemon(
2632
2729
  )
2633
2730
  session.sid = sid
2634
2731
  session.spatial_meta = spatial_meta
2635
- # Multi-array .npz/.mat: store keys so the viewer can show a picker
2636
- if (filepath.endswith(".npz") or filepath.endswith(".mat")) and not cleanup:
2637
- try:
2638
- keys = list_array_keys(filepath)
2639
- if len(keys) > 1:
2640
- session.array_keys = keys
2641
- session.array_filepath = filepath
2642
- except Exception:
2643
- pass
2732
+ if _array_keys and len(_array_keys) > 1:
2733
+ session.array_keys = _array_keys
2734
+ session.array_filepath = filepath
2644
2735
  if spatial_meta is not None:
2645
2736
  session.original_volume = data
2646
2737
  if rgb:
@@ -2905,6 +2996,8 @@ def arrayview():
2905
2996
  return
2906
2997
 
2907
2998
  parser = argparse.ArgumentParser(description="Lightning Fast ND Array Viewer")
2999
+ from arrayview import __version__ as _av_version
3000
+ parser.add_argument("--version", action="version", version=f"arrayview {_av_version}")
2908
3001
  parser.add_argument(
2909
3002
  "files",
2910
3003
  nargs="*",
@@ -3165,10 +3258,62 @@ def arrayview():
3165
3258
  # --diagnose: print detection results and exit
3166
3259
  if getattr(args, "diagnose", False):
3167
3260
  import json as _json
3261
+ import importlib.util as _importlib_util
3168
3262
  from ._platform import (
3169
3263
  _find_vscode_ipc_hook,
3170
3264
  _in_jupyter,
3171
3265
  )
3266
+ from arrayview._config import CONFIG_PATH, get_window_default, load_config
3267
+ from arrayview._platform import detect_environment
3268
+
3269
+ _det_env = detect_environment()
3270
+ _config_window = get_window_default(_det_env)
3271
+ _in_vs = _in_vscode_terminal()
3272
+ _is_remote = _is_vscode_remote()
3273
+ _can_native = _can_native_window()
3274
+ _window_plan = _resolve_cli_window_mode(
3275
+ explicit_window=args.window,
3276
+ browser_flag=args.browser,
3277
+ config_window=_config_window,
3278
+ in_vscode_terminal=_in_vs,
3279
+ is_vscode_remote=_is_remote,
3280
+ can_native_window=_can_native,
3281
+ )
3282
+
3283
+ def _localhost_candidates() -> list[dict[str, object]]:
3284
+ out = []
3285
+ try:
3286
+ infos = socket.getaddrinfo(
3287
+ _LOOPBACK_HOST,
3288
+ args.port,
3289
+ type=socket.SOCK_STREAM,
3290
+ )
3291
+ except Exception as exc:
3292
+ return [{"error": str(exc)}]
3293
+ for family, socktype, proto, _canon, sockaddr in infos:
3294
+ out.append(
3295
+ {
3296
+ "family": getattr(socket.AddressFamily(family), "name", str(family)),
3297
+ "socktype": socktype,
3298
+ "proto": proto,
3299
+ "sockaddr": str(sockaddr),
3300
+ }
3301
+ )
3302
+ return out
3303
+
3304
+ def _bind_probe(port: int) -> dict[str, object]:
3305
+ try:
3306
+ sock = _make_loopback_socket(port)
3307
+ except Exception as exc:
3308
+ return {"ok": False, "error": str(exc)}
3309
+ try:
3310
+ return {
3311
+ "ok": True,
3312
+ "family": getattr(socket.AddressFamily(sock.family), "name", str(sock.family)),
3313
+ "sockname": str(sock.getsockname()),
3314
+ }
3315
+ finally:
3316
+ sock.close()
3172
3317
 
3173
3318
  diag: dict = {
3174
3319
  "env": {
@@ -3182,28 +3327,40 @@ def arrayview():
3182
3327
  "WAYLAND_DISPLAY": os.environ.get("WAYLAND_DISPLAY"),
3183
3328
  },
3184
3329
  "detection": {
3185
- "in_vscode_terminal": _in_vscode_terminal(),
3186
- "is_vscode_remote": _is_vscode_remote(),
3330
+ "in_vscode_terminal": _in_vs,
3331
+ "is_vscode_remote": _is_remote,
3187
3332
  "in_vscode_tunnel": _in_vscode_tunnel(),
3188
- "can_native_window": _can_native_window(),
3333
+ "can_native_window": _can_native,
3189
3334
  "in_jupyter": _in_jupyter(),
3190
3335
  "vscode_ipc_hook_recovered": _find_vscode_ipc_hook(),
3191
3336
  },
3337
+ "launch_plan": {
3338
+ **_window_plan,
3339
+ "port": args.port,
3340
+ "port_in_use": _port_in_use(args.port),
3341
+ "arrayview_server_alive": _server_alive(args.port),
3342
+ },
3343
+ "loopback": {
3344
+ "host": _LOOPBACK_HOST,
3345
+ "getaddrinfo": _localhost_candidates(),
3346
+ "bind_probe": _bind_probe(0),
3347
+ },
3348
+ "native_dependencies": {
3349
+ "qtpy": _importlib_util.find_spec("qtpy") is not None,
3350
+ "gi": _importlib_util.find_spec("gi") is not None,
3351
+ "webview": _importlib_util.find_spec("webview") is not None,
3352
+ },
3192
3353
  "pid": os.getpid(),
3193
3354
  "ppid": os.getppid(),
3194
3355
  "platform": sys.platform,
3195
3356
  "python": sys.executable,
3196
3357
  }
3197
- from arrayview._config import CONFIG_PATH, get_window_default, load_config
3198
- from arrayview._platform import detect_environment
3199
-
3200
- _det_env = detect_environment()
3201
3358
  diag["config"] = {
3202
3359
  "detected_environment": _det_env,
3203
3360
  "config_file": CONFIG_PATH,
3204
3361
  "config_contents": load_config() or None,
3205
3362
  "ARRAYVIEW_WINDOW": os.environ.get("ARRAYVIEW_WINDOW") or None,
3206
- "resolved_window_pref": get_window_default(_det_env),
3363
+ "resolved_window_pref": _config_window,
3207
3364
  }
3208
3365
  print(_json.dumps(diag, indent=2))
3209
3366
  return
arrayview/_server.py CHANGED
@@ -20,6 +20,7 @@ from arrayview._session import (
20
20
  SESSIONS,
21
21
  COLORMAPS,
22
22
  )
23
+ from arrayview import __version__ as _av_version
23
24
  import arrayview._session as _session_mod # for mutable VIEWER_SOCKETS
24
25
 
25
26
  from arrayview._render import (
@@ -152,6 +153,7 @@ def ping():
152
153
  "pid": os.getpid(),
153
154
  "hostname": socket.gethostname(),
154
155
  "viewer_sockets": _session_mod.VIEWER_SOCKETS,
156
+ "viewer_connections_seen": _session_mod.VIEWER_CONNECTIONS_SEEN,
155
157
  }
156
158
 
157
159
 
@@ -194,6 +196,7 @@ def get_ui(sid: str = None):
194
196
  .replace("__DEFAULT_THEME_IDX__", str(_default_theme_idx))
195
197
  .replace("__DEFAULT_ROUNDED_PANES__", _default_rounded_panes)
196
198
  .replace("__BODY_CLASS__", "av-loading" if sid else "")
199
+ .replace("__ARRAYVIEW_VERSION__", _av_version)
197
200
  )
198
201
  headers = {"Cache-Control": "no-store"}
199
202
  return HTMLResponse(content=html, headers=headers)
@@ -23,6 +23,7 @@ import uuid
23
23
 
24
24
  import numpy as np
25
25
 
26
+ from arrayview import __version__ as _av_version
26
27
  from arrayview._analysis import (
27
28
  _build_metadata,
28
29
  _lebesgue_slice,
@@ -686,6 +687,7 @@ def _handle_get_viewer_html(msg: dict) -> None:
686
687
  .replace("__DEFAULT_THEME_IDX__", str(_default_theme_idx))
687
688
  .replace("__DEFAULT_ROUNDED_PANES__", _default_rounded_panes)
688
689
  .replace("__BODY_CLASS__", "av-loading" if sid else "")
690
+ .replace("__ARRAYVIEW_VERSION__", _av_version)
689
691
  )
690
692
 
691
693
  _write_json({"html": html})