ddex-parser 0.5.0__cp310-abi3-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.
@@ -0,0 +1,133 @@
1
+ # packages/ddex-parser/bindings/python/python/ddex_parser/__init__.py
2
+ """
3
+ DDEX Parser - High-performance DDEX XML parser for Python
4
+ """
5
+
6
+ from __future__ import annotations
7
+ from typing import Optional, Union, Dict, Any, Iterator, IO, TYPE_CHECKING
8
+ import asyncio
9
+ from pathlib import Path
10
+
11
+ if TYPE_CHECKING:
12
+ import pandas as pd
13
+
14
+ from importlib.metadata import version as _version
15
+
16
+ __version__ = _version("ddex-parser")
17
+
18
+ # The native extension (the Rust parser) is required: there is no pure-Python fallback,
19
+ # so a failed load is an ImportError that names the real cause.
20
+ try:
21
+ from ._internal import DDEXParser as _DDEXParser, StreamIterator
22
+ except ImportError as e:
23
+ raise ImportError(
24
+ f"ddex_parser: the native extension (ddex_parser._internal) failed to load: {e}. "
25
+ "Reinstall a wheel built for this platform and Python version "
26
+ "(pip install --force-reinstall ddex-parser), or, in a source checkout, build it with "
27
+ "`maturin develop` in packages/ddex-parser/bindings/python."
28
+ ) from e
29
+
30
+ __all__ = ["DDEXParser", "ParseOptions", "ParseResult", "parse", "__version__"]
31
+
32
+
33
+ class ParseOptions:
34
+ """Options for parsing DDEX XML."""
35
+
36
+ def __init__(
37
+ self,
38
+ include_raw_extensions: bool = False,
39
+ include_comments: bool = False,
40
+ validate_references: bool = True,
41
+ streaming: bool = False,
42
+ timeout: float = 30.0,
43
+ ):
44
+ self.include_raw_extensions = include_raw_extensions
45
+ self.include_comments = include_comments
46
+ self.validate_references = validate_references
47
+ self.streaming = streaming
48
+ self.timeout = timeout
49
+
50
+ def to_dict(self) -> Dict[str, Any]:
51
+ """Convert to dictionary for Rust."""
52
+ return {
53
+ "include_raw_extensions": self.include_raw_extensions,
54
+ "include_comments": self.include_comments,
55
+ "validate_references": self.validate_references,
56
+ "streaming": self.streaming,
57
+ }
58
+
59
+
60
+ class ParseResult:
61
+ """Result of parsing a DDEX message."""
62
+
63
+ def __init__(self, data: Dict[str, Any]):
64
+ self._data = data
65
+ self.message_id = data.get("message_id", "")
66
+ self.version = data.get("version", "")
67
+ self.release_count = data.get("release_count", 0)
68
+ self.releases = data.get("releases", [])
69
+
70
+ def __repr__(self) -> str:
71
+ return f"ParseResult(message_id='{self.message_id}', version='{self.version}', releases={self.release_count})"
72
+
73
+
74
+ class DDEXParser:
75
+ """High-performance DDEX XML parser."""
76
+
77
+ def __init__(self):
78
+ """Initialize the DDEX parser."""
79
+ self._parser = _DDEXParser()
80
+
81
+ def __repr__(self) -> str:
82
+ return f"DDEXParser(version='{__version__}')"
83
+
84
+ def parse(self, xml: Union[str, bytes], options: Optional[ParseOptions] = None) -> ParseResult:
85
+ """Parse DDEX XML synchronously."""
86
+ opts = options.to_dict() if options else None
87
+ result = self._parser.parse(xml, opts)
88
+ return result # Return PyParsedERNMessage directly
89
+
90
+ async def parse_async(self, xml: Union[str, bytes], options: Optional[ParseOptions] = None) -> ParseResult:
91
+ """Parse DDEX XML asynchronously."""
92
+ opts = options.to_dict() if options else None
93
+ result = await self._parser.parse_async(xml, opts)
94
+ return result # Return PyParsedERNMessage directly
95
+
96
+ def stream(self, xml: Union[str, bytes], options: Optional[ParseOptions] = None) -> Iterator[Dict[str, Any]]:
97
+ """Stream parse large DDEX files."""
98
+ opts = options.to_dict() if options else None
99
+ stream_iter = self._parser.stream(xml, opts)
100
+
101
+ # Yield from the Rust iterator
102
+ try:
103
+ while True:
104
+ item = next(stream_iter)
105
+ if item is None:
106
+ break
107
+ yield item
108
+ except StopIteration:
109
+ pass
110
+
111
+ def to_dataframe(self, xml: Union[str, bytes], schema: str = 'flat') -> 'pd.DataFrame':
112
+ """Convert DDEX XML to pandas DataFrame."""
113
+ return self._parser.to_dataframe(xml, schema)
114
+
115
+ def detect_version(self, xml: Union[str, bytes]) -> str:
116
+ """Detect DDEX version from XML."""
117
+ return self._parser.detect_version(xml)
118
+
119
+ def sanity_check(self, xml: Union[str, bytes]) -> Dict[str, Any]:
120
+ """Perform sanity check on DDEX XML."""
121
+ return self._parser.sanity_check(xml)
122
+
123
+
124
+ # Convenience function
125
+ def parse(xml: Union[str, bytes], **kwargs) -> ParseResult:
126
+ """Convenience function to parse DDEX XML."""
127
+ parser = DDEXParser()
128
+ options = ParseOptions(**kwargs) if kwargs else None
129
+ return parser.parse(xml, options)
130
+
131
+
132
+ # Import CLI main function
133
+ from .cli import main # noqa: E402
Binary file
ddex_parser/cli.py ADDED
@@ -0,0 +1,76 @@
1
+ """DDEX Parser CLI."""
2
+ import sys
3
+ import json
4
+
5
+ def main():
6
+ """CLI entry point."""
7
+ from ddex_parser import DDEXParser, __version__
8
+
9
+ if len(sys.argv) < 2 or sys.argv[1] in ["--help", "-h"]:
10
+ print(f"DDEX Parser v{__version__}")
11
+ print("\nUsage: ddex-parser <command> <file>")
12
+ print("\nCommands:")
13
+ print(" parse <file> Parse DDEX XML file")
14
+ print(" version <file> Detect DDEX version")
15
+ print(" check <file> Check file validity")
16
+ print("\nOptions:")
17
+ print(" --version Show version")
18
+ print(" --help, -h Show this help")
19
+ return
20
+
21
+ if sys.argv[1] == "--version":
22
+ print(f"ddex-parser {__version__}")
23
+ return
24
+
25
+ command = sys.argv[1]
26
+
27
+ if len(sys.argv) < 3:
28
+ print(f"Error: Command '{command}' requires a file argument")
29
+ sys.exit(1)
30
+
31
+ filepath = sys.argv[2]
32
+ parser = DDEXParser()
33
+
34
+ try:
35
+ with open(filepath, 'r') as f:
36
+ xml = f.read()
37
+ except FileNotFoundError:
38
+ print(f"Error: File not found: {filepath}")
39
+ sys.exit(1)
40
+ except Exception as e:
41
+ print(f"Error reading file: {e}")
42
+ sys.exit(1)
43
+
44
+ try:
45
+ if command == "parse":
46
+ result = parser.parse(xml)
47
+ data = {
48
+ 'message_id': result.message_id,
49
+ 'version': result.version,
50
+ 'release_count': result.release_count,
51
+ 'releases': result.releases[:3] if result.releases else [] # First 3 releases
52
+ }
53
+ print(json.dumps(data, indent=2))
54
+ elif command == "version":
55
+ v = parser.detect_version(xml)
56
+ print(f"DDEX Version: {v}")
57
+ elif command == "check":
58
+ result = parser.sanity_check(xml)
59
+ if result['is_valid']:
60
+ print(f"✅ Valid DDEX {result['version']}")
61
+ else:
62
+ print(f"❌ Invalid DDEX")
63
+ if result.get('errors'):
64
+ for error in result['errors']:
65
+ print(f" - {error}")
66
+ sys.exit(1)
67
+ else:
68
+ print(f"Error: Unknown command '{command}'")
69
+ print("Run 'ddex-parser --help' for usage")
70
+ sys.exit(1)
71
+ except Exception as e:
72
+ print(f"Error processing file: {e}")
73
+ sys.exit(1)
74
+
75
+ if __name__ == '__main__':
76
+ main()
@@ -0,0 +1,120 @@
1
+ Metadata-Version: 2.4
2
+ Name: ddex-parser
3
+ Version: 0.5.0
4
+ Classifier: Development Status :: 4 - Beta
5
+ Classifier: Intended Audience :: Developers
6
+ Classifier: License :: OSI Approved :: MIT License
7
+ Classifier: Operating System :: MacOS
8
+ Classifier: Operating System :: Microsoft :: Windows
9
+ Classifier: Operating System :: POSIX :: Linux
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Classifier: Programming Language :: Rust
18
+ Classifier: Topic :: Multimedia :: Sound/Audio
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Classifier: Topic :: Text Processing :: Markup :: XML
21
+ Requires-Dist: pytest>=7.0 ; extra == 'dev'
22
+ Requires-Dist: pytest-asyncio>=0.21 ; extra == 'dev'
23
+ Requires-Dist: pytest-benchmark>=4.0 ; extra == 'dev'
24
+ Requires-Dist: black>=23.0 ; extra == 'dev'
25
+ Requires-Dist: mypy>=1.0 ; extra == 'dev'
26
+ Requires-Dist: ruff>=0.1 ; extra == 'dev'
27
+ Requires-Dist: pandas>=1.5 ; extra == 'pandas'
28
+ Requires-Dist: pyarrow>=10.0 ; extra == 'pandas'
29
+ Provides-Extra: dev
30
+ Provides-Extra: pandas
31
+ Summary: DDEX ERN XML parser (ERN 3.8.x, 4.2, 4.3) for Python, with pandas export
32
+ Keywords: ddex,xml,parser,music,metadata,ern
33
+ Author-email: Kevin Marques Moo <daddykev@gmail.com>
34
+ License: MIT
35
+ Requires-Python: >=3.10
36
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
37
+ Project-URL: Changelog, https://github.com/daddykev/ddex-suite/blob/main/CHANGELOG.md
38
+ Project-URL: Documentation, https://ddex-suite.org/docs/parser
39
+ Project-URL: Homepage, https://ddex-suite.org
40
+ Project-URL: Issues, https://github.com/daddykev/ddex-suite/issues
41
+ Project-URL: Migration notes (0.5.0), https://github.com/daddykev/ddex-suite/blob/main/dev-docs/RELEASE_NOTES_0.5.0.md
42
+ Project-URL: Repository, https://github.com/daddykev/ddex-suite
43
+
44
+ # ddex-parser (Python)
45
+
46
+ DDEX ERN XML parser for Python, a native extension over the Rust
47
+ [`ddex-parser`](https://crates.io/crates/ddex-parser) crate. Part of
48
+ [DDEX Suite](https://github.com/daddykev/ddex-suite). It reads ERN 3.8.1, 3.8.2, 4.2 and
49
+ 4.3 messages and exports them to pandas DataFrames.
50
+
51
+ > **0.5.0 has breaking changes.** Importing without the native extension raises
52
+ > `ImportError` (the mock fallback is gone), text is kept exactly as written, and the
53
+ > DataFrames gained columns. See the
54
+ > [0.5.0 migration notes](https://github.com/daddykev/ddex-suite/blob/main/dev-docs/RELEASE_NOTES_0.5.0.md).
55
+
56
+ ## Installation
57
+
58
+ ```bash
59
+ pip install ddex-parser
60
+ pip install "ddex-parser[pandas]" # for to_dataframe()
61
+ ```
62
+
63
+ Wheels (abi3, Python 3.10 or newer) are published for Linux x86_64 and aarch64 (glibc
64
+ 2.28+), Linux x86_64 (musl), macOS x86_64 and arm64, and Windows x64. On other platforms
65
+ pip builds from the source distribution, which needs a Rust toolchain. If the native
66
+ extension cannot be loaded, `import ddex_parser` raises an `ImportError` that names the
67
+ cause.
68
+
69
+ ## Example
70
+
71
+ ```python
72
+ from ddex_parser import DDEXParser
73
+
74
+ parser = DDEXParser()
75
+ with open("release.xml", encoding="utf-8") as f:
76
+ message = parser.parse(f.read())
77
+
78
+ print(message.message_id(), message.version(), message.message_control_type())
79
+ print(message.release_count(), "release(s)")
80
+ for deal in message.deals():
81
+ print(deal["deal_id"], deal["releases"], deal["start_date"], deal["end_date"], deal["territories"])
82
+
83
+ releases = message.to_dataframe("releases")
84
+ print(releases[["release_id", "title", "artist", "genre", "label_name", "release_dates"]])
85
+
86
+ tracks = message.to_dataframe("tracks")
87
+ print(tracks[["track_index", "track_title", "isrc", "duration", "disc_number", "group_path"]])
88
+ ```
89
+
90
+ - `parse(xml)` accepts `str` or `bytes` and returns a `ParsedERNMessage`:
91
+ `message_id()`, `version()`, `release_count()`, `message_control_type()`, `deals()`
92
+ (one dict per deal) and `to_dataframe(schema)`. These are methods.
93
+ - `to_dataframe` schemas: `"flat"` (a message row, then one row per release),
94
+ `"releases"` and `"tracks"`. Columns include release dates as written, P and C lines,
95
+ genres, parental warnings, labels, and each track's position, disc and track numbers
96
+ and enclosing groups. Absent values are `None` or empty lists, never invented.
97
+ Durations are in seconds.
98
+ - `parse_async(xml)` is the awaitable version; `detect_version(xml)` returns the enum
99
+ spelling (`"V4_3"`).
100
+ - `stream(xml)` parses the whole document and then yields its releases one by one; it
101
+ does not reduce memory use.
102
+
103
+ ## Security
104
+
105
+ The parser rejects DTDs and external entities (XXE), limits entity expansion, element
106
+ depth and input size, and never fetches from the network. It does not validate against
107
+ the DDEX XSD or the AVS business rules.
108
+
109
+ ## Links
110
+
111
+ - Documentation: [ddex-suite.org](https://ddex-suite.org/docs/parser)
112
+ - [Changelog](https://github.com/daddykev/ddex-suite/blob/main/CHANGELOG.md)
113
+ - [0.5.0 migration notes](https://github.com/daddykev/ddex-suite/blob/main/dev-docs/RELEASE_NOTES_0.5.0.md)
114
+ - [Known issues](https://github.com/daddykev/ddex-suite/blob/main/KNOWN_ISSUES.md)
115
+ - [Report an issue](https://github.com/daddykev/ddex-suite/issues)
116
+
117
+ ## License
118
+
119
+ MIT, see [LICENSE](https://github.com/daddykev/ddex-suite/blob/main/LICENSE).
120
+
@@ -0,0 +1,8 @@
1
+ ddex_parser/__init__.py,sha256=BPgIoaliU_KzB4DwVSZ91EUndb7YySrtAnC3cPpCRPA,4915
2
+ ddex_parser/_internal.pyd,sha256=LM8uH2X_YajU4Keo5fiop2kwG_sP5rvcpCRNNPbrAMw,976896
3
+ ddex_parser/cli.py,sha256=sxaVo-DA8WH_GsJVuSpyHeiD6naCmTOoAhsQE007480,2504
4
+ ddex_parser-0.5.0.dist-info/METADATA,sha256=CjsyxNtbrPRNVGffiQcHn-YbSb26tOg3Ol9aM9B81XI,5462
5
+ ddex_parser-0.5.0.dist-info/WHEEL,sha256=TzjyIyBUptJHnlQyOymQYLWjtXe7MGI0m3QvmcG7PpI,96
6
+ ddex_parser-0.5.0.dist-info/entry_points.txt,sha256=-2qqcyzKMjRRcaXezFUbwF_GquT-buw-_gML0sEQMZI,47
7
+ ddex_parser-0.5.0.dist-info/sboms/ddex-parser-python.cyclonedx.json,sha256=nKEJeNtJcPukfqiqugygVB30yfXi3xCXRtLF3Xu7VGY,199044
8
+ ddex_parser-0.5.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: maturin (1.16.0)
3
+ Root-Is-Purelib: false
4
+ Tag: cp310-abi3-win_amd64
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ddex-parser=ddex_parser:main