xprof 2.22.2__py3-none-win_amd64.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.
Files changed (71) hide show
  1. xprof/__init__.py +23 -0
  2. xprof/api/continuous_profiling_snapshot.py +73 -0
  3. xprof/convert/_pywrap_profiler_plugin.py +506 -0
  4. xprof/convert/csv_writer.py +139 -0
  5. xprof/convert/profiler_plugin_c_api.pyd +0 -0
  6. xprof/convert/raw_to_tool_data.py +237 -0
  7. xprof/convert/trace_events_json.py +105 -0
  8. xprof/integration_tests/tf_mnist.py +100 -0
  9. xprof/integration_tests/tf_profiler_session.py +40 -0
  10. xprof/integration_tests/tpu/tensorflow/tpu_tf2_keras_test.py +183 -0
  11. xprof/profile_io.py +411 -0
  12. xprof/profile_plugin.py +1896 -0
  13. xprof/profile_plugin_loader.py +82 -0
  14. xprof/protobuf/dcn_collective_info_pb2.py +44 -0
  15. xprof/protobuf/dcn_slack_analysis_pb2.py +42 -0
  16. xprof/protobuf/diagnostics_pb2.py +36 -0
  17. xprof/protobuf/event_time_fraction_analyzer_pb2.py +54 -0
  18. xprof/protobuf/hardware_types_pb2.py +40 -0
  19. xprof/protobuf/hlo_stats_pb2.py +41 -0
  20. xprof/protobuf/inference_stats_pb2.py +86 -0
  21. xprof/protobuf/input_pipeline_pb2.py +52 -0
  22. xprof/protobuf/kernel_stats_pb2.py +38 -0
  23. xprof/protobuf/memory_profile_pb2.py +56 -0
  24. xprof/protobuf/memory_viewer_preprocess_pb2.py +49 -0
  25. xprof/protobuf/op_metrics_pb2.py +71 -0
  26. xprof/protobuf/op_profile_pb2.py +49 -0
  27. xprof/protobuf/op_stats_pb2.py +75 -0
  28. xprof/protobuf/overview_page_pb2.py +65 -0
  29. xprof/protobuf/pod_stats_pb2.py +45 -0
  30. xprof/protobuf/pod_viewer_pb2.py +61 -0
  31. xprof/protobuf/power_metrics_pb2.py +38 -0
  32. xprof/protobuf/roofline_model_pb2.py +44 -0
  33. xprof/protobuf/smart_suggestion_pb2.py +38 -0
  34. xprof/protobuf/source_info_pb2.py +36 -0
  35. xprof/protobuf/source_stats_pb2.py +50 -0
  36. xprof/protobuf/steps_db_pb2.py +76 -0
  37. xprof/protobuf/task_pb2.py +37 -0
  38. xprof/protobuf/tf_data_stats_pb2.py +72 -0
  39. xprof/protobuf/tf_function_pb2.py +52 -0
  40. xprof/protobuf/tf_stats_pb2.py +42 -0
  41. xprof/protobuf/tfstreamz_pb2.py +40 -0
  42. xprof/protobuf/topology_pb2.py +50 -0
  43. xprof/protobuf/tpu_input_pipeline_pb2.py +43 -0
  44. xprof/protobuf/trace_data_response_pb2.py +48 -0
  45. xprof/protobuf/trace_events_old_pb2.py +54 -0
  46. xprof/protobuf/trace_events_pb2.py +64 -0
  47. xprof/protobuf/trace_events_raw_pb2.py +45 -0
  48. xprof/protobuf/trace_filter_config_pb2.py +40 -0
  49. xprof/server.py +359 -0
  50. xprof/standalone/base_plugin.py +52 -0
  51. xprof/standalone/context.py +22 -0
  52. xprof/standalone/data_provider.py +32 -0
  53. xprof/standalone/plugin_asset_util.py +131 -0
  54. xprof/standalone/plugin_event_multiplexer.py +185 -0
  55. xprof/standalone/tensorboard_shim.py +31 -0
  56. xprof/static/bundle.js +137744 -0
  57. xprof/static/index.html +64 -0
  58. xprof/static/index.js +3 -0
  59. xprof/static/materialicons.woff2 +0 -0
  60. xprof/static/styles.css +1 -0
  61. xprof/static/trace_viewer_index.html +3935 -0
  62. xprof/static/trace_viewer_index.js +15946 -0
  63. xprof/static/trace_viewer_v2.js +8103 -0
  64. xprof/static/trace_viewer_v2.wasm +0 -0
  65. xprof/static/zone.js +3558 -0
  66. xprof/version.py +18 -0
  67. xprof-2.22.2.dist-info/METADATA +354 -0
  68. xprof-2.22.2.dist-info/RECORD +71 -0
  69. xprof-2.22.2.dist-info/WHEEL +5 -0
  70. xprof-2.22.2.dist-info/entry_points.txt +5 -0
  71. xprof-2.22.2.dist-info/top_level.txt +1 -0
xprof/__init__.py ADDED
@@ -0,0 +1,23 @@
1
+ # Copyright 2025 The XProf Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ """Entry point for the TensorBoard plugin package for XProf.
16
+
17
+ Public submodules:
18
+ profile_plugin: The TensorBoard plugin integration.
19
+ profile_plugin_loader: TensorBoard's entrypoint for the plugin.
20
+ profile_io: File I/O utilities for the plugin.
21
+ server: Standalone server entrypoint.
22
+ version: The version of the plugin.
23
+ """
@@ -0,0 +1,73 @@
1
+ # Copyright 2026 The TensorFlow Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ """Continuous profiling Snapshot APIs."""
16
+
17
+ from collections.abc import Mapping
18
+ import dataclasses
19
+ import os
20
+ from typing import Any
21
+
22
+ from xprof.convert import _pywrap_profiler_plugin
23
+
24
+
25
+ @dataclasses.dataclass
26
+ class ContinuousProfilingSnapshot:
27
+ """A handler for continuous profiling."""
28
+
29
+ _profiler_plugin: Any = dataclasses.field(
30
+ default_factory=lambda: _pywrap_profiler_plugin
31
+ )
32
+
33
+ def start_continuous_profiling(
34
+ self, service_addr: str, options: Mapping[str, Any]
35
+ ) -> None:
36
+ """Starts continuous profiling on the profiling service.
37
+
38
+ Args:
39
+ service_addr: Address of the profiling service (e.g. localhost:6006).
40
+ options: A dictionary of profiling options derived from
41
+ tensorflow.compiler.xla.tsl.profiler ProfileOptions. Expected keys
42
+ include 'include_dataset_ops','repository_path',
43
+ 'raise_error_on_start_failure', 'advanced_configuration', etc. Example:
44
+ `{'duration_ms': 1000}`.
45
+ """
46
+
47
+ self._profiler_plugin.start_continuous_profiling(service_addr, options)
48
+
49
+ def stop_continuous_profiling(self, service_addr: str) -> None:
50
+ """Stops continuous profiling on the profiling service.
51
+
52
+ Args:
53
+ service_addr: Address of the profiling service (e.g. localhost:6006).
54
+ """
55
+ self._profiler_plugin.stop_continuous_profiling(service_addr)
56
+
57
+ def get_snapshot(self, service_addr: str, logdir: os.PathLike[str]) -> None:
58
+ """Gets a snapshot of the profiling result.
59
+
60
+ Args:
61
+ service_addr: Address of the profiling service (e.g. localhost:6006).
62
+ logdir: Directory to save the profiling result (e.g.
63
+ /tmp/profile_snapshot).
64
+ """
65
+ self._profiler_plugin.get_snapshot(service_addr, logdir)
66
+
67
+
68
+ _default_profiler = ContinuousProfilingSnapshot()
69
+
70
+
71
+ start_continuous_profiling = _default_profiler.start_continuous_profiling
72
+ stop_continuous_profiling = _default_profiler.stop_continuous_profiling
73
+ get_snapshot = _default_profiler.get_snapshot
@@ -0,0 +1,506 @@
1
+ """Python wrapper for the profiler plugin C API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping, Sequence
6
+ import ctypes
7
+ import dataclasses
8
+ import enum
9
+ import glob
10
+ import itertools
11
+ import os
12
+ import threading
13
+ from typing import Any
14
+
15
+
16
+ class OptionType(enum.IntEnum):
17
+ BOOLEAN = 0
18
+ INTEGER = 1
19
+ STRING = 2
20
+
21
+
22
+ @dataclasses.dataclass
23
+ class PackedOptions:
24
+ """Packed options for the C API.
25
+
26
+ Attributes:
27
+ keys: Ctypes array of option keys.
28
+ string_vals: Ctypes array of string values.
29
+ int_vals: Ctypes array of int values.
30
+ bool_vals: Ctypes array of bool values.
31
+ types: Ctypes array of option types.
32
+ num_options: Number of options.
33
+ keep_alive: List of bytes objects to keep alive for the C API.
34
+ """
35
+
36
+ keys: ctypes.Array[ctypes.c_char_p] | None
37
+ string_vals: ctypes.Array[ctypes.c_char_p] | None
38
+ int_vals: ctypes.Array[ctypes.c_int] | None
39
+ bool_vals: ctypes.Array[ctypes.c_bool] | None
40
+ types: ctypes.Array[ctypes.c_int] | None
41
+ num_options: int
42
+ keep_alive: list[bytes]
43
+
44
+
45
+ # Look for the fully-linked shared library and skip any .abi3.so stubs.
46
+ _lib_paths = tuple(
47
+ p
48
+ for p in itertools.chain.from_iterable(
49
+ glob.glob(os.path.join(os.path.dirname(__file__), pattern))
50
+ for pattern in (
51
+ "profiler_plugin_c_api*.so",
52
+ "profiler_plugin_c_api*.pyd",
53
+ "profiler_plugin_c_api*.dylib",
54
+ "profiler_plugin_c_api*.dll",
55
+ )
56
+ )
57
+ if ".abi3." not in p
58
+ )
59
+
60
+ if not _lib_paths:
61
+ raise ImportError(
62
+ f"Could not find profiler_plugin_c_api.* at {os.path.dirname(__file__)}"
63
+ )
64
+
65
+ _lib = ctypes.CDLL(
66
+ sorted(_lib_paths)[0],
67
+ mode=ctypes.RTLD_LOCAL | getattr(os, "RTLD_DEEPBIND", 0),
68
+ )
69
+
70
+ _initialized_lock = threading.Lock()
71
+ _initialized = False
72
+
73
+
74
+ def _ensure_initialized() -> None:
75
+ global _initialized
76
+ if not _initialized:
77
+ with _initialized_lock:
78
+ if not _initialized:
79
+ _lib.InitializeProfiler()
80
+ _initialized = True
81
+
82
+
83
+ _lib.FreeString.argtypes = [ctypes.c_void_p]
84
+ _lib.FreeString.restype = None
85
+
86
+
87
+ def _check_error(err_ptr: int | None) -> None:
88
+ if err_ptr:
89
+ err_msg = ctypes.string_at(err_ptr).decode("utf-8")
90
+ _lib.FreeString(err_ptr)
91
+ raise RuntimeError(err_msg)
92
+
93
+
94
+ def _pack_options(options: Mapping[str, Any] | None) -> PackedOptions:
95
+ """Packs Python options dict into ctypes arrays for the C API.
96
+
97
+ Args:
98
+ options: Dictionary of options to pass to the C API.
99
+
100
+ Returns:
101
+ A PackedOptions dataclass containing ctypes arrays and keep-alive list.
102
+ """
103
+ if not options:
104
+ return PackedOptions(
105
+ keys=None,
106
+ string_vals=None,
107
+ int_vals=None,
108
+ bool_vals=None,
109
+ types=None,
110
+ num_options=0,
111
+ keep_alive=[],
112
+ )
113
+
114
+ # Filter out None values and complex types (lists, tuples, dicts).
115
+ options = {
116
+ k: v
117
+ for k, v in options.items()
118
+ if v is not None and not isinstance(v, (list, tuple, dict))
119
+ }
120
+ if not options:
121
+ return PackedOptions(
122
+ keys=None,
123
+ string_vals=None,
124
+ int_vals=None,
125
+ bool_vals=None,
126
+ types=None,
127
+ num_options=0,
128
+ keep_alive=[],
129
+ )
130
+
131
+ num_options = len(options)
132
+ keys = (ctypes.c_char_p * num_options)()
133
+ string_vals = (ctypes.c_char_p * num_options)()
134
+ int_vals = (ctypes.c_int * num_options)()
135
+ bool_vals = (ctypes.c_bool * num_options)()
136
+ types = (ctypes.c_int * num_options)()
137
+ keep_alive = []
138
+
139
+ for i, (k, v) in enumerate(options.items()):
140
+ key_bytes = k.encode("utf-8")
141
+ keep_alive.append(key_bytes)
142
+ keys[i] = key_bytes
143
+ if isinstance(v, bool):
144
+ types[i] = OptionType.BOOLEAN
145
+ bool_vals[i] = v
146
+ elif isinstance(v, int):
147
+ types[i] = OptionType.INTEGER
148
+ int_vals[i] = v
149
+ elif isinstance(v, str):
150
+ types[i] = OptionType.STRING
151
+ val_bytes = v.encode("utf-8")
152
+ keep_alive.append(val_bytes)
153
+ string_vals[i] = val_bytes
154
+ else:
155
+ raise TypeError(f"Unsupported option type for key {k!r}: {type(v)!r}")
156
+
157
+ return PackedOptions(
158
+ keys, string_vals, int_vals, bool_vals, types, num_options, keep_alive
159
+ )
160
+
161
+
162
+ _lib.Trace.argtypes = [
163
+ ctypes.c_char_p,
164
+ ctypes.c_char_p,
165
+ ctypes.c_char_p,
166
+ ctypes.c_bool,
167
+ ctypes.c_int,
168
+ ctypes.c_int,
169
+ ctypes.POINTER(ctypes.c_char_p),
170
+ ctypes.POINTER(ctypes.c_char_p),
171
+ ctypes.POINTER(ctypes.c_int),
172
+ ctypes.POINTER(ctypes.c_bool),
173
+ ctypes.POINTER(ctypes.c_int),
174
+ ctypes.c_int,
175
+ ]
176
+ _lib.Trace.restype = ctypes.c_void_p
177
+
178
+
179
+ def trace(
180
+ service_addr: str,
181
+ logdir: str,
182
+ worker_list: str,
183
+ include_dataset_ops: bool,
184
+ duration_ms: int,
185
+ num_tracing_attempts: int,
186
+ options: Mapping[str, Any] | None = None,
187
+ ) -> None:
188
+ """Traces the profiler.
189
+
190
+ Args:
191
+ service_addr: Address of the profiler service.
192
+ logdir: Directory to save the profile.
193
+ worker_list: List of workers to profile.
194
+ include_dataset_ops: Whether to include dataset ops.
195
+ duration_ms: Duration of the trace in milliseconds.
196
+ num_tracing_attempts: Number of tracing attempts.
197
+ options: Dictionary of options to pass to the C API.
198
+ """
199
+ _ensure_initialized()
200
+ packed = _pack_options(options)
201
+ err = _lib.Trace(
202
+ service_addr.encode() if service_addr else None,
203
+ logdir.encode() if logdir else None,
204
+ worker_list.encode() if worker_list else None,
205
+ include_dataset_ops,
206
+ duration_ms,
207
+ num_tracing_attempts,
208
+ packed.keys,
209
+ packed.string_vals,
210
+ packed.int_vals,
211
+ packed.bool_vals,
212
+ packed.types,
213
+ packed.num_options,
214
+ )
215
+ _check_error(err)
216
+ # Keep Python objects alive until the C API call completes.
217
+ _ = packed.keep_alive
218
+
219
+
220
+ _lib.Monitor.argtypes = [
221
+ ctypes.c_char_p,
222
+ ctypes.c_int,
223
+ ctypes.c_int,
224
+ ctypes.c_bool,
225
+ ctypes.POINTER(ctypes.c_void_p),
226
+ ]
227
+ _lib.Monitor.restype = ctypes.c_void_p
228
+
229
+
230
+ def monitor(
231
+ service_addr: str,
232
+ duration_ms: int,
233
+ monitoring_level: int,
234
+ display_timestamp: bool,
235
+ ) -> str:
236
+ """Monitors the profiler.
237
+
238
+ Args:
239
+ service_addr: Address of the profiler service.
240
+ duration_ms: Duration of the monitoring in milliseconds.
241
+ monitoring_level: Monitoring level.
242
+ display_timestamp: Whether to display timestamps.
243
+
244
+ Returns:
245
+ The monitoring results as a string.
246
+ """
247
+ _ensure_initialized()
248
+ content_ptr = ctypes.c_void_p()
249
+ err = _lib.Monitor(
250
+ service_addr.encode() if service_addr else None,
251
+ duration_ms,
252
+ monitoring_level,
253
+ display_timestamp,
254
+ ctypes.byref(content_ptr),
255
+ )
256
+ _check_error(err)
257
+ if not content_ptr:
258
+ return ""
259
+
260
+ res = ctypes.string_at(content_ptr).decode("utf-8")
261
+ _lib.FreeString(content_ptr)
262
+ return res
263
+
264
+
265
+ _lib.StartContinuousProfiling.argtypes = [
266
+ ctypes.c_char_p,
267
+ ctypes.POINTER(ctypes.c_char_p),
268
+ ctypes.POINTER(ctypes.c_char_p),
269
+ ctypes.POINTER(ctypes.c_int),
270
+ ctypes.POINTER(ctypes.c_bool),
271
+ ctypes.POINTER(ctypes.c_int),
272
+ ctypes.c_int,
273
+ ]
274
+ _lib.StartContinuousProfiling.restype = ctypes.c_void_p
275
+
276
+
277
+ def start_continuous_profiling(
278
+ service_addr: str,
279
+ options: Mapping[str, Any] | None = None,
280
+ ) -> None:
281
+ """Starts continuous profiling.
282
+
283
+ Args:
284
+ service_addr: Address of the profiler service.
285
+ options: Dictionary of options.
286
+ """
287
+ _ensure_initialized()
288
+ packed = _pack_options(options)
289
+ err = _lib.StartContinuousProfiling(
290
+ service_addr.encode() if service_addr else None,
291
+ packed.keys,
292
+ packed.string_vals,
293
+ packed.int_vals,
294
+ packed.bool_vals,
295
+ packed.types,
296
+ packed.num_options,
297
+ )
298
+ _check_error(err)
299
+ # Keep Python objects alive until the C API call completes.
300
+ _ = packed.keep_alive
301
+
302
+
303
+ _lib.StopContinuousProfiling.argtypes = [ctypes.c_char_p]
304
+ _lib.StopContinuousProfiling.restype = ctypes.c_void_p
305
+
306
+
307
+ def stop_continuous_profiling(service_addr: str) -> None:
308
+ _ensure_initialized()
309
+ err = _lib.StopContinuousProfiling(
310
+ service_addr.encode() if service_addr else None
311
+ )
312
+ _check_error(err)
313
+
314
+
315
+ _lib.GetSnapshot.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
316
+ _lib.GetSnapshot.restype = ctypes.c_void_p
317
+
318
+
319
+ def get_snapshot(service_addr: str, logdir: str) -> None:
320
+ _ensure_initialized()
321
+ err = _lib.GetSnapshot(
322
+ service_addr.encode() if service_addr else None,
323
+ logdir.encode() if logdir else None,
324
+ )
325
+ _check_error(err)
326
+
327
+
328
+ _lib.XSpaceToToolsData.argtypes = [
329
+ ctypes.POINTER(ctypes.c_char_p),
330
+ ctypes.c_size_t,
331
+ ctypes.c_char_p,
332
+ ctypes.POINTER(ctypes.c_char_p),
333
+ ctypes.POINTER(ctypes.c_char_p),
334
+ ctypes.POINTER(ctypes.c_int),
335
+ ctypes.POINTER(ctypes.c_bool),
336
+ ctypes.POINTER(ctypes.c_int),
337
+ ctypes.c_int,
338
+ ctypes.POINTER(ctypes.c_void_p),
339
+ ctypes.POINTER(ctypes.c_size_t),
340
+ ctypes.POINTER(ctypes.c_bool),
341
+ ]
342
+ _lib.XSpaceToToolsData.restype = ctypes.c_void_p
343
+
344
+
345
+ def xspace_to_tools_data(
346
+ xspace_paths: Sequence[os.PathLike[str]],
347
+ tool_name: str,
348
+ options: Mapping[str, Any] | None = None,
349
+ ) -> tuple[bytes, bool]:
350
+ """Converts XSpaces to tools data.
351
+
352
+ Args:
353
+ xspace_paths: List of XSpace paths.
354
+ tool_name: Name of the tool.
355
+ options: Dictionary of options.
356
+
357
+ Returns:
358
+ A tuple of (result_bytes, success_flag), where result_bytes is the
359
+ tools data as bytes, and success_flag is True if the conversion was
360
+ successful.
361
+ """
362
+ _ensure_initialized()
363
+ packed = _pack_options(options or {})
364
+
365
+ c_paths = (ctypes.c_char_p * len(xspace_paths))()
366
+ paths_keep_alive = [str(p).encode("utf-8") for p in xspace_paths]
367
+ for i, path_bytes in enumerate(paths_keep_alive):
368
+ c_paths[i] = path_bytes
369
+
370
+ result_ptr = ctypes.c_void_p()
371
+ result_size = ctypes.c_size_t(0)
372
+ success = ctypes.c_bool(False)
373
+
374
+ err = _lib.XSpaceToToolsData(
375
+ c_paths,
376
+ len(xspace_paths),
377
+ tool_name.encode() if tool_name else None,
378
+ packed.keys,
379
+ packed.string_vals,
380
+ packed.int_vals,
381
+ packed.bool_vals,
382
+ packed.types,
383
+ packed.num_options,
384
+ ctypes.byref(result_ptr),
385
+ ctypes.byref(result_size),
386
+ ctypes.byref(success),
387
+ )
388
+ _check_error(err)
389
+ # Keep Python objects alive until the C API call completes.
390
+ _ = packed.keep_alive
391
+ _ = paths_keep_alive
392
+
393
+ if not result_ptr:
394
+ return b"", success.value
395
+
396
+ res_bytes = ctypes.string_at(result_ptr, result_size.value)
397
+ _lib.FreeString(result_ptr)
398
+ return (res_bytes, success.value)
399
+
400
+
401
+ _lib.XSpaceToToolsDataFromByteString.argtypes = [
402
+ ctypes.POINTER(ctypes.c_char_p),
403
+ ctypes.POINTER(ctypes.c_size_t),
404
+ ctypes.POINTER(ctypes.c_char_p),
405
+ ctypes.c_size_t,
406
+ ctypes.c_char_p,
407
+ ctypes.POINTER(ctypes.c_char_p),
408
+ ctypes.POINTER(ctypes.c_char_p),
409
+ ctypes.POINTER(ctypes.c_int),
410
+ ctypes.POINTER(ctypes.c_bool),
411
+ ctypes.POINTER(ctypes.c_int),
412
+ ctypes.c_int,
413
+ ctypes.POINTER(ctypes.c_void_p),
414
+ ctypes.POINTER(ctypes.c_size_t),
415
+ ctypes.POINTER(ctypes.c_bool),
416
+ ]
417
+ _lib.XSpaceToToolsDataFromByteString.restype = ctypes.c_void_p
418
+
419
+
420
+ def xspace_to_tools_data_from_byte_string(
421
+ xspace_strings: Sequence[bytes],
422
+ filenames_list: Sequence[str],
423
+ tool_name: str,
424
+ options: Mapping[str, Any] | None = None,
425
+ ) -> tuple[bytes, bool]:
426
+ """Converts XSpace byte strings to tools data.
427
+
428
+ Args:
429
+ xspace_strings: List of XSpace byte strings.
430
+ filenames_list: List of corresponding filenames.
431
+ tool_name: Name of the tool.
432
+ options: Dictionary of options.
433
+
434
+ Returns:
435
+ A tuple of (result_bytes, success_flag).
436
+ """
437
+ _ensure_initialized()
438
+ packed = _pack_options(options or {})
439
+
440
+ num_xspaces = len(xspace_strings)
441
+ if len(filenames_list) != num_xspaces:
442
+ raise ValueError("Lengths of xspace_strings and filenames_list must match")
443
+
444
+ c_strings = (ctypes.c_char_p * num_xspaces)()
445
+ c_sizes = (ctypes.c_size_t * num_xspaces)()
446
+ c_paths = (ctypes.c_char_p * num_xspaces)()
447
+ paths_keep_alive = []
448
+
449
+ for i, (string, path) in enumerate(zip(xspace_strings, filenames_list)):
450
+ c_strings[i] = string
451
+ c_sizes[i] = len(string)
452
+ path_bytes = path.encode("utf-8")
453
+ paths_keep_alive.append(path_bytes)
454
+ c_paths[i] = path_bytes
455
+
456
+ result_ptr = ctypes.c_void_p()
457
+ result_size = ctypes.c_size_t(0)
458
+ success = ctypes.c_bool(False)
459
+
460
+ err = _lib.XSpaceToToolsDataFromByteString(
461
+ c_strings,
462
+ c_sizes,
463
+ c_paths,
464
+ num_xspaces,
465
+ tool_name.encode() if tool_name else None,
466
+ packed.keys,
467
+ packed.string_vals,
468
+ packed.int_vals,
469
+ packed.bool_vals,
470
+ packed.types,
471
+ packed.num_options,
472
+ ctypes.byref(result_ptr),
473
+ ctypes.byref(result_size),
474
+ ctypes.byref(success),
475
+ )
476
+ _check_error(err)
477
+ # Keep Python objects alive until the C API call completes.
478
+ _ = packed.keep_alive
479
+ _ = paths_keep_alive
480
+
481
+ if not result_ptr:
482
+ return b"", success.value
483
+
484
+ res_bytes = ctypes.string_at(result_ptr, result_size.value)
485
+ _lib.FreeString(result_ptr)
486
+ return (res_bytes, success.value)
487
+
488
+
489
+ _lib.StartGrpcServer.argtypes = [ctypes.c_int, ctypes.c_int]
490
+ _lib.StartGrpcServer.restype = None
491
+
492
+
493
+ def start_grpc_server(port: int, max_concurrent_requests: int) -> None:
494
+ _ensure_initialized()
495
+ _lib.StartGrpcServer(port, max_concurrent_requests)
496
+
497
+
498
+ _lib.InitializeStubs.argtypes = [ctypes.c_char_p]
499
+ _lib.InitializeStubs.restype = None
500
+
501
+
502
+ def initialize_stubs(worker_service_addresses: str) -> None:
503
+ _ensure_initialized()
504
+ _lib.InitializeStubs(
505
+ worker_service_addresses.encode() if worker_service_addresses else None
506
+ )