dcmspec 0.2.3__tar.gz → 0.3.0__tar.gz
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.
- {dcmspec-0.2.3 → dcmspec-0.3.0}/CHANGELOG.md +22 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/PKG-INFO +5 -3
- {dcmspec-0.2.3 → dcmspec-0.3.0}/README.md +2 -2
- {dcmspec-0.2.3 → dcmspec-0.3.0}/pyproject.toml +3 -1
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/.DS_Store +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/apps/cli/iodattributes.py +28 -5
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/apps/cli/modattributes.py +36 -13
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/dom_table_spec_parser.py +61 -28
- dcmspec-0.3.0/src/dcmspec/iod_spec_printer.py +254 -0
- dcmspec-0.3.0/src/dcmspec/spec_printer.py +414 -0
- dcmspec-0.2.3/src/dcmspec/iod_spec_printer.py +0 -59
- dcmspec-0.2.3/src/dcmspec/spec_printer.py +0 -131
- {dcmspec-0.2.3 → dcmspec-0.3.0}/LICENSE +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/__init__.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/apps/.DS_Store +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/apps/__init__.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/apps/cli/__init__.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/apps/cli/dataelements.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/apps/cli/iodmodules.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/apps/cli/tdwiicontent.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/apps/cli/uidvalues.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/apps/cli/upsdimseattributes.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/apps/cli/upsioddimseattributes.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/apps/ui/iod_explorer/README.md +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/apps/ui/iod_explorer/__init__.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/apps/ui/iod_explorer/config/README.md +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/apps/ui/iod_explorer/config/iod_explorer_config.json +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/apps/ui/iod_explorer/config/iod_explorer_config_debug.json +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/apps/ui/iod_explorer/config/iod_explorer_config_example.json +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/apps/ui/iod_explorer/config/iod_explorer_config_minimal_logging.json +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/apps/ui/iod_explorer/iod_explorer.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/config.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/csv_table_spec_parser.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/doc_handler.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/dom_utils.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/iod_spec_builder.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/json_spec_store.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/module_registry.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/pdf_doc_handler.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/progress.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/service_attribute_defaults.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/service_attribute_model.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/spec_factory.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/spec_merger.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/spec_model.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/spec_parser.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/spec_store.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/ups_xhtml_doc_handler.py +0 -0
- {dcmspec-0.2.3 → dcmspec-0.3.0}/src/dcmspec/xhtml_doc_handler.py +0 -0
|
@@ -2,6 +2,28 @@
|
|
|
2
2
|
|
|
3
3
|
These release notes summarize key changes, improvements, and breaking updates for each version of **dcmspec**.
|
|
4
4
|
|
|
5
|
+
## [0.3.0] - 2025-11-27
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- CSV output mode in `SpecPrinter` via `print_csv` method
|
|
10
|
+
- Excel OOXML output mode in `SpecPrinter` via `print_xlsx` method
|
|
11
|
+
- Optional `output` parameter in `SpecPrinter` for writing to files
|
|
12
|
+
- Optional `column_width` parameter in `print_table` and `print_xlsx`
|
|
13
|
+
- `--print-mode` option in `modattributes` CLI for CSV and OOXML output
|
|
14
|
+
- `--output` option in `modattributes` CLI for directing output to files
|
|
15
|
+
|
|
16
|
+
### Changed
|
|
17
|
+
|
|
18
|
+
- Switch PyPI version badge in `README` from `badge.fury.io` to `shields.io` for faster updates
|
|
19
|
+
- Update modattributes CLI example for CSV and XLSX output
|
|
20
|
+
- Improved nesting level color schemes for consistency and better contrast and readability.
|
|
21
|
+
|
|
22
|
+
### Fixed
|
|
23
|
+
|
|
24
|
+
- Correct handling of `include_table` names in `DOMTableSpecParser`
|
|
25
|
+
- Correct handling of empty node attributes in `SpecPrinter`
|
|
26
|
+
|
|
5
27
|
## [0.2.3] - 2025-09-29
|
|
6
28
|
|
|
7
29
|
### Fixed
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: dcmspec
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Toolkit for extracting, parsing, and processing DICOM specifications.
|
|
5
5
|
License: Apache-2.0
|
|
6
6
|
License-File: LICENSE
|
|
@@ -25,8 +25,10 @@ Provides-Extra: pdf
|
|
|
25
25
|
Requires-Dist: anytree (>=2.13.0,<3.0.0)
|
|
26
26
|
Requires-Dist: bs4 (>=0.0.2,<0.0.3)
|
|
27
27
|
Requires-Dist: camelot-py (>=1.0.0,<2.0.0) ; extra == "pdf"
|
|
28
|
+
Requires-Dist: html2text (>=2025.4.15,<2026.0.0)
|
|
28
29
|
Requires-Dist: lxml (>=5.4.0,<6.0.0)
|
|
29
30
|
Requires-Dist: opencv-python-headless (>=4.12.0.88,<5.0.0) ; extra == "pdf"
|
|
31
|
+
Requires-Dist: openpyxl (>=3.1.5,<4.0.0)
|
|
30
32
|
Requires-Dist: openpyxl (>=3.1.5,<4.0.0) ; extra == "pdf"
|
|
31
33
|
Requires-Dist: pandas (>=2.3.1,<3.0.0) ; extra == "pdf"
|
|
32
34
|
Requires-Dist: pdfplumber (>=0.11.7,<0.12.0) ; extra == "pdf"
|
|
@@ -43,9 +45,9 @@ Project-URL: Source, https://github.com/dwikler/dcmspec
|
|
|
43
45
|
Description-Content-Type: text/markdown
|
|
44
46
|
|
|
45
47
|
[](https://github.com/dwikler/dcmspec/actions/workflows/test.yml)
|
|
46
|
-
[](https://pypi.org/project/dcmspec/)
|
|
47
49
|
[](https://pypi.org/project/dcmspec/)
|
|
48
|
-
[](https://doi.org/10.5281/zenodo.17742287)
|
|
49
51
|
|
|
50
52
|
# dcmspec
|
|
51
53
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
[](https://github.com/dwikler/dcmspec/actions/workflows/test.yml)
|
|
2
|
-
[](https://pypi.org/project/dcmspec/)
|
|
3
3
|
[](https://pypi.org/project/dcmspec/)
|
|
4
|
-
[](https://doi.org/10.5281/zenodo.17742287)
|
|
5
5
|
|
|
6
6
|
# dcmspec
|
|
7
7
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "dcmspec"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.3.0"
|
|
4
4
|
description = "Toolkit for extracting, parsing, and processing DICOM specifications."
|
|
5
5
|
authors = [{ name = "David Wikler", email = "david.wikler@ulb.be" }]
|
|
6
6
|
license = { text = "Apache-2.0" }
|
|
@@ -29,6 +29,8 @@ dependencies = [
|
|
|
29
29
|
"requests (>=2.32.3,<3.0.0)",
|
|
30
30
|
"lxml (>=5.4.0,<6.0.0)",
|
|
31
31
|
"rich (>=14.0.0,<15.0.0)",
|
|
32
|
+
"html2text (>=2025.4.15,<2026.0.0)",
|
|
33
|
+
"openpyxl (>=3.1.5,<4.0.0)",
|
|
32
34
|
]
|
|
33
35
|
|
|
34
36
|
[project.urls]
|
|
Binary file
|
|
@@ -58,12 +58,25 @@ def main():
|
|
|
58
58
|
parser.add_argument("--config", help="Path to the configuration file")
|
|
59
59
|
parser.add_argument(
|
|
60
60
|
"--print-mode",
|
|
61
|
-
choices=["table", "tree", "none"],
|
|
61
|
+
choices=["table", "tree", "csv", "xlsx", "none"],
|
|
62
62
|
default="table",
|
|
63
|
-
help="Print as 'table' (default), 'tree', or 'none' to skip printing"
|
|
63
|
+
help="Print as 'table' (default), 'tree', 'csv', 'xlsx' (requires --output), or 'none' to skip printing"
|
|
64
|
+
)
|
|
65
|
+
parser.add_argument(
|
|
66
|
+
"--no-color",
|
|
67
|
+
action="store_true",
|
|
68
|
+
help="Disable colorized output (default: color enabled for terminal, disabled for file output)"
|
|
69
|
+
)
|
|
70
|
+
parser.add_argument(
|
|
71
|
+
"--output",
|
|
72
|
+
type=str,
|
|
73
|
+
help="Path to output file. If not specified (and not xlsx), prints to stdout."
|
|
64
74
|
)
|
|
65
75
|
args = parser.parse_args()
|
|
66
76
|
|
|
77
|
+
if args.print_mode == "xlsx" and not args.output:
|
|
78
|
+
parser.error("--output is required when --print-mode xlsx")
|
|
79
|
+
|
|
67
80
|
cache_file_name = "Part3.xhtml"
|
|
68
81
|
model_file_name = f"Part3_{args.table}_expanded.json"
|
|
69
82
|
table_id = args.table
|
|
@@ -114,11 +127,21 @@ def main():
|
|
|
114
127
|
)
|
|
115
128
|
|
|
116
129
|
# Print the model
|
|
117
|
-
printer = IODSpecPrinter(model)
|
|
130
|
+
printer = IODSpecPrinter(model, output=getattr(args, "output", None))
|
|
131
|
+
|
|
132
|
+
# Only disable color if --no-color is set; SpecPrinter disables color for file outputs automatically
|
|
133
|
+
use_color = not args.no_color
|
|
134
|
+
|
|
118
135
|
if args.print_mode == "tree":
|
|
119
|
-
printer.print_tree(
|
|
136
|
+
printer.print_tree(
|
|
137
|
+
attr_names=["elem_tag", "elem_type", "elem_name"], attr_widths=[11, 2, 100], colorize=use_color
|
|
138
|
+
)
|
|
120
139
|
elif args.print_mode == "table":
|
|
121
|
-
printer.print_table(colorize=
|
|
140
|
+
printer.print_table(colorize=use_color, column_widths=[30, 11, 4, 60])
|
|
141
|
+
elif args.print_mode == "csv":
|
|
142
|
+
printer.print_csv(colorize=use_color)
|
|
143
|
+
elif args.print_mode == "xlsx":
|
|
144
|
+
printer.print_xlsx(column_widths=[60, 16, 10, 100], colorize=use_color)
|
|
122
145
|
# else: do not print anything if print_mode == "none"
|
|
123
146
|
|
|
124
147
|
if __name__ == "__main__":
|
|
@@ -4,7 +4,7 @@ Features:
|
|
|
4
4
|
- Download and parse DICOM Module Attributes tables from Part 3 of the DICOM standard.
|
|
5
5
|
- Optionally merge additional information (VR, VM, Keyword, Status) from Part 6.
|
|
6
6
|
- Cache the resulting model as a JSON file for future runs and as a structured representation of the standard.
|
|
7
|
-
- Print the resulting model as a table or
|
|
7
|
+
- Print the resulting model as a table, tree, csv, or xlsx.
|
|
8
8
|
- Supports caching, configuration files, and command-line options for flexible workflows.
|
|
9
9
|
|
|
10
10
|
Usage:
|
|
@@ -113,12 +113,12 @@ def main():
|
|
|
113
113
|
|
|
114
114
|
The tool parses the specified Module Attributes table to extract all attributes, tags, types,
|
|
115
115
|
and descriptions for the module. Optionally, it can merge in VR, VM, Keyword, or Status information
|
|
116
|
-
from Part 6. The output can be printed as a table or
|
|
116
|
+
from Part 6. The output can be printed as a table, tree, csv, or xlsx (xlsx requires --output).
|
|
117
117
|
|
|
118
118
|
The resulting model is cached as a JSON file. The primary purpose of this cache file is to provide
|
|
119
|
-
a structured, machine-readable representation of the module's attributes, which can be used for
|
|
120
|
-
or integration in other tools. As a secondary benefit, the cache file is also used
|
|
121
|
-
of the CLI scripts.
|
|
119
|
+
a structured, machine-readable representation of the module's attributes, which can be used for
|
|
120
|
+
further processing or integration in other tools. As a secondary benefit, the cache file is also used
|
|
121
|
+
to speed up subsequent runs of the CLI scripts.
|
|
122
122
|
|
|
123
123
|
Usage:
|
|
124
124
|
poetry run python -m src.dcmspec.apps.cli.modattributes <table_id> [options]
|
|
@@ -129,14 +129,17 @@ def main():
|
|
|
129
129
|
--include-depth (int): Depth to which included tables should be parsed (default: unlimited).
|
|
130
130
|
--force-parse: Force reparsing of the DOM and regeneration of the JSON model.
|
|
131
131
|
--force-download: Force download of the input file and regeneration of the model.
|
|
132
|
-
--print-mode (str): Print as 'table' (default), 'tree', or 'none' to skip printing.
|
|
132
|
+
--print-mode (str): Print as 'table' (default), 'tree', 'csv', 'xlsx', or 'none' to skip printing.
|
|
133
|
+
'xlsx' requires --output.
|
|
134
|
+
--output (str): Path to output file. If not specified (and not xlsx), prints to stdout.
|
|
133
135
|
--add-part6 (list): Specification(s) to merge from Part 6 (e.g., --add-part6 VR VM).
|
|
134
136
|
--force-update: Force update of the specifications merged from part 6, even if cached.
|
|
135
137
|
-d, --debug: Enable debug logging to the console.
|
|
136
138
|
-v, --verbose: Enable verbose (info-level) logging to the console.
|
|
137
139
|
|
|
138
|
-
|
|
140
|
+
Examples:
|
|
139
141
|
poetry run python -m src.dcmspec.apps.cli.modattributes table_C.7-1 --add-part6 VR VM
|
|
142
|
+
poetry run python -m src.dcmspec.apps.cli.modattributes table_C.7-1 --print-mode xlsx --output module.xlsx
|
|
140
143
|
|
|
141
144
|
"""
|
|
142
145
|
# Parse command-line arguments
|
|
@@ -164,9 +167,19 @@ def main():
|
|
|
164
167
|
)
|
|
165
168
|
parser.add_argument(
|
|
166
169
|
"--print-mode",
|
|
167
|
-
choices=["table", "tree", "none"],
|
|
170
|
+
choices=["table", "tree", "csv", "xlsx", "none"],
|
|
168
171
|
default="table",
|
|
169
|
-
help="Print as 'table' (default), 'tree', or 'none' to skip printing"
|
|
172
|
+
help="Print as 'table' (default), 'tree', 'csv', 'xlsx' (requires --output), or 'none' to skip printing"
|
|
173
|
+
)
|
|
174
|
+
parser.add_argument(
|
|
175
|
+
"--no-color",
|
|
176
|
+
action="store_true",
|
|
177
|
+
help="Disable colorized output (default: color enabled for terminal, disabled for file output)"
|
|
178
|
+
)
|
|
179
|
+
parser.add_argument(
|
|
180
|
+
"--output",
|
|
181
|
+
type=str,
|
|
182
|
+
help="Path to output file. If not specified (and not xlsx), prints to stdout."
|
|
170
183
|
)
|
|
171
184
|
parser.add_argument(
|
|
172
185
|
"--add-part6",
|
|
@@ -189,9 +202,12 @@ def main():
|
|
|
189
202
|
action="store_true",
|
|
190
203
|
help="Enable verbose (info-level) logging to the console"
|
|
191
204
|
)
|
|
192
|
-
|
|
205
|
+
|
|
193
206
|
args = parser.parse_args()
|
|
194
207
|
|
|
208
|
+
if args.print_mode == "xlsx" and not args.output:
|
|
209
|
+
parser.error("--output is required when --print-mode xlsx")
|
|
210
|
+
|
|
195
211
|
# Set up logger
|
|
196
212
|
logger = logging.getLogger("modattributes")
|
|
197
213
|
handler = logging.StreamHandler()
|
|
@@ -254,11 +270,18 @@ def main():
|
|
|
254
270
|
model = module_model
|
|
255
271
|
|
|
256
272
|
logger.debug("Model ready for printing/output")
|
|
257
|
-
printer = SpecPrinter(model)
|
|
273
|
+
printer = SpecPrinter(model, output=args.output)
|
|
274
|
+
|
|
275
|
+
# Only disable color if --no-color is set; SpecPrinter disables color for file outputs automatically
|
|
276
|
+
use_color = not args.no_color
|
|
258
277
|
if args.print_mode == "tree":
|
|
259
|
-
printer.print_tree(colorize=
|
|
278
|
+
printer.print_tree(attr_names=["elem_tag", "elem_type", "elem_name"], attr_widths=[11, 2, 100], colorize=use_color)
|
|
260
279
|
elif args.print_mode == "table":
|
|
261
|
-
printer.print_table(colorize=
|
|
280
|
+
printer.print_table(colorize=use_color, column_widths=[30, 11, 4, 60])
|
|
281
|
+
elif args.print_mode == "csv":
|
|
282
|
+
printer.print_csv(colorize=use_color)
|
|
283
|
+
elif args.print_mode == "xlsx":
|
|
284
|
+
printer.print_xlsx(column_widths=[60, 16, 10, 100], colorize=use_color)
|
|
262
285
|
# else: do not print anything if print_mode == "none"
|
|
263
286
|
|
|
264
287
|
if __name__ == "__main__":
|
|
@@ -3,15 +3,18 @@
|
|
|
3
3
|
Provides the DOMSpecParser class for parsing DICOM specification tables from XHTML documents,
|
|
4
4
|
converting them into structured in-memory representations using anytree.
|
|
5
5
|
"""
|
|
6
|
+
|
|
6
7
|
from contextlib import contextmanager
|
|
7
8
|
import re
|
|
8
9
|
import unicodedata
|
|
10
|
+
from typing import Any, Dict, Optional, Union
|
|
11
|
+
|
|
9
12
|
from unidecode import unidecode
|
|
10
13
|
from anytree import Node
|
|
11
14
|
from bs4 import BeautifulSoup, Tag
|
|
12
|
-
|
|
13
|
-
from dcmspec.spec_parser import SpecParser
|
|
15
|
+
import html2text
|
|
14
16
|
|
|
17
|
+
from dcmspec.spec_parser import SpecParser
|
|
15
18
|
from dcmspec.dom_utils import DOMUtils
|
|
16
19
|
from dcmspec.progress import Progress, ProgressObserver, ProgressStatus, calculate_percent
|
|
17
20
|
|
|
@@ -506,6 +509,7 @@ class DOMTableSpecParser(SpecParser):
|
|
|
506
509
|
|
|
507
510
|
return logical_cells, logical_col_idx, physical_col_idx
|
|
508
511
|
|
|
512
|
+
|
|
509
513
|
def _extract_cell_value(
|
|
510
514
|
self,
|
|
511
515
|
cell: Tag,
|
|
@@ -518,11 +522,27 @@ class DOMTableSpecParser(SpecParser):
|
|
|
518
522
|
if unformatted_list and logical_col_idx < len(unformatted_list)
|
|
519
523
|
else True
|
|
520
524
|
)
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
525
|
+
|
|
526
|
+
# Guard clause: if formatted HTML is required, return content as-is
|
|
527
|
+
if not use_unformatted:
|
|
528
|
+
# Keep original HTML content
|
|
524
529
|
return self._clean_extracted_text(cell.decode_contents())
|
|
525
530
|
|
|
531
|
+
# Use html2text for better readability of unformatted text extraction
|
|
532
|
+
converter = self._create_html2text_converter()
|
|
533
|
+
raw_text = converter.handle(str(cell))
|
|
534
|
+
return self._clean_extracted_text(raw_text)
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def _create_html2text_converter(self) -> html2text.HTML2Text:
|
|
538
|
+
"""Create and configure an html2text converter for consistent text extraction."""
|
|
539
|
+
converter = html2text.HTML2Text()
|
|
540
|
+
converter.ignore_links = True # Remove URLs
|
|
541
|
+
converter.ignore_images = True # Remove image references
|
|
542
|
+
converter.ignore_emphasis = True # Remove Markdown emphasis
|
|
543
|
+
converter.body_width = 0 # Disable word wrapping
|
|
544
|
+
return converter
|
|
545
|
+
|
|
526
546
|
def _update_rowspan_trackers(
|
|
527
547
|
self,
|
|
528
548
|
physical_col_idx: int,
|
|
@@ -781,15 +801,7 @@ class DOMTableSpecParser(SpecParser):
|
|
|
781
801
|
return header
|
|
782
802
|
|
|
783
803
|
def _clean_extracted_text(self, text: str) -> str:
|
|
784
|
-
"""Clean extracted text using Unicode normalization and regex.
|
|
785
|
-
|
|
786
|
-
Args:
|
|
787
|
-
text (str): The text to be cleaned.
|
|
788
|
-
|
|
789
|
-
Returns:
|
|
790
|
-
str: The cleaned text.
|
|
791
|
-
|
|
792
|
-
"""
|
|
804
|
+
"""Clean extracted text using Unicode normalization and regex."""
|
|
793
805
|
# Normalize unicode characters to compatibility form
|
|
794
806
|
cleaned = unicodedata.normalize('NFKC', text)
|
|
795
807
|
|
|
@@ -805,27 +817,48 @@ class DOMTableSpecParser(SpecParser):
|
|
|
805
817
|
# Remove stray  character
|
|
806
818
|
cleaned = cleaned.replace('\u00c2', '')
|
|
807
819
|
|
|
820
|
+
# Collapse multiple newlines (including those separated by spaces/tabs) into a single newline
|
|
821
|
+
cleaned = re.sub(r'(\n\s*){2,}', '\n', cleaned)
|
|
822
|
+
|
|
808
823
|
return cleaned.strip()
|
|
809
824
|
|
|
810
|
-
|
|
811
|
-
|
|
825
|
+
@staticmethod
|
|
826
|
+
def _sanitize_string(input_string: str) -> str:
|
|
827
|
+
r"""Sanitize a string to make it safe for use as a node attribute name.
|
|
812
828
|
|
|
813
|
-
|
|
814
|
-
-
|
|
815
|
-
-
|
|
829
|
+
Transformations applied:
|
|
830
|
+
- Convert to lowercase.
|
|
831
|
+
- Transliterate non-ASCII characters to ASCII.
|
|
832
|
+
- Replace spaces, slashes, newlines, and dots with underscores ("_").
|
|
833
|
+
- Replace parentheses with dashes ("-").
|
|
834
|
+
- Remove all characters except letters, digits, underscores, and dashes.
|
|
835
|
+
- Collapse multiple consecutive underscores into a single underscore.
|
|
836
|
+
- Remove leading and trailing underscores for cleanliness.
|
|
837
|
+
- Return a default name if the result is empty after sanitization.
|
|
816
838
|
|
|
817
839
|
Args:
|
|
818
|
-
input_string (str): The string to
|
|
840
|
+
input_string (str): The original string to sanitize.
|
|
819
841
|
|
|
820
842
|
Returns:
|
|
821
|
-
str:
|
|
843
|
+
str: A sanitized version of the input string, suitable for use as an identifier.
|
|
844
|
+
or "unnamed_node" if sanitization results in an empty string.
|
|
845
|
+
|
|
846
|
+
Example:
|
|
847
|
+
>>> DOMTableSpecParser._sanitize_string(
|
|
848
|
+
'>>Include\\nTable C.36.2.2.19-1 "RT Beam Limiting Device Definition Macro Attributes"\\n.'
|
|
849
|
+
)
|
|
850
|
+
'include_table_c_36_2_2_19-1_rt_beam_limiting_device_definition_macro_attributes'
|
|
851
|
+
>>> DOMTableSpecParser._sanitize_string('...')
|
|
852
|
+
'unnamed_node'
|
|
822
853
|
|
|
823
854
|
"""
|
|
824
|
-
# Normalize the string to NFC form and transliterate to ASCII
|
|
825
855
|
normalized_str = unidecode(input_string.lower())
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
856
|
+
sanitized = re.sub(r"[ /\n\\.]", "_", normalized_str) # spaces, slashes, newlines, dots → _
|
|
857
|
+
sanitized = re.sub(r"[()]", "-", sanitized) # parentheses → -
|
|
858
|
+
sanitized = re.sub(r"[^a-z0-9_-]", "", sanitized) # remove other chars
|
|
859
|
+
sanitized = re.sub(r"_+", "_", sanitized) # collapse multiple underscores
|
|
860
|
+
sanitized = sanitized.strip("_") # remove leading/trailing underscores
|
|
861
|
+
|
|
862
|
+
# Fallback to default name if sanitization resulted in empty string
|
|
863
|
+
return sanitized or "unnamed_node"
|
|
864
|
+
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""Printer class for DICOM IOD specification model in dcmspec.
|
|
2
|
+
|
|
3
|
+
Provides the SpecPrinter class for printing DICOM IOD specification models (SpecModel)
|
|
4
|
+
to standard output, either as a hierarchical tree or as a flat table, using rich formatting.
|
|
5
|
+
"""
|
|
6
|
+
import re
|
|
7
|
+
from typing import Generator, List, Optional, Tuple
|
|
8
|
+
|
|
9
|
+
from anytree import PreOrderIter
|
|
10
|
+
from anytree import RenderTree
|
|
11
|
+
from rich.table import Table, box
|
|
12
|
+
from rich.text import Text
|
|
13
|
+
|
|
14
|
+
from dcmspec.spec_printer import LEVEL_COLORS, SPECIAL_COLORS, SpecPrinter
|
|
15
|
+
|
|
16
|
+
class IODSpecPrinter(SpecPrinter):
|
|
17
|
+
"""Printer for DICOM IOD specification models with mixed node types.
|
|
18
|
+
|
|
19
|
+
Overrides print_table to display IOD Modules nodes as a one-cell title row (spanning all columns)
|
|
20
|
+
The table columns are those of the Module Attributes nodes.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def print_tree(
|
|
24
|
+
self,
|
|
25
|
+
attr_names=None,
|
|
26
|
+
attr_widths=None,
|
|
27
|
+
colorize: bool = False,
|
|
28
|
+
) -> None:
|
|
29
|
+
"""Print the specification model as a hierarchical tree to the console or file.
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
attr_names (Optional[Union[str, list[str]]]): Attribute name(s) to display for each node.
|
|
33
|
+
attr_widths (Optional[list[int]]): List of widths for each attribute in attr_names.
|
|
34
|
+
colorize (bool): Whether to colorize the output by node depth. Ignored when writing to file.
|
|
35
|
+
|
|
36
|
+
Returns:
|
|
37
|
+
None
|
|
38
|
+
|
|
39
|
+
"""
|
|
40
|
+
if self.output:
|
|
41
|
+
colorize = False
|
|
42
|
+
|
|
43
|
+
for pre, fill, node in RenderTree(self.model.content):
|
|
44
|
+
if node.name == "content":
|
|
45
|
+
continue
|
|
46
|
+
|
|
47
|
+
if hasattr(node, "module"):
|
|
48
|
+
# Module title row: always use title color if colorize
|
|
49
|
+
iod_title = getattr(node, "module", getattr(node, "name", ""))
|
|
50
|
+
iod_usage = getattr(node, "usage", "")
|
|
51
|
+
iod_title_text = f"{iod_title} Module ({iod_usage})" if iod_usage else iod_title
|
|
52
|
+
node_text = Text(iod_title_text, style=SPECIAL_COLORS["title"] if colorize else None)
|
|
53
|
+
else:
|
|
54
|
+
attr_text = self._format_tree_row(node, attr_names, attr_widths)
|
|
55
|
+
row_style = self._get_tree_row_style(node, colorize)
|
|
56
|
+
node_text = Text(attr_text, style=row_style)
|
|
57
|
+
self.console.print(Text(pre) + node_text)
|
|
58
|
+
|
|
59
|
+
if self.console.file:
|
|
60
|
+
self.console.file.flush()
|
|
61
|
+
|
|
62
|
+
def print_table(self, column_widths=None, colorize: bool = False) -> None:
|
|
63
|
+
"""Print the specification model as a flat table with module title rows.
|
|
64
|
+
|
|
65
|
+
Args:
|
|
66
|
+
column_widths (Optional[List[int]]): List of widths for each column's content.
|
|
67
|
+
These widths do not include borders or padding added by Rich.
|
|
68
|
+
If provided, each column will be set to the specified content width.
|
|
69
|
+
If None, all columns default to width 20.
|
|
70
|
+
If the list is shorter than the number of columns, remaining columns default to width 20.
|
|
71
|
+
|
|
72
|
+
colorize (bool): Whether to colorize the output by node depth.
|
|
73
|
+
|
|
74
|
+
"""
|
|
75
|
+
# Disable colorization if writing to file
|
|
76
|
+
if self.output:
|
|
77
|
+
colorize = False
|
|
78
|
+
|
|
79
|
+
table = Table(show_header=True, header_style="bold magenta", show_lines=True, box=box.ASCII_DOUBLE_HEAD)
|
|
80
|
+
|
|
81
|
+
attr_headers = list(self.model.metadata.header)
|
|
82
|
+
for i, header in enumerate(attr_headers):
|
|
83
|
+
width = column_widths[i] if column_widths and i < len(column_widths) else 20
|
|
84
|
+
table.add_column(header, width=width)
|
|
85
|
+
|
|
86
|
+
for row, row_style, _ in self._iterate_rows_iod(colorize):
|
|
87
|
+
table.add_row(*row, style=row_style)
|
|
88
|
+
|
|
89
|
+
self.console.print(table)
|
|
90
|
+
|
|
91
|
+
if self.console.file:
|
|
92
|
+
self.console.file.flush() # Ensure data is written immediately
|
|
93
|
+
|
|
94
|
+
def print_csv(self, colorize: bool = False) -> None:
|
|
95
|
+
"""Print the specification model as CSV to the console or file, with module title rows.
|
|
96
|
+
|
|
97
|
+
Traverses the content tree and prints each node's attributes in CSV format,
|
|
98
|
+
with column headers from the metadata node. Optionally colorizes rows.
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
colorize (bool): Whether to colorize the output by node depth. Ignored when writing to file.
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
None
|
|
105
|
+
|
|
106
|
+
"""
|
|
107
|
+
# Disable colorization if writing to file
|
|
108
|
+
if self.output:
|
|
109
|
+
colorize = False
|
|
110
|
+
|
|
111
|
+
# Print CSV header
|
|
112
|
+
header_row = ",".join(f'"{h}"' for h in self.model.metadata.header)
|
|
113
|
+
self.console.print(header_row)
|
|
114
|
+
|
|
115
|
+
# Add data rows (including module title rows)
|
|
116
|
+
for row, row_style, _ in self._iterate_rows_iod(colorize):
|
|
117
|
+
# Escape quotes inside each field by doubling them, then wrap in quotes
|
|
118
|
+
csv_row = ",".join(
|
|
119
|
+
f'"{("" if cell is None else str(cell)).replace(chr(34), chr(34) + chr(34))}"'
|
|
120
|
+
for cell in row
|
|
121
|
+
)
|
|
122
|
+
self.console.print(csv_row, style=row_style)
|
|
123
|
+
|
|
124
|
+
if self.console.file:
|
|
125
|
+
self.console.file.flush()
|
|
126
|
+
|
|
127
|
+
def print_xlsx(self, column_widths: Optional[list] = None, colorize: bool = False) -> None:
|
|
128
|
+
"""Print the specification model to an OOXML format Excel (.xlsx) file.
|
|
129
|
+
|
|
130
|
+
Traverses the content tree and writes each node's attributes into an Excel sheet,
|
|
131
|
+
with column headers from the metadata node. Handles newlines and applies background
|
|
132
|
+
colorization using the same color scheme as console output (LEVEL_COLORS and SPECIAL_COLORS).
|
|
133
|
+
Each module in the IOD is written to a separate worksheet, named after the module, and attribute rows
|
|
134
|
+
for each module are written to their corresponding worksheet.
|
|
135
|
+
|
|
136
|
+
Args:
|
|
137
|
+
column_widths (list): Optional list of column widths for Excel columns.
|
|
138
|
+
colorize (bool): Whether to apply color styling to cell backgrounds.
|
|
139
|
+
|
|
140
|
+
Returns:
|
|
141
|
+
None
|
|
142
|
+
|
|
143
|
+
"""
|
|
144
|
+
if not self.output:
|
|
145
|
+
raise ValueError("Output file path must be specified when constructing SpecPrinter for print_xlsx).")
|
|
146
|
+
|
|
147
|
+
header_style, data_style = self._create_styles()
|
|
148
|
+
wb = self._setup_workbook()
|
|
149
|
+
ws = None
|
|
150
|
+
current_module = None
|
|
151
|
+
rows_for_ws = []
|
|
152
|
+
|
|
153
|
+
def flush_ws():
|
|
154
|
+
if ws and rows_for_ws:
|
|
155
|
+
self._write_data_rows(ws, rows_for_ws, data_style, colorize)
|
|
156
|
+
rows_for_ws.clear()
|
|
157
|
+
|
|
158
|
+
used_names = set()
|
|
159
|
+
for row, row_style, module_name in self._iterate_rows_iod(colorize=colorize, include_module_titles=False):
|
|
160
|
+
if module_name != current_module:
|
|
161
|
+
flush_ws()
|
|
162
|
+
|
|
163
|
+
ws = self._setup_worksheet(wb, self._sanitize_sheet_name(module_name, used_names))
|
|
164
|
+
self._write_headers(ws, self.model.metadata.header, header_style)
|
|
165
|
+
if column_widths:
|
|
166
|
+
self._set_column_widths(ws, column_widths)
|
|
167
|
+
current_module = module_name
|
|
168
|
+
rows_for_ws.append((row, row_style))
|
|
169
|
+
|
|
170
|
+
flush_ws()
|
|
171
|
+
wb.save(self.output)
|
|
172
|
+
|
|
173
|
+
@staticmethod
|
|
174
|
+
def _sanitize_sheet_name(name: str, used_names: set = None) -> str:
|
|
175
|
+
"""Sanitize and ensure uniqueness of a worksheet name for Excel compatibility.
|
|
176
|
+
|
|
177
|
+
This function replaces invalid characters with underscores and trims the name to 31 characters.
|
|
178
|
+
If the name is empty or None, it uses 'Sheet'. If the name is already used, it appends a numeric
|
|
179
|
+
suffix to ensure uniqueness within the workbook.
|
|
180
|
+
|
|
181
|
+
Args:
|
|
182
|
+
name (str): The proposed worksheet name.
|
|
183
|
+
used_names (set, optional): Set of already used worksheet names.
|
|
184
|
+
|
|
185
|
+
Returns:
|
|
186
|
+
str: A sanitized and unique worksheet name suitable for Excel.
|
|
187
|
+
|
|
188
|
+
"""
|
|
189
|
+
orig_name = re.sub(r'[\[\]\*:/\\\?]', '_', name) if name else "Sheet"
|
|
190
|
+
orig_name = orig_name[:31] if orig_name else "Sheet"
|
|
191
|
+
if used_names is None:
|
|
192
|
+
used_names = set()
|
|
193
|
+
sheet_name = orig_name
|
|
194
|
+
i = 1
|
|
195
|
+
while sheet_name in used_names or not sheet_name:
|
|
196
|
+
suffix = f"_{i}"
|
|
197
|
+
sheet_name = (
|
|
198
|
+
(orig_name[:31-len(suffix)] + suffix)
|
|
199
|
+
if len(orig_name) + len(suffix) > 31
|
|
200
|
+
else orig_name + suffix
|
|
201
|
+
)
|
|
202
|
+
i += 1
|
|
203
|
+
used_names.add(sheet_name)
|
|
204
|
+
return sheet_name
|
|
205
|
+
|
|
206
|
+
def _iterate_rows_iod(
|
|
207
|
+
self,
|
|
208
|
+
colorize: bool = False,
|
|
209
|
+
include_module_titles: bool = True
|
|
210
|
+
) -> Generator[Tuple[List[str], Optional[str], Optional[str]], None, None]:
|
|
211
|
+
"""Generate rows for IODSpecPrinter with module title rows, module grouping, and optional styling.
|
|
212
|
+
|
|
213
|
+
Iterates through the model content tree and yields tuples representing each row to be printed.
|
|
214
|
+
For module nodes, optionnaly yields a module title row with the module name and styling.
|
|
215
|
+
For attribute rows, yields the attribute values, row style, and the current module name for grouping.
|
|
216
|
+
|
|
217
|
+
Args:
|
|
218
|
+
colorize (bool): Whether to apply color styling to rows.
|
|
219
|
+
include_module_titles (bool): Whether to yield module title rows (True for table/csv, False for xlsx).
|
|
220
|
+
|
|
221
|
+
Yields:
|
|
222
|
+
tuple: (row_data, row_style, module_name) where row_data is a list of cell values,
|
|
223
|
+
row_style is an RGB color string (e.g., "rgb(255,255,0)") from LEVEL_COLORS or SPECIAL_COLORS,
|
|
224
|
+
or None if not colorized, and module_name is the current module for grouping.
|
|
225
|
+
|
|
226
|
+
"""
|
|
227
|
+
attr_headers = list(self.model.metadata.header)
|
|
228
|
+
current_module = None
|
|
229
|
+
for node in PreOrderIter(self.model.content):
|
|
230
|
+
if node.name == "content":
|
|
231
|
+
continue
|
|
232
|
+
if hasattr(node, "module"):
|
|
233
|
+
current_module = getattr(node, "module", None)
|
|
234
|
+
if include_module_titles:
|
|
235
|
+
iod_title = getattr(node, "module", getattr(node, "name", ""))
|
|
236
|
+
iod_usage = getattr(node, "usage", "")
|
|
237
|
+
iod_title_text = f"{iod_title} Module ({iod_usage})" if iod_usage else iod_title
|
|
238
|
+
row_style = SPECIAL_COLORS["title"] if colorize else None
|
|
239
|
+
yield [iod_title_text] + [""] * (len(attr_headers) - 1), row_style, current_module or "Other"
|
|
240
|
+
# else: skip module title rows for xlsx
|
|
241
|
+
else:
|
|
242
|
+
# Use the most recent current_ie for all attribute rows
|
|
243
|
+
row = [getattr(node, attr, "") for attr in self.model.metadata.column_to_attr.values()]
|
|
244
|
+
row_style = None
|
|
245
|
+
if colorize:
|
|
246
|
+
if self.model._is_include(node):
|
|
247
|
+
row_style = SPECIAL_COLORS["include"]
|
|
248
|
+
elif self.model._is_title(node):
|
|
249
|
+
row_style = SPECIAL_COLORS["title"]
|
|
250
|
+
else:
|
|
251
|
+
# use (node.depth - 2) since attributes are children of module nodes,
|
|
252
|
+
# which are themselves children of content (root) node
|
|
253
|
+
row_style = LEVEL_COLORS[(node.depth - 2) % len(LEVEL_COLORS)]
|
|
254
|
+
yield row, row_style, current_module or "Other"
|