chordseq 0.0.2__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.
@@ -0,0 +1,58 @@
1
+ # wads CI — calls the reusable workflow hosted in i2mint/wads.
2
+ #
3
+ # All configuration comes from this repo's pyproject.toml [tool.wads.ci.*].
4
+ # To customize the workflow itself (rare), replace this file with the
5
+ # full inline template `wads/data/github_ci_uv.yml` from i2mint/wads.
6
+ #
7
+ # Pinning: `@master` floats with wads. If you need a stable job graph for
8
+ # a release-sensitive repo, change `@master` to a wads tag (e.g. `@0.2.15`;
9
+ # tags have no `v` prefix). That freezes this workflow, not the actions it
10
+ # calls, which still run at `@master`.
11
+ # CI failure does not block a published release — it blocks the publish
12
+ # step itself — so floating master is generally safe.
13
+ #
14
+ # Permissions: GitHub validates that the caller grants AT LEAST the
15
+ # permissions any job in the called workflow requests — at workflow-parse
16
+ # time, not at run-time, even if the job would be skipped via `if:`.
17
+ # The reusable workflow needs:
18
+ # contents: write for the publish job's version-bump push-back
19
+ # and for the github-pages job's gh-pages branch push
20
+ # pages: write for the github-pages job's REST API Pages config
21
+ # Both default to `write` on org-account GITHUB_TOKEN and need to be
22
+ # granted explicitly on personal-account callers (where the default is
23
+ # read-only). No `id-token: write` needed — the publish-github-pages
24
+ # action uses peaceiris/actions-gh-pages (branch-based) + REST API,
25
+ # not the OIDC `actions/deploy-pages` flow.
26
+ name: Continuous Integration
27
+ on:
28
+ push:
29
+ pull_request:
30
+ jobs:
31
+ ci:
32
+ uses: i2mint/wads/.github/workflows/uv-ci.yml@master
33
+ permissions:
34
+ contents: write
35
+ pages: write
36
+ # Transport (named): passes ONLY the secrets listed below — PYPI_PASSWORD
37
+ # (for the publish job) plus the secret behind each env var declared in
38
+ # [tool.wads.ci.env]. `wads-secrets add VAR_NAME` declares a var and adds
39
+ # its secret here. Every listed name must be declared by the reusable
40
+ # workflow (the superset in wads/ci_secrets.py) or GitHub rejects this
41
+ # workflow at parse time; a missing name is a one-line addition there.
42
+ # (Cross-owner `secrets: inherit` does not propagate secrets, so it
43
+ # cannot replace this list.)
44
+ #
45
+ # Opt-in alternative: `wads-migrate ci-to-stub --transport json` passes
46
+ # this repo's WHOLE secrets context — every secret it can read, including
47
+ # org-level ones — as one WADS_CI_SECRETS_JSON secret. GitHub's
48
+ # malicious-workflow scanner may hold runs that do that: `action_required`,
49
+ # zero jobs, no log (i2mint/wads#74, #101).
50
+ #
51
+ # *Which* of these become job env vars — and which are required — is
52
+ # driven entirely by [tool.wads.ci.env] in pyproject.toml; nothing is
53
+ # exported unless declared there. Non-sensitive values don't need a secret:
54
+ # use [tool.wads.ci.env].defaults (committed literals) or a repository
55
+ # *variable* (`gh variable set NAME`) — declared names fall back to
56
+ # repo variables automatically.
57
+ secrets:
58
+ PYPI_PASSWORD: ${{ secrets.PYPI_PASSWORD }}
@@ -0,0 +1,129 @@
1
+ .claude/handoffs/
2
+ .claude/scratch/
3
+
4
+ # Byte-compiled / optimized / DLL files
5
+ __pycache__/
6
+ *.py[cod]
7
+ *$py.class
8
+
9
+
10
+ .DS_Store
11
+ # C extensions
12
+ *.so
13
+
14
+ # TLS certificates
15
+ ## Ignore all PEM files anywhere
16
+ *.pem
17
+ ## Also ignore any certs directory
18
+ certs/
19
+
20
+ # Distribution / packaging
21
+ .Python
22
+ build/
23
+ develop-eggs/
24
+ dist/
25
+ downloads/
26
+ eggs/
27
+ .eggs/
28
+ lib/
29
+ lib64/
30
+ parts/
31
+ sdist/
32
+ var/
33
+ wheels/
34
+ *.egg-info/
35
+ .installed.cfg
36
+ *.egg
37
+ MANIFEST
38
+ _build
39
+
40
+ # PyInstaller
41
+ # Usually these files are written by a python script from a template
42
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
43
+ *.manifest
44
+ *.spec
45
+
46
+ # Installer logs
47
+ pip-log.txt
48
+ pip-delete-this-directory.txt
49
+
50
+ # Unit test / coverage reports
51
+ htmlcov/
52
+ .tox/
53
+ .coverage
54
+ .coverage.*
55
+ .cache
56
+ nosetests.xml
57
+ coverage.xml
58
+ *.cover
59
+ .hypothesis/
60
+ .pytest_cache/
61
+
62
+ # Translations
63
+ *.mo
64
+ *.pot
65
+
66
+ # Django stuff:
67
+ *.log
68
+ local_settings.py
69
+ db.sqlite3
70
+
71
+ # Flask stuff:
72
+ instance/
73
+ .webassets-cache
74
+
75
+ # Scrapy stuff:
76
+ .scrapy
77
+
78
+ # Sphinx documentation
79
+ docs/_build/
80
+ docs/*
81
+
82
+ # PyBuilder
83
+ target/
84
+
85
+ # Jupyter Notebook
86
+ .ipynb_checkpoints
87
+
88
+ # pyenv
89
+ .python-version
90
+
91
+ # celery beat schedule file
92
+ celerybeat-schedule
93
+
94
+ # SageMath parsed files
95
+ *.sage.py
96
+
97
+ # Environments
98
+ .env
99
+ .venv
100
+ env/
101
+ venv/
102
+ ENV/
103
+ env.bak/
104
+ venv.bak/
105
+
106
+ # Spyder project settings
107
+ .spyderproject
108
+ .spyproject
109
+
110
+ # Rope project settings
111
+ .ropeproject
112
+
113
+ # mkdocs documentation
114
+ /site
115
+
116
+ # mypy
117
+ .mypy_cache/
118
+
119
+ # PyCharm
120
+ .idea
121
+ __pycache__/
122
+ *.egg-info/
123
+ dist/
124
+ .venv/
125
+ .pytest_cache/
126
+ .ruff_cache/
127
+
128
+ # Node / the TypeScript twin (ts/)
129
+ node_modules/
chordseq-0.0.2/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Thor Whalen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.5
2
+ Name: chordseq
3
+ Version: 0.0.2
4
+ Summary: Chord-progression search in any key, n-gram counts and Roman numerals over chord-symbol sequences
5
+ Project-URL: Homepage, https://github.com/thorwhalen/chordseq
6
+ Project-URL: Repository, https://github.com/thorwhalen/chordseq
7
+ Project-URL: Documentation, https://thorwhalen.github.io/chordseq
8
+ Author: Thor Whalen
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: chords,harmony,music,n-grams,search
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Multimedia :: Sound/Audio
15
+ Requires-Python: >=3.10
16
+ Requires-Dist: chordsym>=0.0.8
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest-cov>=4.0; extra == 'dev'
19
+ Requires-Dist: pytest>=7.0; extra == 'dev'
20
+ Requires-Dist: ruff>=0.1.0; extra == 'dev'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # chordseq
24
+
25
+ Search chord progressions in any key, count n-grams, and name chords by key. Pure Python, one dependency ([chordsym](https://pypi.org/project/chordsym/)).
26
+
27
+ ```python
28
+ >>> from chordseq import find, ngrams
29
+ >>> sequence = ["Dm", "Bb", "F", "C", "Dm", "Bb", "F", "C"]
30
+ >>> [(m.start, m.stop) for m in find("vi IV I V", sequence)] # Roman numerals: any key
31
+ [(0, 4), (4, 8)]
32
+ >>> [m.transposition for m in find("Am F C G", sequence)] # chord symbols: any key too
33
+ [5, 5]
34
+ ```
35
+
36
+ `pip install chordseq`
37
+
38
+ ## One-command test on real data
39
+
40
+ ```bash
41
+ pytest tests/test_smoke.py
42
+ ```
43
+
44
+ It reads the first Chordonomicon progressions over the public datasets-server API (standard library only; skipped offline), searches them and counts their 4-grams. The same by hand:
45
+
46
+ ```python
47
+ from chordseq import find, ngrams
48
+
49
+ progressions = [row.split() for row in chordonomicon_rows] # "<verse_1> C G Amin F ..."
50
+ hits = [m for p in progressions for m in find("Amin F C G", p, dialect="chordonomicon")]
51
+ ngrams(progressions, n=4, dialect="chordonomicon").most_common(5)
52
+ ```
53
+
54
+ ## The query
55
+
56
+ Whitespace-separated items, like a regular expression over chords:
57
+
58
+ | Item | Means |
59
+ |---|---|
60
+ | `Am`, `E7`, `F#m7b5` | a chord symbol |
61
+ | `vi`, `V7`, `bVII`, `ii`, `viiø7` | a Roman numeral (upper major, lower minor, `°` `ø` `+` `sus`) |
62
+ | `.` | any one chord |
63
+ | `E\|E7` | either (no spaces) |
64
+ | `E7?` | optional |
65
+ | `*` (alone, or after an item) | any run of chords, as few as will do |
66
+
67
+ `E(7)` is refused with a hint: parentheses already mean alterations in chord symbols. Chord symbols and Roman numerals do not mix in a query.
68
+
69
+ ## Defaults
70
+
71
+ `level="triads"` (`E` matches `E7`; `"root"` and `"tetrads"` are the other mir_eval levels), transposition-invariant, inversions ignored, repeated chords collapsed. `transposition_invariant=False` matches the query's own key: chord symbols as written, Roman numerals against `key=`.
72
+
73
+ ## Sequences, payloads, matches
74
+
75
+ A sequence is an iterable of chord symbols, each optionally `(symbol, payload)` with any payload you like (a time, a bar, a page). `find(query, sequence)` returns `Match` objects: `start`/`stop` are indices into the sequence as you gave it (so collapsed repeats are covered), `items`, `symbols`, `payloads`, `transposition`. `search(query, sequences)` does many sequences lazily, with `sequence_index`. The engine knows nothing about audio, pages or songs; you map spans to times or pages through the payloads. Anything that is not a chord (`N`, `<verse_1>`) matches nothing, so no match runs across it: cut a song into sections and the matches stay inside them.
76
+
77
+ ## N-grams and Roman numerals
78
+
79
+ ```python
80
+ ngrams(sequences, n=(2, 3, 4)) # pooled Counter of tuples, in the key of each sequence
81
+ ngrams(
82
+ sequences, relative_to="first"
83
+ ) # keyless: numerals from each n-gram's first chord
84
+ ngrams(sequences, relative_to=None, per_sequence=True)
85
+ to_roman_sequence(["G", "D", "Em", "C"]) # ['I', 'V', 'vi', 'IV']
86
+ ```
87
+
88
+ Roman numerals use one chromatic scheme from the tonic, major or minor key alike (`bIII`, `bVI`, `bVII` in a minor key), so `to_roman` and the query read each other.
89
+
90
+ ## Seams
91
+
92
+ | Seam | Keyword | Default | Replacement that exists |
93
+ |---|---|---|---|
94
+ | Chord spelling of the input | `dialect=` | `"default"` (chart spellings) | `chordsym.DIALECTS` (`chordonomicon`, `harte`), `chordsym.register_dialect` |
95
+ | Detail of comparison | `level=` | `"triads"` | `"root"`, `"tetrads"` (mir_eval names) |
96
+ | Key for Roman numerals | `key=` | estimated by `chordsym.estimate_key` | any `chordsym.Key` |
97
+
98
+ **NOT seams (v1):** the scan engine (one regex pass per transposition over a string of one-character tokens; the packed-byte numpy scan of the phase-1 prototypes, in `misc/docs/research/prototypes/`, is the replacement when a corpus-sized consumer needs it, and then it lands behind the same `search` signature); an index; ranking and popularity; a browser or Web Worker build; a CLI; audio, pages and songs (callers map spans through payloads); chord symbols beyond what `chordsym` parses.
99
+
100
+ ## Design and research
101
+
102
+ The phase-1 design, five research reports and prototypes are in `misc/docs/research/`.
@@ -0,0 +1,80 @@
1
+ # chordseq
2
+
3
+ Search chord progressions in any key, count n-grams, and name chords by key. Pure Python, one dependency ([chordsym](https://pypi.org/project/chordsym/)).
4
+
5
+ ```python
6
+ >>> from chordseq import find, ngrams
7
+ >>> sequence = ["Dm", "Bb", "F", "C", "Dm", "Bb", "F", "C"]
8
+ >>> [(m.start, m.stop) for m in find("vi IV I V", sequence)] # Roman numerals: any key
9
+ [(0, 4), (4, 8)]
10
+ >>> [m.transposition for m in find("Am F C G", sequence)] # chord symbols: any key too
11
+ [5, 5]
12
+ ```
13
+
14
+ `pip install chordseq`
15
+
16
+ ## One-command test on real data
17
+
18
+ ```bash
19
+ pytest tests/test_smoke.py
20
+ ```
21
+
22
+ It reads the first Chordonomicon progressions over the public datasets-server API (standard library only; skipped offline), searches them and counts their 4-grams. The same by hand:
23
+
24
+ ```python
25
+ from chordseq import find, ngrams
26
+
27
+ progressions = [row.split() for row in chordonomicon_rows] # "<verse_1> C G Amin F ..."
28
+ hits = [m for p in progressions for m in find("Amin F C G", p, dialect="chordonomicon")]
29
+ ngrams(progressions, n=4, dialect="chordonomicon").most_common(5)
30
+ ```
31
+
32
+ ## The query
33
+
34
+ Whitespace-separated items, like a regular expression over chords:
35
+
36
+ | Item | Means |
37
+ |---|---|
38
+ | `Am`, `E7`, `F#m7b5` | a chord symbol |
39
+ | `vi`, `V7`, `bVII`, `ii`, `viiø7` | a Roman numeral (upper major, lower minor, `°` `ø` `+` `sus`) |
40
+ | `.` | any one chord |
41
+ | `E\|E7` | either (no spaces) |
42
+ | `E7?` | optional |
43
+ | `*` (alone, or after an item) | any run of chords, as few as will do |
44
+
45
+ `E(7)` is refused with a hint: parentheses already mean alterations in chord symbols. Chord symbols and Roman numerals do not mix in a query.
46
+
47
+ ## Defaults
48
+
49
+ `level="triads"` (`E` matches `E7`; `"root"` and `"tetrads"` are the other mir_eval levels), transposition-invariant, inversions ignored, repeated chords collapsed. `transposition_invariant=False` matches the query's own key: chord symbols as written, Roman numerals against `key=`.
50
+
51
+ ## Sequences, payloads, matches
52
+
53
+ A sequence is an iterable of chord symbols, each optionally `(symbol, payload)` with any payload you like (a time, a bar, a page). `find(query, sequence)` returns `Match` objects: `start`/`stop` are indices into the sequence as you gave it (so collapsed repeats are covered), `items`, `symbols`, `payloads`, `transposition`. `search(query, sequences)` does many sequences lazily, with `sequence_index`. The engine knows nothing about audio, pages or songs; you map spans to times or pages through the payloads. Anything that is not a chord (`N`, `<verse_1>`) matches nothing, so no match runs across it: cut a song into sections and the matches stay inside them.
54
+
55
+ ## N-grams and Roman numerals
56
+
57
+ ```python
58
+ ngrams(sequences, n=(2, 3, 4)) # pooled Counter of tuples, in the key of each sequence
59
+ ngrams(
60
+ sequences, relative_to="first"
61
+ ) # keyless: numerals from each n-gram's first chord
62
+ ngrams(sequences, relative_to=None, per_sequence=True)
63
+ to_roman_sequence(["G", "D", "Em", "C"]) # ['I', 'V', 'vi', 'IV']
64
+ ```
65
+
66
+ Roman numerals use one chromatic scheme from the tonic, major or minor key alike (`bIII`, `bVI`, `bVII` in a minor key), so `to_roman` and the query read each other.
67
+
68
+ ## Seams
69
+
70
+ | Seam | Keyword | Default | Replacement that exists |
71
+ |---|---|---|---|
72
+ | Chord spelling of the input | `dialect=` | `"default"` (chart spellings) | `chordsym.DIALECTS` (`chordonomicon`, `harte`), `chordsym.register_dialect` |
73
+ | Detail of comparison | `level=` | `"triads"` | `"root"`, `"tetrads"` (mir_eval names) |
74
+ | Key for Roman numerals | `key=` | estimated by `chordsym.estimate_key` | any `chordsym.Key` |
75
+
76
+ **NOT seams (v1):** the scan engine (one regex pass per transposition over a string of one-character tokens; the packed-byte numpy scan of the phase-1 prototypes, in `misc/docs/research/prototypes/`, is the replacement when a corpus-sized consumer needs it, and then it lands behind the same `search` signature); an index; ranking and popularity; a browser or Web Worker build; a CLI; audio, pages and songs (callers map spans through payloads); chord symbols beyond what `chordsym` parses.
77
+
78
+ ## Design and research
79
+
80
+ The phase-1 design, five research reports and prototypes are in `misc/docs/research/`.
@@ -0,0 +1,30 @@
1
+ """chordseq: search chord progressions in any key, count n-grams, name chords by key.
2
+
3
+ >>> from chordseq import find, ngrams, to_roman_sequence
4
+ >>> [(m.start, m.stop) for m in find("Am F C", ["Dm", "Bb", "F", "G", "Em", "Bb", "G"])]
5
+ [(0, 3)]
6
+ >>> to_roman_sequence(["G", "D", "Em", "C", "G"])
7
+ ['I', 'V', 'vi', 'IV', 'I']
8
+ >>> ngrams([["C", "G", "Am", "F"]], n=2).most_common(2)
9
+ [(('I', 'V'), 1), (('V', 'vi'), 1)]
10
+ """
11
+
12
+ from chordseq.ngrams import ngrams
13
+ from chordseq.query import Query, QueryError, parse_query
14
+ from chordseq.roman import parse_roman, to_roman, to_roman_sequence
15
+ from chordseq.search import Match, find, search
16
+ from chordseq.tokens import LEVELS
17
+
18
+ __all__ = [
19
+ "LEVELS",
20
+ "Match",
21
+ "Query",
22
+ "QueryError",
23
+ "find",
24
+ "ngrams",
25
+ "parse_query",
26
+ "parse_roman",
27
+ "search",
28
+ "to_roman",
29
+ "to_roman_sequence",
30
+ ]
@@ -0,0 +1,121 @@
1
+ """N-gram counts of chord progressions, in the same alphabet the search uses.
2
+
3
+ Each sequence is tokenised as in :mod:`chordseq.search` (level, repeats collapsed), windows
4
+ of ``n`` chords are counted, and a window that holds a non-chord is skipped. How an n-gram is
5
+ *named* decides what counts as the same progression:
6
+
7
+ - ``relative_to="key"`` (default): Roman numerals in the sequence's key (estimated by
8
+ ``chordsym.estimate_key`` unless ``key=`` is given); ``I V vi IV`` however it is transposed.
9
+ - ``relative_to="first"``: Roman numerals measured from the n-gram's first chord, so no key is
10
+ needed (``vi IV I V`` becomes ``I bVI bIII bVII``).
11
+ - ``relative_to=None``: absolute chord names (``Am F C G``).
12
+
13
+ >>> seqs = [["C", "G", "Am", "F", "C", "G", "Am", "F"], ["D", "A", "Bm", "G"]]
14
+ >>> counts = ngrams(seqs, n=4)
15
+ >>> counts[("I", "V", "vi", "IV")], counts[("V", "vi", "IV", "I")]
16
+ (3, 1)
17
+ >>> ngrams(seqs, n=2, relative_to=None)[("C", "G")]
18
+ 2
19
+ >>> ngrams(seqs, n=2, per_sequence=True)[1][("I", "V")]
20
+ 1
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from collections import Counter
26
+ from collections.abc import Iterable
27
+
28
+ from chordsym import Dialect, Key, estimate_key
29
+
30
+ from chordseq.roman import roman_from_parts
31
+ from chordseq.tokens import (
32
+ DEFAULT_LEVEL,
33
+ SEVENTHS,
34
+ TRIADS,
35
+ check_level,
36
+ encode,
37
+ split_item,
38
+ token_parts,
39
+ )
40
+
41
+ DEFAULT_SIZES = (2, 3, 4)
42
+ _RELATIVE_TO = ("key", "first", None)
43
+ _ROOT_NAMES = ("C", "C#", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B")
44
+ _TRIAD_SUFFIX = {
45
+ "major": "",
46
+ "minor": "m",
47
+ "diminished": "dim",
48
+ "augmented": "aug",
49
+ "open": "sus",
50
+ }
51
+ _SEVENTH_SUFFIX = {"": "", "7": "7", "maj7": "maj7", "dim7": "7"}
52
+
53
+
54
+ def _chord_name(parts) -> str:
55
+ root, triad, seventh = parts
56
+ kind, sev = TRIADS[triad], SEVENTHS[seventh]
57
+ if kind == "diminished" and sev:
58
+ return _ROOT_NAMES[root] + ("dim7" if sev == "dim7" else "m7b5")
59
+ return _ROOT_NAMES[root] + _TRIAD_SUFFIX[kind] + _SEVENTH_SUFFIX[sev]
60
+
61
+
62
+ def ngrams(
63
+ sequences: Iterable[Iterable],
64
+ n: int | Iterable[int] = DEFAULT_SIZES,
65
+ *,
66
+ level: str = DEFAULT_LEVEL,
67
+ collapse: bool = True,
68
+ relative_to: str | None = "key",
69
+ key: Key | None = None,
70
+ per_sequence: bool = False,
71
+ dialect: str | Dialect = "default",
72
+ ) -> Counter | list[Counter]:
73
+ """Counts of n-grams (tuples of chord names) pooled over ``sequences``.
74
+
75
+ ``n`` is one size or several (default 2, 3 and 4). With ``per_sequence=True`` the result is
76
+ one :class:`~collections.Counter` per sequence, in order, instead of one pooled counter.
77
+ """
78
+ check_level(level)
79
+ if relative_to not in _RELATIVE_TO:
80
+ raise ValueError(
81
+ f"relative_to must be one of {_RELATIVE_TO}, not {relative_to!r}"
82
+ )
83
+ sizes = (n,) if isinstance(n, int) else tuple(n)
84
+ if not sizes or min(sizes) < 1:
85
+ raise ValueError(f"n-gram sizes must be positive, not {sizes!r}")
86
+ results = [
87
+ _count(seq, sizes, level, collapse, relative_to, key, dialect)
88
+ for seq in sequences
89
+ ]
90
+ if per_sequence:
91
+ return results
92
+ pooled: Counter = Counter()
93
+ for counter in results:
94
+ pooled.update(counter)
95
+ return pooled
96
+
97
+
98
+ def _count(sequence, sizes, level, collapse, relative_to, key, dialect) -> Counter:
99
+ items = list(sequence)
100
+ runs, _ = encode(items, level=level, collapse=collapse, dialect=dialect)
101
+ parts = [token_parts(char) for char, _, _ in runs]
102
+ if relative_to == "key" and key is None:
103
+ key = estimate_key((split_item(i)[0] for i in items), dialect=dialect)
104
+ counter: Counter = Counter()
105
+ for size in sizes:
106
+ for start in range(len(parts) - size + 1):
107
+ window = parts[start : start + size]
108
+ if None in window:
109
+ continue
110
+ counter[_name_window(window, relative_to, key, level)] += 1
111
+ return counter
112
+
113
+
114
+ def _name_window(window, relative_to, key, level) -> tuple[str, ...]:
115
+ if relative_to is None:
116
+ return tuple(_chord_name(p) for p in window)
117
+ tonic = window[0][0] if relative_to == "first" else key.tonic
118
+ return tuple(
119
+ roman_from_parts(((root - tonic) % 12, triad, seventh), level=level)
120
+ for root, triad, seventh in window
121
+ )
@@ -0,0 +1,96 @@
1
+ """The query notation: regex-shaped, over plain chord symbols or Roman numerals.
2
+
3
+ A query is whitespace-separated items:
4
+
5
+ - a chord symbol (``Am``, ``E7``, ``F#m7b5``) or a Roman numeral (``vi``, ``V7``, ``bVII``);
6
+ - ``.`` any one chord;
7
+ - ``|`` between alternatives in one item, no spaces (``E|E7``, ``V|bVII``);
8
+ - ``?`` after an item makes it optional (``E7?``); ``*`` after an item, or alone, any run of
9
+ chords (``.*`` and ``*`` are the same: zero or more chords, as few as will do).
10
+
11
+ ``E(7)`` is refused: parentheses already mean alterations in chord symbols. At the default
12
+ level (``triads``) ``E`` already matches ``E7``; write ``E|E7`` to be explicit, or search
13
+ at ``level="tetrads"`` to tell them apart. Chord symbols and Roman numerals do not mix in
14
+ one query. Chord symbols in a query use the default spelling.
15
+
16
+ >>> [item.text for item in parse_query("Am E7? F").items]
17
+ ['Am', 'E7?', 'F']
18
+ >>> parse_query("vi IV I V").roman
19
+ True
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import re
25
+ from dataclasses import dataclass
26
+
27
+ from chordsym import is_chord_token
28
+
29
+ from chordseq.roman import is_roman, parse_roman
30
+ from chordseq.tokens import Parts, chord_parts
31
+
32
+ _PAREN_SEVENTH_RE = re.compile(r"^[A-G][#b]?\(\d+\)")
33
+ _QUANTIFIERS = ("?", "*")
34
+
35
+
36
+ class QueryError(ValueError):
37
+ """A query that cannot be read; the message says which item and why."""
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class Item:
42
+ """One query item: alternatives (None = any chord) and a quantifier ('', '?' or '*')."""
43
+
44
+ text: str
45
+ alternatives: tuple[Parts, ...] | None
46
+ quantifier: str = ""
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class Query:
51
+ """A parsed query. ``roman`` is True when its atoms are degrees, not roots."""
52
+
53
+ items: tuple[Item, ...]
54
+ roman: bool
55
+
56
+
57
+ def _atom(text: str) -> tuple[Parts, bool]:
58
+ if _PAREN_SEVENTH_RE.match(text):
59
+ raise QueryError(
60
+ f"{text!r}: parentheses mean alterations in chord symbols; "
61
+ f"write {text[0]}|{text[0]}7 for 'with or without the seventh' "
62
+ "(at the default level, plain "
63
+ f"{text[0]} already matches {text[0]}7)"
64
+ )
65
+ if is_roman(text):
66
+ return parse_roman(text), True
67
+ if is_chord_token(text):
68
+ return chord_parts(text), False
69
+ raise QueryError(f"{text!r} is neither a chord symbol nor a Roman numeral")
70
+
71
+
72
+ def parse_query(text: str) -> Query:
73
+ """Read a query (see the module docstring for the notation); ``QueryError`` if it is not one."""
74
+ items: list[Item] = []
75
+ kinds: set[bool] = set()
76
+ for word in text.split():
77
+ quantifier = ""
78
+ body = word
79
+ if word == "*":
80
+ body, quantifier = ".", "*"
81
+ elif word[-1] in _QUANTIFIERS and len(word) > 1:
82
+ body, quantifier = word[:-1], word[-1]
83
+ if body == ".":
84
+ items.append(Item(word, None, quantifier))
85
+ continue
86
+ alternatives = []
87
+ for part in body.split("|"):
88
+ parts, is_degree = _atom(part)
89
+ kinds.add(is_degree)
90
+ alternatives.append(parts)
91
+ items.append(Item(word, tuple(alternatives), quantifier))
92
+ if not any(it.alternatives is not None for it in items):
93
+ raise QueryError(f"{text!r} names no chord")
94
+ if len(kinds) > 1:
95
+ raise QueryError(f"{text!r} mixes chord symbols and Roman numerals")
96
+ return Query(tuple(items), roman=kinds == {True})