syd 1.0.2__py3-none-any.whl → 1.2.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.
syd/__init__.py CHANGED
@@ -1,11 +1,4 @@
1
- from typing import Callable, Optional
2
- from .viewer import Viewer
1
+ __version__ = "1.2.0"
3
2
 
4
- __version__ = "1.0.2"
5
-
6
-
7
- def make_viewer(plot_func: Optional[Callable] = None):
8
- viewer = Viewer()
9
- if plot_func is not None:
10
- viewer.set_plot(plot_func)
11
- return viewer
3
+ from .viewer import make_viewer, Viewer
4
+ from .support import show_open_servers, close_servers
@@ -6,7 +6,6 @@ from dataclasses import dataclass
6
6
  import matplotlib as mpl
7
7
  import matplotlib.pyplot as plt
8
8
  import io
9
- import time
10
9
  import webbrowser
11
10
  import threading
12
11
  import socket
@@ -20,7 +19,7 @@ from flask import (
20
19
  jsonify,
21
20
  render_template,
22
21
  )
23
- from werkzeug.serving import run_simple
22
+ from werkzeug.serving import make_server
24
23
 
25
24
  # Use Deployer base class
26
25
  from ..viewer import Viewer
@@ -43,12 +42,61 @@ from ..support import ParameterUpdateWarning, plot_context
43
42
  mpl.use("Agg")
44
43
 
45
44
 
45
+ class ServerManager:
46
+ def __init__(self):
47
+ self.servers: dict[int, "ServerThread"] = {}
48
+
49
+ def register_server(self, server: "ServerThread", port: int):
50
+ self.servers[port] = server
51
+
52
+ def close_app(self, port: int | None = None):
53
+ if port is None:
54
+ for server in self.servers.values():
55
+ server.shutdown()
56
+ self.servers.clear()
57
+ else:
58
+ if port in self.servers:
59
+ self.servers[port].shutdown()
60
+ del self.servers[port]
61
+
62
+
63
+ server_manager = ServerManager()
64
+
65
+
66
+ class ServerThread(threading.Thread):
67
+ def __init__(self, host: str, port: int, app, debug: bool):
68
+ super().__init__(daemon=True)
69
+ self.server = make_server(host, port, app, threaded=True)
70
+ self.port = port
71
+ self.debug = debug
72
+ self.ready = threading.Event()
73
+
74
+ num_open_servers = len(server_manager.servers)
75
+ if num_open_servers >= 10:
76
+ open_servers = "\n".join([f"{port}" for port in server_manager.servers])
77
+ print(
78
+ f"\nYou have {num_open_servers} open servers!\n"
79
+ f"Open servers:\n{open_servers}\n"
80
+ "You can close them with syd.close_servers() or a particular one with syd.close_servers(port).\n"
81
+ "To see a list, use: syd.show_open_servers()."
82
+ )
83
+
84
+ def run(self):
85
+ server_manager.register_server(self, self.port)
86
+ self.ready.set()
87
+ self.server.serve_forever()
88
+
89
+ def shutdown(self):
90
+ # Call this to stop the server cleanly
91
+ self.server.shutdown()
92
+
93
+
46
94
  @dataclass
47
95
  class FlaskLayoutConfig:
48
96
  """Configuration for the Flask viewer layout."""
49
97
 
50
98
  controls_position: str = "left" # Options are: 'left', 'top', 'right', 'bottom'
51
- controls_width_percent: int = 30
99
+ controls_width_percent: int = 15
52
100
 
53
101
  def __post_init__(self):
54
102
  valid_positions = ["left", "top", "right", "bottom"]
@@ -73,12 +121,14 @@ class FlaskDeployer:
73
121
  viewer: Viewer,
74
122
  controls_position: str = "left",
75
123
  fig_dpi: int = 300,
76
- controls_width_percent: int = 20,
124
+ controls_width_percent: int = 15,
77
125
  suppress_warnings: bool = True,
78
126
  debug: bool = False,
79
127
  host: str = "127.0.0.1",
80
128
  port: Optional[int] = None,
81
129
  open_browser: bool = True,
130
+ update_threshold: float = 1.0,
131
+ timeout_threshold: float = 10.0,
82
132
  ):
83
133
  """
84
134
  Initialize the Flask deployer.
@@ -107,10 +157,16 @@ class FlaskDeployer:
107
157
  Port for the server. If None, finds an available port (default: None).
108
158
  open_browser : bool, optional
109
159
  Whether to open the web application in a browser tab (default: True).
160
+ update_threshold : float, optional
161
+ Time in seconds to wait before showing the loading indicator (default: 1.0)
162
+ timeout_threshold : float, optional
163
+ Time in seconds to wait for the browser to open (default: 10.0).
110
164
  """
111
165
  self.viewer = viewer
112
166
  self.suppress_warnings = suppress_warnings
113
167
  self._updating = False # Flag to check circular updates
168
+ self.update_threshold = update_threshold # Store update threshold
169
+ self.timeout_threshold = timeout_threshold # Store timeout threshold
114
170
 
115
171
  # Flask specific configurations
116
172
  self.config = FlaskLayoutConfig(
@@ -167,12 +223,17 @@ class FlaskDeployer:
167
223
  }
168
224
  # Get the order of parameters
169
225
  param_order = list(self.viewer.parameters.keys())
170
- # Also include the initial state
226
+ # Also include the initial state and configuration
171
227
  return jsonify(
172
228
  {
173
229
  "params": param_info,
174
230
  "param_order": param_order,
175
231
  "state": self.viewer.state,
232
+ "config": {
233
+ "controls_position": self.config.controls_position,
234
+ "controls_width_percent": self.config.controls_width_percent,
235
+ "update_threshold": self.update_threshold,
236
+ },
176
237
  }
177
238
  )
178
239
 
@@ -315,7 +376,6 @@ class FlaskDeployer:
315
376
  host: str = "127.0.0.1",
316
377
  port: Optional[int] = None,
317
378
  open_browser: bool = True,
318
- **kwargs,
319
379
  ) -> None:
320
380
  """Starts the Flask development server."""
321
381
  if not self.app:
@@ -329,26 +389,59 @@ class FlaskDeployer:
329
389
  self.url = f"http://{self.host}:{self.port}"
330
390
  print(f" * Syd Flask server running on {self.url}")
331
391
 
332
- if open_browser:
333
-
334
- def open_browser_tab():
335
- time.sleep(1.0)
336
- webbrowser.open(self.url)
337
-
338
- threading.Thread(target=open_browser_tab, daemon=True).start()
339
-
340
- # Run the Flask server using Werkzeug's run_simple
341
- # Pass debug status to run_simple for auto-reloading
342
- run_simple(
343
- self.host,
344
- self.port,
345
- self.app,
346
- use_reloader=self.debug,
347
- use_debugger=self.debug,
348
- **kwargs,
349
- )
392
+ # if open_browser:
393
+
394
+ # def wait_until_responsive(url, timeout=self.timeout_threshold):
395
+ # start_time = time.time()
396
+ # while time.time() - start_time < timeout:
397
+ # try:
398
+ # r = requests.get(url, timeout=0.5)
399
+ # if r.status_code == 200:
400
+ # return True
401
+ # except requests.exceptions.RequestException:
402
+ # pass
403
+ # time.sleep(0.1)
404
+ # return False
405
+
406
+ # def open_browser_tab_when_ready():
407
+ # if wait_until_responsive(self.url):
408
+ # out = webbrowser.open(self.url, new=1, autoraise=True)
409
+ # else:
410
+ # print(
411
+ # f"Could not open browser: server at {self.url} not responding."
412
+ # f"Increase the timeout_threshold to fix this! It's set to {self.timeout_threshold} seconds."
413
+ # "You can do this from viewer.show(timeout_threshold=...) or in the FlaskDeployer constructor."
414
+ # "Also, this is unexpected so please report this issue on GitHub."
415
+ # )
416
+
417
+ # threading.Thread(target=open_browser_tab_when_ready, daemon=True).start()
418
+
419
+ # # Run the Flask server using Werkzeug's run_simple
420
+ # # Pass debug status to run_simple for auto-reloading
421
+ # run_simple(
422
+ # self.host,
423
+ # self.port,
424
+ # self.app,
425
+ # use_reloader=False,
426
+ # use_debugger=self.debug,
427
+ # )
428
+
429
+ # 1) Spin up the server thread
430
+ srv_thread = ServerThread(self.host, self.port, self.app, debug=self.debug)
431
+ srv_thread.start()
432
+
433
+ # 2) Wait for the socket‐bind event (not for an HTTP 200)
434
+ if not srv_thread.ready.wait(timeout=self.timeout_threshold):
435
+ print(
436
+ f"[!] Server did not bind within {self.timeout_threshold:.1f}s; it may already be in use."
437
+ )
438
+ else:
439
+ # 3) Now we know the app is truly listening; open a focused window
440
+ if open_browser:
441
+ webbrowser.open(self.url, new=1, autoraise=True)
350
442
 
351
- # --- Overridden Methods ---
443
+ # 4) Keep the thread handle around so you can call srv_thread.shutdown()
444
+ self._server_thread = srv_thread
352
445
 
353
446
  def deploy(self) -> None:
354
447
  """
@@ -598,7 +691,7 @@ class FlaskDeployer:
598
691
  )
599
692
 
600
693
 
601
- def _find_available_port(start_port=5000, max_attempts=100):
694
+ def _find_available_port(start_port=5000, max_attempts=1000):
602
695
  """
603
696
  Find an available port starting from start_port.
604
697
  (Identical to original)
@@ -60,14 +60,14 @@ body {
60
60
  #controls-container {
61
61
  display: grid;
62
62
  grid-template-columns: 1fr;
63
- gap: 10px;
63
+ gap: 5px;
64
64
  }
65
65
 
66
66
  /* Control groups */
67
67
  .control-group {
68
68
  display: flex;
69
69
  flex-direction: column;
70
- padding: 10px;
70
+ padding: 7px;
71
71
  border: 1px solid #eee;
72
72
  border-radius: 4px;
73
73
  background-color: white;
@@ -76,7 +76,7 @@ body {
76
76
 
77
77
  .control-label {
78
78
  font-weight: 600;
79
- margin-bottom: 10px;
79
+ margin-bottom: 0px;
80
80
  color: #333;
81
81
  text-transform: capitalize;
82
82
  }
@@ -87,38 +87,13 @@ input[type="number"] {
87
87
  padding: 8px 12px;
88
88
  border: 1px solid #ddd;
89
89
  border-radius: 4px;
90
- font-size: 14px;
90
+ font-size: 12px;
91
91
  width: 100%;
92
92
  box-sizing: border-box;
93
93
  }
94
94
 
95
- /* Range inputs */
96
95
  input[type="range"] {
97
96
  width: 100%;
98
- height: 6px;
99
- background: #ddd;
100
- border-radius: 3px;
101
- outline: none;
102
- margin: 10px 0;
103
- }
104
-
105
- input[type="range"]::-webkit-slider-thumb {
106
- -webkit-appearance: none;
107
- width: 18px;
108
- height: 18px;
109
- border-radius: 50%;
110
- background: #3f51b5;
111
- cursor: pointer;
112
- border: 1px solid #2c3e90;
113
- }
114
-
115
- input[type="range"]::-moz-range-thumb {
116
- width: 18px;
117
- height: 18px;
118
- border-radius: 50%;
119
- background: #3f51b5;
120
- cursor: pointer;
121
- border: 1px solid #2c3e90;
122
97
  }
123
98
 
124
99
  /* Checkbox styling */
@@ -184,6 +159,49 @@ button.active {
184
159
  font-style: italic;
185
160
  }
186
161
 
162
+ /* Style all numeric controls consistently */
163
+ .numeric-control {
164
+ display: flex;
165
+ align-items: center;
166
+ }
167
+
168
+ .numeric-control input[type="range"] {
169
+ flex: 1;
170
+ -webkit-appearance: none;
171
+ appearance: none;
172
+ height: 6px;
173
+ background: #ddd;
174
+ outline: none;
175
+ border-radius: 3px;
176
+ }
177
+
178
+ .numeric-control input[type="range"]::-webkit-slider-thumb {
179
+ -webkit-appearance: none;
180
+ appearance: none;
181
+ width: 16px;
182
+ height: 16px;
183
+ background: #4a90e2;
184
+ cursor: pointer;
185
+ border-radius: 50%;
186
+ }
187
+
188
+ .numeric-control input[type="range"]::-moz-range-thumb {
189
+ width: 16px;
190
+ height: 16px;
191
+ background: #4a90e2;
192
+ cursor: pointer;
193
+ border-radius: 50%;
194
+ border: none;
195
+ }
196
+
197
+ .numeric-control input[type="number"] {
198
+ width: 60px;
199
+ padding: 4px 1px;
200
+ border: 1px solid #ddd;
201
+ border-radius: 1px;
202
+ margin-left: 6px;
203
+ }
204
+
187
205
  /* Range slider styles */
188
206
  .range-container {
189
207
  display: flex;
@@ -194,7 +212,7 @@ button.active {
194
212
  .range-inputs {
195
213
  display: flex;
196
214
  justify-content: space-between;
197
- margin-bottom: 10px;
215
+ margin-bottom: 5px;
198
216
  }
199
217
 
200
218
  .range-input {
@@ -204,77 +222,92 @@ button.active {
204
222
 
205
223
  .range-slider-container {
206
224
  position: relative;
207
- margin: 10px 0;
208
- background: linear-gradient(to right,
225
+ margin: 10px 0 15px 0;
226
+ background: linear-gradient(
227
+ to right,
209
228
  #ddd 0%,
210
229
  #ddd var(--min-pos, 0%),
211
- #3f51b5 var(--min-pos, 0%),
212
- #3f51b5 var(--max-pos, 100%),
230
+ #4a90e2 var(--min-pos, 0%),
231
+ #4a90e2 var(--max-pos, 100%),
213
232
  #ddd var(--max-pos, 100%),
214
233
  #ddd 100%);
215
- border-radius: 3px;
216
- height: 18px;
234
+ border-radius: 4px;
235
+ height: 6px;
236
+ width: 100%;
217
237
  }
218
238
 
219
239
  .range-slider {
220
240
  position: absolute;
221
- top: 50%;
222
- transform: translateY(-50%);
241
+ top: 0;
223
242
  left: 0;
224
243
  width: 100%;
225
- pointer-events: none;
226
- -webkit-appearance: none;
244
+ height: 100%;
227
245
  appearance: none;
228
- background: transparent;
246
+ -webkit-appearance: none;
229
247
  cursor: pointer;
248
+ background: none;
230
249
  margin: 0;
231
- height: 18px;
250
+ padding: 0;
251
+ pointer-events: none;
232
252
  }
233
253
 
234
254
  /* Transparent Track for Webkit */
235
- .range-slider::-webkit-slider-runnable-track {
255
+ .range-slider-container .range-slider::-webkit-slider-runnable-track {
236
256
  background: transparent;
237
- border: none;
238
- border-radius: 3px;
257
+ border-radius: 2px;
258
+ height: 8px;
239
259
  }
240
260
 
241
261
  /* Transparent Track for Firefox */
242
- .range-slider::-moz-range-track {
262
+ .range-slider-container .range-slider::-moz-range-track {
243
263
  background: transparent;
244
- border: none;
245
- border-radius: 3px;
264
+ border-radius: 2px;
265
+ height: 8px;
246
266
  }
247
267
 
248
- .range-slider.active {
249
- z-index: 2;
250
- }
251
-
252
- .range-slider::-webkit-slider-thumb {
268
+ .range-slider-container .range-slider::-webkit-slider-thumb {
253
269
  pointer-events: auto;
254
270
  -webkit-appearance: none;
255
- appearance: none;
256
- width: 18px;
257
- height: 18px;
258
- border-radius: 50%;
259
- background: #3f51b5;
271
+ width: 16px;
272
+ height: 16px;
273
+ background: #4a90e2;
260
274
  cursor: pointer;
261
- border: 1px solid #2c3e90;
275
+ border-radius: 50%;
276
+ margin-top: -4px; /* center on track */
262
277
  }
263
278
 
264
- .range-slider::-moz-range-thumb {
279
+ .range-slider-container .range-slider::-moz-range-thumb {
265
280
  pointer-events: auto;
266
- width: 18px;
267
- height: 18px;
268
- border-radius: 50%;
269
- background: #3f51b5;
281
+ width: 16px;
282
+ height: 16px;
283
+ background: #4a90e2;
270
284
  cursor: pointer;
271
- border: 1px solid #2c3e90;
285
+ border-radius: 50%;
286
+ margin-top: -4px; /* center on track */
272
287
  }
273
288
 
274
289
  .min-slider {
275
- z-index: 1;
290
+ z-index: 5;
276
291
  }
277
292
 
278
293
  .max-slider {
279
- z-index: 2;
294
+ z-index: 5;
295
+ }
296
+
297
+ #status-display {
298
+ margin-top: 10px;
299
+ margin-bottom: 3px;
300
+ padding: 8px;
301
+ border-radius: 4px;
302
+ background-color: #ffffff;
303
+ border: 1px solid #e5e7eb;
304
+ }
305
+
306
+ .status-message {
307
+ background-color: #e0e0e0;
308
+ color: #000;
309
+ padding: 2px 6px;
310
+ border-radius: 4px;
311
+ font-size: 90%;
312
+ margin-left: 8px;
280
313
  }
@@ -0,0 +1,48 @@
1
+ #viewer-container {
2
+ width: 100%;
3
+ max-width: 100%;
4
+ margin: 0;
5
+ padding: 0;
6
+ box-sizing: border-box;
7
+ display: flex;
8
+ }
9
+
10
+ #controls-container {
11
+ padding: 15px;
12
+ box-sizing: border-box;
13
+ overflow-y: auto;
14
+ max-height: 100vh;
15
+ }
16
+
17
+ #plot-container {
18
+ padding: 15px;
19
+ box-sizing: border-box;
20
+ display: flex;
21
+ align-items: center;
22
+ justify-content: center;
23
+ }
24
+
25
+ #plot-container img {
26
+ max-width: 100%;
27
+ height: auto;
28
+ }
29
+
30
+ .system-controls {
31
+ margin: 10px 0px;
32
+ padding: 10px;
33
+ background-color: #ffffff;
34
+ border: 1px solid #e5e7eb;
35
+ border-radius: 4px;
36
+ }
37
+
38
+ .parameter-controls {
39
+ padding: 10px;
40
+ background-color: #ffffff;
41
+ border: 1px solid #e5e7eb;
42
+ border-radius: 4px;
43
+ }
44
+
45
+ .section-header {
46
+ margin-bottom: 15px;
47
+ font-size: 16px;
48
+ }
@@ -0,0 +1,89 @@
1
+ import { updateStatus } from './utils.js';
2
+ import { initializeState, updateStateFromServer } from './state.js';
3
+ import { updatePlot } from './plot.js';
4
+ import { setUpdateThreshold } from './config.js';
5
+
6
+ /**
7
+ * Fetch initial parameter information from the server.
8
+ * Initializes the state and gets configuration.
9
+ */
10
+ export async function fetchInitialData() {
11
+ try {
12
+ const response = await fetch('/init-data');
13
+ if (!response.ok) {
14
+ throw new Error(`HTTP error! status: ${response.status}`);
15
+ }
16
+ const data = await response.json();
17
+
18
+ setUpdateThreshold(data.config.update_threshold); // Set initial threshold
19
+ initializeState(data); // Initialize state
20
+
21
+ return data; // Return data in case the caller needs it
22
+ } catch (error) {
23
+ console.error('Error initializing viewer:', error);
24
+ updateStatus('Error initializing viewer');
25
+ throw error; // Re-throw the error to signal failure
26
+ }
27
+ }
28
+
29
+ /**
30
+ * Send parameter update to the server.
31
+ * @param {string} name - The name of the parameter.
32
+ * @param {*} value - The new value of the parameter.
33
+ * @param {boolean} [action=false] - Whether this is a button action.
34
+ */
35
+ export async function updateParameterOnServer(name, value, action = false) {
36
+ try {
37
+ const response = await fetch('/update-param', {
38
+ method: 'POST',
39
+ headers: {
40
+ 'Content-Type': 'application/json',
41
+ },
42
+ body: JSON.stringify({
43
+ name: name,
44
+ value: value,
45
+ action: action
46
+ }),
47
+ });
48
+ if (!response.ok) {
49
+ throw new Error(`HTTP error! status: ${response.status}`);
50
+ }
51
+ return await response.json(); // Return the server response (likely includes updated state)
52
+ } catch (error) {
53
+ console.error('Error updating parameter:', error);
54
+ updateStatus('Error updating parameter');
55
+ throw error; // Re-throw error
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Handles button click actions by sending to the server.
61
+ * @param {string} name - The name of the button parameter.
62
+ */
63
+ export function handleButtonClick(name) {
64
+ const button = document.getElementById(`${name}-button`);
65
+ if (!button) return;
66
+
67
+ button.classList.add('active'); // Show button as active
68
+ updateStatus(`Processing ${name}...`);
69
+
70
+ updateParameterOnServer(name, null, true) // Send action=true
71
+ .then(data => {
72
+ button.classList.remove('active');
73
+ if (data.error) {
74
+ console.error('Error:', data.error);
75
+ updateStatus(`Error processing ${name}`);
76
+ } else {
77
+ // Update state with any changes from callbacks
78
+ updateStateFromServer(data.state, data.params);
79
+ // Update plot if needed (plot.js handles this now)
80
+ updatePlot();
81
+ updateStatus('Ready!');
82
+ }
83
+ })
84
+ .catch(error => {
85
+ button.classList.remove('active');
86
+ console.error('Error during button action:', error);
87
+ updateStatus(`Error processing ${name}`);
88
+ });
89
+ }
@@ -0,0 +1,22 @@
1
+ export let updateThreshold = 1.0; // Default update threshold
2
+
3
+ // Config object parsed from HTML data attributes
4
+ export const config = {
5
+ controlsPosition: document.getElementById('viewer-config')?.dataset.controlsPosition || 'left',
6
+ controlsWidthPercent: parseInt(document.getElementById('viewer-config')?.dataset.controlsWidthPercent || 20),
7
+ plotMarginPercent: parseInt(document.getElementById('viewer-config')?.dataset.plotMarginPercent || 15)
8
+ };
9
+
10
+ // Function to update threshold, needed by system controls
11
+ export function setUpdateThreshold(value) {
12
+ updateThreshold = value;
13
+ }
14
+
15
+ // Function to update config values, needed by system controls
16
+ export function setConfigValue(key, value) {
17
+ if (key in config) {
18
+ config[key] = value;
19
+ } else {
20
+ console.warn(`Attempted to set unknown config key: ${key}`);
21
+ }
22
+ }