hamonpy 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.
Files changed (59) hide show
  1. hamonpy-0.3.0/LICENSE +232 -0
  2. hamonpy-0.3.0/MANIFEST.in +5 -0
  3. hamonpy-0.3.0/PKG-INFO +84 -0
  4. hamonpy-0.3.0/README.md +38 -0
  5. hamonpy-0.3.0/hamonpy/__init__.py +5 -0
  6. hamonpy-0.3.0/hamonpy/__main__.py +5 -0
  7. hamonpy-0.3.0/hamonpy/adapters/__init__.py +20 -0
  8. hamonpy-0.3.0/hamonpy/adapters/bps_fh.py +161 -0
  9. hamonpy-0.3.0/hamonpy/adapters/choro.py +141 -0
  10. hamonpy-0.3.0/hamonpy/adapters/dcml.py +383 -0
  11. hamonpy-0.3.0/hamonpy/adapters/dcml_expanded.py +168 -0
  12. hamonpy-0.3.0/hamonpy/adapters/dezrann.py +208 -0
  13. hamonpy-0.3.0/hamonpy/adapters/dilemma.py +321 -0
  14. hamonpy-0.3.0/hamonpy/adapters/flexohr.py +319 -0
  15. hamonpy-0.3.0/hamonpy/adapters/formats.py +363 -0
  16. hamonpy-0.3.0/hamonpy/adapters/harm.py +201 -0
  17. hamonpy-0.3.0/hamonpy/adapters/harte.py +439 -0
  18. hamonpy-0.3.0/hamonpy/adapters/humdrum.py +268 -0
  19. hamonpy-0.3.0/hamonpy/adapters/ireal.py +239 -0
  20. hamonpy-0.3.0/hamonpy/adapters/jams.py +198 -0
  21. hamonpy-0.3.0/hamonpy/adapters/kp.py +91 -0
  22. hamonpy-0.3.0/hamonpy/adapters/mei.py +288 -0
  23. hamonpy-0.3.0/hamonpy/adapters/ms3_adapter.py +90 -0
  24. hamonpy-0.3.0/hamonpy/adapters/music21_adapter.py +514 -0
  25. hamonpy-0.3.0/hamonpy/adapters/music21_converter.py +87 -0
  26. hamonpy-0.3.0/hamonpy/adapters/musicxml.py +115 -0
  27. hamonpy-0.3.0/hamonpy/adapters/partitura_adapter.py +148 -0
  28. hamonpy-0.3.0/hamonpy/adapters/rock_corpus.py +160 -0
  29. hamonpy-0.3.0/hamonpy/adapters/romantext.py +75 -0
  30. hamonpy-0.3.0/hamonpy/adapters/treebank.py +79 -0
  31. hamonpy-0.3.0/hamonpy/ast.py +286 -0
  32. hamonpy-0.3.0/hamonpy/capability.py +296 -0
  33. hamonpy-0.3.0/hamonpy/cli.py +540 -0
  34. hamonpy-0.3.0/hamonpy/datasets.py +318 -0
  35. hamonpy-0.3.0/hamonpy/export.py +293 -0
  36. hamonpy-0.3.0/hamonpy/generated/__init__.py +0 -0
  37. hamonpy-0.3.0/hamonpy/generated/antlr/__init__.py +0 -0
  38. hamonpy-0.3.0/hamonpy/generated/antlr/hamonLexer.interp +185 -0
  39. hamonpy-0.3.0/hamonpy/generated/antlr/hamonLexer.py +354 -0
  40. hamonpy-0.3.0/hamonpy/generated/antlr/hamonLexer.tokens +81 -0
  41. hamonpy-0.3.0/hamonpy/generated/antlr/hamonParser.interp +167 -0
  42. hamonpy-0.3.0/hamonpy/generated/antlr/hamonParser.py +3841 -0
  43. hamonpy-0.3.0/hamonpy/generated/antlr/hamonParser.tokens +81 -0
  44. hamonpy-0.3.0/hamonpy/generated/antlr/hamonParserListener.py +408 -0
  45. hamonpy-0.3.0/hamonpy/generated/antlr/hamonParserVisitor.py +233 -0
  46. hamonpy-0.3.0/hamonpy/normalize.py +683 -0
  47. hamonpy-0.3.0/hamonpy/parse.py +56 -0
  48. hamonpy-0.3.0/hamonpy/parse_visitor.py +289 -0
  49. hamonpy-0.3.0/hamonpy/report.py +604 -0
  50. hamonpy-0.3.0/hamonpy/serialize.py +169 -0
  51. hamonpy-0.3.0/hamonpy/validate.py +54 -0
  52. hamonpy-0.3.0/hamonpy.egg-info/PKG-INFO +84 -0
  53. hamonpy-0.3.0/hamonpy.egg-info/SOURCES.txt +57 -0
  54. hamonpy-0.3.0/hamonpy.egg-info/dependency_links.txt +1 -0
  55. hamonpy-0.3.0/hamonpy.egg-info/entry_points.txt +2 -0
  56. hamonpy-0.3.0/hamonpy.egg-info/requires.txt +28 -0
  57. hamonpy-0.3.0/hamonpy.egg-info/top_level.txt +1 -0
  58. hamonpy-0.3.0/pyproject.toml +76 -0
  59. hamonpy-0.3.0/setup.cfg +4 -0
hamonpy-0.3.0/LICENSE ADDED
@@ -0,0 +1,232 @@
1
+ hamonpy — the Python reference implementation of HAMON
2
+ =====================================================
3
+
4
+ Copyright (c) 2026 Universidad de Alicante.
5
+
6
+ hamonpy was written by Patricia Garcia-Iasci and David Rizo. It implements HAMON,
7
+ the standard authored with Johannes Hentschel and Fabian C. Moss.
8
+
9
+ This package is software, licensed under the Apache License 2.0, reproduced in
10
+ full below (SPDX: Apache-2.0).
11
+
12
+ HAMON is a standard as well as an implementation. The specification and its data
13
+ — the grammar, the schema, the conformance corpus and the documentation — are
14
+ licensed separately under CC BY 4.0, and are not part of this package. See the
15
+ LICENSE file in the HAMON repository for both.
16
+
17
+ Datasets that HAMON reads are not redistributed here and keep their own terms.
18
+
19
+ Attribution
20
+ -----------
21
+
22
+ Apache-2.0 requires you to keep this notice. If you use HAMON in research, cite:
23
+
24
+ Garcia-Iasci, P., Hentschel, J., Moss, F. C., & Rizo, D. (2026).
25
+ Bridging harmonic representations through a multi-modal encoding.
26
+ International Conference on Computational and Cognitive Musicology
27
+ (ICCCM 2026). https://digital.musicology.org/icccm-2026/
28
+
29
+ --------------------------------------------------------------------------------
30
+
31
+
32
+ Apache License
33
+ Version 2.0, January 2004
34
+ http://www.apache.org/licenses/
35
+
36
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
37
+
38
+ 1. Definitions.
39
+
40
+ "License" shall mean the terms and conditions for use, reproduction,
41
+ and distribution as defined by Sections 1 through 9 of this document.
42
+
43
+ "Licensor" shall mean the copyright owner or entity authorized by
44
+ the copyright owner that is granting the License.
45
+
46
+ "Legal Entity" shall mean the union of the acting entity and all
47
+ other entities that control, are controlled by, or are under common
48
+ control with that entity. For the purposes of this definition,
49
+ "control" means (i) the power, direct or indirect, to cause the
50
+ direction or management of such entity, whether by contract or
51
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
52
+ outstanding shares, or (iii) beneficial ownership of such entity.
53
+
54
+ "You" (or "Your") shall mean an individual or Legal Entity
55
+ exercising permissions granted by this License.
56
+
57
+ "Source" form shall mean the preferred form for making modifications,
58
+ including but not limited to software source code, documentation
59
+ source, and configuration files.
60
+
61
+ "Object" form shall mean any form resulting from mechanical
62
+ transformation or translation of a Source form, including but
63
+ not limited to compiled object code, generated documentation,
64
+ and conversions to other media types.
65
+
66
+ "Work" shall mean the work of authorship, whether in Source or
67
+ Object form, made available under the License, as indicated by a
68
+ copyright notice that is included in or attached to the work
69
+ (an example is provided in the Appendix below).
70
+
71
+ "Derivative Works" shall mean any work, whether in Source or Object
72
+ form, that is based on (or derived from) the Work and for which the
73
+ editorial revisions, annotations, elaborations, or other modifications
74
+ represent, as a whole, an original work of authorship. For the purposes
75
+ of this License, Derivative Works shall not include works that remain
76
+ separable from, or merely link (or bind by name) to the interfaces of,
77
+ the Work and Derivative Works thereof.
78
+
79
+ "Contribution" shall mean any work of authorship, including
80
+ the original version of the Work and any modifications or additions
81
+ to that Work or Derivative Works thereof, that is intentionally
82
+ submitted to Licensor for inclusion in the Work by the copyright owner
83
+ or by an individual or Legal Entity authorized to submit on behalf of
84
+ the copyright owner. For the purposes of this definition, "submitted"
85
+ means any form of electronic, verbal, or written communication sent
86
+ to the Licensor or its representatives, including but not limited to
87
+ communication on electronic mailing lists, source code control systems,
88
+ and issue tracking systems that are managed by, or on behalf of, the
89
+ Licensor for the purpose of discussing and improving the Work, but
90
+ excluding communication that is conspicuously marked or otherwise
91
+ designated in writing by the copyright owner as "Not a Contribution."
92
+
93
+ "Contributor" shall mean Licensor and any individual or Legal Entity
94
+ on behalf of whom a Contribution has been received by Licensor and
95
+ subsequently incorporated within the Work.
96
+
97
+ 2. Grant of Copyright License. Subject to the terms and conditions of
98
+ this License, each Contributor hereby grants to You a perpetual,
99
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
100
+ copyright license to reproduce, prepare Derivative Works of,
101
+ publicly display, publicly perform, sublicense, and distribute the
102
+ Work and such Derivative Works in Source or Object form.
103
+
104
+ 3. Grant of Patent License. Subject to the terms and conditions of
105
+ this License, each Contributor hereby grants to You a perpetual,
106
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
107
+ (except as stated in this section) patent license to make, have made,
108
+ use, offer to sell, sell, import, and otherwise transfer the Work,
109
+ where such license applies only to those patent claims licensable
110
+ by such Contributor that are necessarily infringed by their
111
+ Contribution(s) alone or by combination of their Contribution(s)
112
+ with the Work to which such Contribution(s) was submitted. If You
113
+ institute patent litigation against any entity (including a
114
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
115
+ or a Contribution incorporated within the Work constitutes direct
116
+ or contributory patent infringement, then any patent licenses
117
+ granted to You under this License for that Work shall terminate
118
+ as of the date such litigation is filed.
119
+
120
+ 4. Redistribution. You may reproduce and distribute copies of the
121
+ Work or Derivative Works thereof in any medium, with or without
122
+ modifications, and in Source or Object form, provided that You
123
+ meet the following conditions:
124
+
125
+ (a) You must give any other recipients of the Work or
126
+ Derivative Works a copy of this License; and
127
+
128
+ (b) You must cause any modified files to carry prominent notices
129
+ stating that You changed the files; and
130
+
131
+ (c) You must retain, in the Source form of any Derivative Works
132
+ that You distribute, all copyright, patent, trademark, and
133
+ attribution notices from the Source form of the Work,
134
+ excluding those notices that do not pertain to any part of
135
+ the Derivative Works; and
136
+
137
+ (d) If the Work includes a "NOTICE" text file as part of its
138
+ distribution, then any Derivative Works that You distribute must
139
+ include a readable copy of the attribution notices contained
140
+ within such NOTICE file, excluding those notices that do not
141
+ pertain to any part of the Derivative Works, in at least one
142
+ of the following places: within a NOTICE text file distributed
143
+ as part of the Derivative Works; within the Source form or
144
+ documentation, if provided along with the Derivative Works; or,
145
+ within a display generated by the Derivative Works, if and
146
+ wherever such third-party notices normally appear. The contents
147
+ of the NOTICE file are for informational purposes only and
148
+ do not modify the License. You may add Your own attribution
149
+ notices within Derivative Works that You distribute, alongside
150
+ or as an addendum to the NOTICE text from the Work, provided
151
+ that such additional attribution notices cannot be construed
152
+ as modifying the License.
153
+
154
+ You may add Your own copyright statement to Your modifications and
155
+ may provide additional or different license terms and conditions
156
+ for use, reproduction, or distribution of Your modifications, or
157
+ for any such Derivative Works as a whole, provided Your use,
158
+ reproduction, and distribution of the Work otherwise complies with
159
+ the conditions stated in this License.
160
+
161
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
162
+ any Contribution intentionally submitted for inclusion in the Work
163
+ by You to the Licensor shall be under the terms and conditions of
164
+ this License, without any additional terms or conditions.
165
+ Notwithstanding the above, nothing herein shall supersede or modify
166
+ the terms of any separate license agreement you may have executed
167
+ with Licensor regarding such Contributions.
168
+
169
+ 6. Trademarks. This License does not grant permission to use the trade
170
+ names, trademarks, service marks, or product names of the Licensor,
171
+ except as required for reasonable and customary use in describing the
172
+ origin of the Work and reproducing the content of the NOTICE file.
173
+
174
+ 7. Disclaimer of Warranty. Unless required by applicable law or
175
+ agreed to in writing, Licensor provides the Work (and each
176
+ Contributor provides its Contributions) on an "AS IS" BASIS,
177
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
178
+ implied, including, without limitation, any warranties or conditions
179
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
180
+ PARTICULAR PURPOSE. You are solely responsible for determining the
181
+ appropriateness of using or redistributing the Work and assume any
182
+ risks associated with Your exercise of permissions under this License.
183
+
184
+ 8. Limitation of Liability. In no event and under no legal theory,
185
+ whether in tort (including negligence), contract, or otherwise,
186
+ unless required by applicable law (such as deliberate and grossly
187
+ negligent acts) or agreed to in writing, shall any Contributor be
188
+ liable to You for damages, including any direct, indirect, special,
189
+ incidental, or consequential damages of any character arising as a
190
+ result of this License or out of the use or inability to use the
191
+ Work (including but not limited to damages for loss of goodwill,
192
+ work stoppage, computer failure or malfunction, or any and all
193
+ other commercial damages or losses), even if such Contributor
194
+ has been advised of the possibility of such damages.
195
+
196
+ 9. Accepting Warranty or Additional Liability. While redistributing
197
+ the Work or Derivative Works thereof, You may choose to offer,
198
+ and charge a fee for, acceptance of support, warranty, indemnity,
199
+ or other liability obligations and/or rights consistent with this
200
+ License. However, in accepting such obligations, You may act only
201
+ on Your own behalf and on Your sole responsibility, not on behalf
202
+ of any other Contributor, and only if You agree to indemnify,
203
+ defend, and hold each Contributor harmless for any liability
204
+ incurred by, or claims asserted against, such Contributor by reason
205
+ of your accepting any such warranty or additional liability.
206
+
207
+ END OF TERMS AND CONDITIONS
208
+
209
+ APPENDIX: How to apply the Apache License to your work.
210
+
211
+ To apply the Apache License to your work, attach the following
212
+ boilerplate notice, with the fields enclosed by brackets "[]"
213
+ replaced with your own identifying information. (Don't include
214
+ the brackets!) The text should be enclosed in the appropriate
215
+ comment syntax for the file format. We also recommend that a
216
+ file or class name and description of purpose be included on the
217
+ same "printed page" as the copyright notice for easier
218
+ identification within third-party archives.
219
+
220
+ Copyright [yyyy] [name of copyright owner]
221
+
222
+ Licensed under the Apache License, Version 2.0 (the "License");
223
+ you may not use this file except in compliance with the License.
224
+ You may obtain a copy of the License at
225
+
226
+ http://www.apache.org/licenses/LICENSE-2.0
227
+
228
+ Unless required by applicable law or agreed to in writing, software
229
+ distributed under the License is distributed on an "AS IS" BASIS,
230
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
231
+ See the License for the specific language governing permissions and
232
+ limitations under the License.
@@ -0,0 +1,5 @@
1
+ include LICENSE
2
+ include README.md
3
+ # The test suite is data-driven over fixtures that live in the repository, not in the
4
+ # package, so shipping it would hand users a suite that cannot pass. It stays in the repo.
5
+ prune tests
hamonpy-0.3.0/PKG-INFO ADDED
@@ -0,0 +1,84 @@
1
+ Metadata-Version: 2.4
2
+ Name: hamonpy
3
+ Version: 0.3.0
4
+ Summary: HAMON (Harmony Model and Notation) — a universal, lossless harmony-label interlingua (Python reference implementation)
5
+ Author: Patricia Garcia-Iasci, David Rizo
6
+ License: Apache-2.0
7
+ Project-URL: Repository, https://github.com/OMR-PRAIG-UA-ES/hamon
8
+ Project-URL: Homepage, https://omr-praig-ua-es.github.io/hamon/
9
+ Project-URL: Documentation, https://omr-praig-ua-es.github.io/hamon/use.html
10
+ Project-URL: Loss viewer, https://omr-praig-ua-es.github.io/hamon/icccm26.html
11
+ Keywords: harmony,music,music-theory,musicology,chord,roman-numerals,figured-bass,nashville,interlingua,MEI,MusicXML,Humdrum,DCML,OMR
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Multimedia :: Sound/Audio
21
+ Classifier: Topic :: Scientific/Engineering
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: antlr4-python3-runtime==4.13.2
26
+ Provides-Extra: dev
27
+ Requires-Dist: pytest>=8; extra == "dev"
28
+ Provides-Extra: demo
29
+ Requires-Dist: streamlit>=1.30; extra == "demo"
30
+ Provides-Extra: music21
31
+ Requires-Dist: music21>=9; extra == "music21"
32
+ Provides-Extra: partitura
33
+ Requires-Dist: partitura>=1.3; extra == "partitura"
34
+ Provides-Extra: ms3
35
+ Requires-Dist: ms3>=2.0; extra == "ms3"
36
+ Provides-Extra: flexohr
37
+ Requires-Dist: flexohr>=1; extra == "flexohr"
38
+ Provides-Extra: bps
39
+ Requires-Dist: pandas>=1.5; extra == "bps"
40
+ Requires-Dist: openpyxl>=3; extra == "bps"
41
+ Provides-Extra: notebooks
42
+ Requires-Dist: jupytext>=1.16; extra == "notebooks"
43
+ Requires-Dist: nbconvert>=7; extra == "notebooks"
44
+ Requires-Dist: ipykernel>=6; extra == "notebooks"
45
+ Dynamic: license-file
46
+
47
+ # hamonpy
48
+
49
+ We implement the **HAMON** standard — **Ha**rmony **Mo**del and **N**otation — in Python.
50
+
51
+ We design this module to work well in a conda environment.
52
+
53
+ ## We install
54
+
55
+ This package lives in the `hamonpy/` subdirectory of the repo (the repo root is not a
56
+ Python package).
57
+
58
+ **Using it** — once published to PyPI (after ICCCM'26):
59
+
60
+ ```bash
61
+ pip install hamonpy
62
+ ```
63
+
64
+ **Contributing** (and the only way until the PyPI release) — clone the full repo and
65
+ install editable with the dev extra, from the repository root:
66
+
67
+ ```bash
68
+ conda create -n hamonpy python=3.11
69
+ conda activate hamonpy
70
+ python -m pip install -e "./hamonpy[dev]"
71
+ ```
72
+
73
+ Changes land through **pull requests** (branch, push, open a PR — no direct commits to
74
+ `main`); see [`CONTRIBUTING.md`](../CONTRIBUTING.md) for the full workflow.
75
+
76
+ ## We run unit tests
77
+
78
+ ```bash
79
+ pytest -q
80
+ ```
81
+
82
+ ## We parse
83
+
84
+ We ship an **ANTLR4-based parser** generated from the normative grammars (`antlr/hamonLexer.g4` + `antlr/hamonParser.g4`, kept in sync with `grammar/hamon.ebnf`). It parses the full HAMON surface — chord symbols, Roman numerals, Nashville, figured bass, functional labels, positions, alternatives, and rendering dictionaries — into the typed AST in `hamonpy/ast.py`. Labels that can't be parsed with confidence are preserved losslessly as `unparsedHarmony`.
@@ -0,0 +1,38 @@
1
+ # hamonpy
2
+
3
+ We implement the **HAMON** standard — **Ha**rmony **Mo**del and **N**otation — in Python.
4
+
5
+ We design this module to work well in a conda environment.
6
+
7
+ ## We install
8
+
9
+ This package lives in the `hamonpy/` subdirectory of the repo (the repo root is not a
10
+ Python package).
11
+
12
+ **Using it** — once published to PyPI (after ICCCM'26):
13
+
14
+ ```bash
15
+ pip install hamonpy
16
+ ```
17
+
18
+ **Contributing** (and the only way until the PyPI release) — clone the full repo and
19
+ install editable with the dev extra, from the repository root:
20
+
21
+ ```bash
22
+ conda create -n hamonpy python=3.11
23
+ conda activate hamonpy
24
+ python -m pip install -e "./hamonpy[dev]"
25
+ ```
26
+
27
+ Changes land through **pull requests** (branch, push, open a PR — no direct commits to
28
+ `main`); see [`CONTRIBUTING.md`](../CONTRIBUTING.md) for the full workflow.
29
+
30
+ ## We run unit tests
31
+
32
+ ```bash
33
+ pytest -q
34
+ ```
35
+
36
+ ## We parse
37
+
38
+ We ship an **ANTLR4-based parser** generated from the normative grammars (`antlr/hamonLexer.g4` + `antlr/hamonParser.g4`, kept in sync with `grammar/hamon.ebnf`). It parses the full HAMON surface — chord symbols, Roman numerals, Nashville, figured bass, functional labels, positions, alternatives, and rendering dictionaries — into the typed AST in `hamonpy/ast.py`. Labels that can't be parsed with confidence are preserved losslessly as `unparsedHarmony`.
@@ -0,0 +1,5 @@
1
+ """We implement hamon parsing/normalization and adapters in Python."""
2
+
3
+ from .parse import parse_hamon, parse_hamon_sequence
4
+
5
+ __all__ = ["parse_hamon", "parse_hamon_sequence"]
@@ -0,0 +1,5 @@
1
+ """Enable `python -m hamonpy ...`."""
2
+ from .cli import main
3
+
4
+ if __name__ == "__main__":
5
+ raise SystemExit(main())
@@ -0,0 +1,20 @@
1
+ """We collect adapters for MEI, MusicXML, Humdrum/**kern, ABC, LilyPond, MuseScore, and music21."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any, Callable, Dict, List
7
+
8
+ from ..ast import HarmonyGroup
9
+
10
+ @dataclass
11
+ class Adapter:
12
+ name: str
13
+ from_: Callable[[Any], List[HarmonyGroup]]
14
+ to: Callable[[List[HarmonyGroup]], Any]
15
+
16
+ registry: Dict[str, Adapter] = {}
17
+
18
+
19
+ def register(adapter: Adapter) -> None:
20
+ registry[adapter.name] = adapter
@@ -0,0 +1,161 @@
1
+ """BPS-FH adapter — Beethoven Piano Sonatas Functional Harmony (Chen & Su) → HamonSequence.
2
+
3
+ The BPS-FH dataset (https://github.com/Tsung-Ping/functional-harmony) ships one
4
+ ``chords.xlsx`` per movement with seven unlabelled columns:
5
+
6
+ onset | offset | key | degree | quality | inversion | roman
7
+
8
+ where ``key`` is a letter (upper = major, lower = minor) with ``-`` = flat / ``+`` =
9
+ sharp (e.g. ``A-`` = A♭ major, ``c+`` = C♯ minor); ``degree`` is a scale degree
10
+ (``1``–``7``, optionally ``-``/``+`` altered and ``P/S`` for a secondary, e.g. ``5/5``);
11
+ ``quality`` ∈ {M, m, D7, M7, m7, d, d7, h7, a, a6}; ``inversion`` ∈ {0,1,2,3}; and the
12
+ last column is the analysts' Roman-numeral string.
13
+
14
+ This adapter reconstructs a **canonical HAMON Roman surface** from the structured
15
+ ``degree``/``quality``/``inversion`` columns (so ``°``/``ø``/``+`` and figured-bass tails
16
+ match HAMON's grammar), parses it into the rn/degree layer, attaches each chord's onset
17
+ as a time ``Position``, and turns key changes into ``TonalRegion``s (first = home key,
18
+ later = modulation). Augmented-sixth chords (``a6``: It/Ger/Fr) have no HAMON Roman
19
+ vocabulary yet — their original label (``It+6``…) is preserved as the surface (text).
20
+
21
+ Reading ``.xlsx`` needs ``openpyxl`` (``pip install -e ./hamonpy[bps]``).
22
+ """
23
+ from __future__ import annotations
24
+
25
+ from dataclasses import replace
26
+ from fractions import Fraction as _Fraction
27
+ from pathlib import Path
28
+ from typing import List, Optional
29
+
30
+ from hamonpy.ast import (
31
+ Fraction, HamonSequence, HarmonyGroup, HarmonyLabel, Key, PitchClass,
32
+ Position, RenderingHints, TextSemantic, TonalRegion,
33
+ )
34
+ from hamonpy.parse import parse_hamon_sequence
35
+
36
+ _ROMAN = {1: "I", 2: "II", 3: "III", 4: "IV", 5: "V", 6: "VI", 7: "VII"}
37
+
38
+ # quality -> (case, is_seventh, quality_glyph)
39
+ _QUALITY = {
40
+ "M": ("upper", False, ""),
41
+ "m": ("lower", False, ""),
42
+ "a": ("upper", False, "+"),
43
+ "d": ("lower", False, "°"),
44
+ "D7": ("upper", True, ""),
45
+ "M7": ("upper", True, ""),
46
+ "m7": ("lower", True, ""),
47
+ "d7": ("lower", True, "°"),
48
+ "h7": ("lower", True, "ø"),
49
+ }
50
+ _TRIAD_FIG = {0: "", 1: "6", 2: "64"}
51
+ _SEVENTH_FIG = {0: "7", 1: "65", 2: "43", 3: "42"}
52
+
53
+
54
+ def _parse_key(s: str) -> Optional[Key]:
55
+ s = (s or "").strip()
56
+ if not s or not s[0].isalpha():
57
+ return None
58
+ mode = "minor" if s[0].islower() else "major"
59
+ acc = {"-": "flat", "+": "sharp"}.get(s[1], None) if len(s) > 1 else None
60
+ return Key(tonic=PitchClass(note=s[0].upper(), accidental=acc), mode=mode)
61
+
62
+
63
+ def _degree_part_to_roman(part: str, case: str) -> Optional[str]:
64
+ part = part.strip()
65
+ acc = ""
66
+ if part and part[0] in "+-":
67
+ acc = "#" if part[0] == "+" else "b"
68
+ part = part[1:]
69
+ if not part.isdigit() or int(part) not in _ROMAN:
70
+ return None
71
+ roman = _ROMAN[int(part)]
72
+ return acc + (roman.lower() if case == "lower" else roman)
73
+
74
+
75
+ def _row_to_roman_parts(degree: str, quality: str, inversion: int):
76
+ """Return ``(primary_surface, secondary_roman_or_None)`` for a BPS-FH row, or
77
+ ``None`` for unsupported qualities (a6). ``primary_surface`` is a HAMON Roman the
78
+ grammar parses on its own; the secondary is attached separately because HAMON's
79
+ Roman grammar rejects flat-prefixed secondaries (e.g. ``/bVII``)."""
80
+ if quality not in _QUALITY:
81
+ return None # a6 (augmented sixth) and any future quality
82
+ case, is_seventh, glyph = _QUALITY[quality]
83
+ primary, _, secondary = degree.partition("/")
84
+ base = _degree_part_to_roman(primary, case)
85
+ if base is None:
86
+ return None
87
+ fig = (_SEVENTH_FIG if is_seventh else _TRIAD_FIG).get(inversion, "7" if is_seventh else "")
88
+ primary_surface = base + glyph + fig
89
+ sec = _degree_part_to_roman(secondary, "upper") if secondary else None
90
+ return primary_surface, sec
91
+
92
+
93
+ def _to_fraction(value) -> Optional[Fraction]:
94
+ try:
95
+ fr = _Fraction(float(value)).limit_denominator(960)
96
+ except (TypeError, ValueError):
97
+ return None
98
+ return Fraction(numerator=fr.numerator, denominator=fr.denominator)
99
+
100
+
101
+ def _rows_to_hamon(rows) -> HamonSequence:
102
+ """rows: iterable of (onset, key, degree, quality, inversion, roman_label)."""
103
+ groups: List[HarmonyGroup] = []
104
+ regions: List[TonalRegion] = []
105
+ open_key: Optional[int] = None
106
+ last_key_str: Optional[str] = None
107
+
108
+ for onset, key_str, degree, quality, inversion, roman_label in rows:
109
+ key_str = (str(key_str) if key_str is not None else "").strip()
110
+ if key_str and key_str != last_key_str:
111
+ key = _parse_key(key_str)
112
+ if key is not None:
113
+ gi = len(groups)
114
+ if open_key is not None and gi > 0:
115
+ regions[open_key].to_group = gi - 1
116
+ regions.append(TonalRegion(
117
+ key=key, kind=("key" if open_key is None else "modulation"), from_group=gi,
118
+ ))
119
+ open_key = len(regions) - 1
120
+ last_key_str = key_str
121
+
122
+ parts = _row_to_roman_parts(str(degree), str(quality).strip(), int(inversion))
123
+ label = None
124
+ if parts is not None:
125
+ primary_surface, secondary = parts
126
+ parsed = parse_hamon_sequence("@rn\n" + primary_surface).groups
127
+ if parsed and parsed[0].primary[0].semantic.kind == "roman":
128
+ label = parsed[0].primary[0]
129
+ full = f"{primary_surface}/{secondary}" if secondary else primary_surface
130
+ label = replace(label, surface=full)
131
+ if secondary:
132
+ label = replace(label, semantic=replace(label.semantic, secondary=secondary))
133
+ if label is None: # a6 / unparseable: preserve the analysts' original label
134
+ label = HarmonyLabel(
135
+ surface=str(roman_label), semantic=TextSemantic(text=str(roman_label)),
136
+ rendering=RenderingHints(), detected_system="text", system="text",
137
+ sequence_system_hint="rn",
138
+ )
139
+ pos = _to_fraction(onset)
140
+ groups.append(HarmonyGroup(
141
+ primary=[label], position=Position(time=pos) if pos is not None else None,
142
+ ))
143
+
144
+ return HamonSequence(groups=groups, sequence_system_hint="rn", regions=regions or None)
145
+
146
+
147
+ def bps_fh_chords_file_to_hamon(path: str) -> HamonSequence:
148
+ """Convert one BPS-FH ``chords.xlsx`` (7 unlabelled columns) into a HamonSequence."""
149
+ try:
150
+ import pandas as pd # noqa: PLC0415 - optional, only needed for .xlsx
151
+ except ImportError as exc: # pragma: no cover
152
+ raise ImportError("Reading BPS-FH .xlsx needs pandas+openpyxl: "
153
+ "pip install -e ./hamonpy[bps]") from exc
154
+ df = pd.read_excel(path, header=None)
155
+ rows = ((r[0], r[2], r[3], r[4], r[5], r[6]) for _, r in df.iterrows())
156
+ return _rows_to_hamon(rows)
157
+
158
+
159
+ def bps_fh_movement_to_hamon(folder: str) -> HamonSequence:
160
+ """Convert a BPS-FH movement folder (uses ``<folder>/chords.xlsx``)."""
161
+ return bps_fh_chords_file_to_hamon(str(Path(folder) / "chords.xlsx"))