amend-va 0.1.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.
- amend_va-0.1.0/LICENSE +202 -0
- amend_va-0.1.0/PKG-INFO +241 -0
- amend_va-0.1.0/README.md +222 -0
- amend_va-0.1.0/pyproject.toml +36 -0
- amend_va-0.1.0/pyproject.toml.orig +36 -0
- amend_va-0.1.0/src/amend/__init__.py +6 -0
- amend_va-0.1.0/src/amend/api.py +96 -0
- amend_va-0.1.0/src/amend/cli.py +58 -0
- amend_va-0.1.0/src/amend/judge.py +129 -0
- amend_va-0.1.0/src/amend/metric.py +48 -0
- amend_va-0.1.0/src/amend/prompts.py +94 -0
- amend_va-0.1.0/src/amend/py.typed +0 -0
amend_va-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
amend_va-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: amend-va
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: AMEND and AMEND@0: an LLM-judge minimum-edit metric for dictation tools
|
|
5
|
+
Author: manasdhir976
|
|
6
|
+
Author-email: manasdhir976 <manas@joshtalks.com>
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
12
|
+
Requires-Dist: anthropic>=2.6.0
|
|
13
|
+
Requires-Dist: jiwer>=4.0.0
|
|
14
|
+
Requires-Dist: pandas>=3.1.1
|
|
15
|
+
Requires-Python: >=3.11
|
|
16
|
+
Project-URL: Homepage, https://github.com/VoiceArenaAI/AMEND
|
|
17
|
+
Project-URL: Repository, https://github.com/VoiceArenaAI/AMEND
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# AMEND
|
|
21
|
+
|
|
22
|
+
**AMEND** (Aggregate Minimum Edits Needed per Draft) measures how much a user would have to fix in a dictation tool's output before it is usable.
|
|
23
|
+
|
|
24
|
+
Word error rate (WER) compares a transcript with a single reference, so it penalises every legitimate difference: digits vs words, a resolved self-correction, a reworded phrase. AMEND instead asks a different question: *given what the user meant to write, what is the smallest set of edits that makes this draft acceptable?*
|
|
25
|
+
|
|
26
|
+
## Inspiration: HTER
|
|
27
|
+
|
|
28
|
+
AMEND is inspired by **HTER** (Human-targeted Translation Edit Rate) from machine translation evaluation ([Snover et al., 2006](https://aclanthology.org/2006.amta-papers.25/)).
|
|
29
|
+
|
|
30
|
+
In HTER, a human annotator takes a system's translation and edits it, as little as possible, until it is fluent and means the same as the reference. That edited version becomes a *targeted reference* for that output. The score is the edit rate between the system output and its own targeted reference. Because the target is built from the output itself, a correct translation that is worded differently from the reference costs nothing. Only edits a human actually needed are counted.
|
|
31
|
+
|
|
32
|
+
AMEND applies the same idea to dictation, with an LLM judge in the role of the human annotator:
|
|
33
|
+
|
|
34
|
+
| | HTER | AMEND |
|
|
35
|
+
|---|---|---|
|
|
36
|
+
| Output being scored | MT translation | Dictation tool's draft |
|
|
37
|
+
| Ground truth | Reference translation | Intended text, plus the spoken text |
|
|
38
|
+
| Who builds the targeted reference | Human annotator | LLM judge (`claude-sonnet-5-5`) |
|
|
39
|
+
| Edit rate | TER (word level, with shifts) | CER (character level, via `jiwer`) |
|
|
40
|
+
|
|
41
|
+
## How it works
|
|
42
|
+
|
|
43
|
+
For each draft:
|
|
44
|
+
|
|
45
|
+
1. The judge receives the **spoken text** (a verbatim transcript of what the user said), the **intended text** and the **draft**.
|
|
46
|
+
2. It returns the draft with the **minimum edits** needed for it to serve the same purpose as the intended text.
|
|
47
|
+
3. Both the draft and the judge's version are normalised: Unicode NFKC, lowercased, sentence punctuation at word edges stripped, whitespace collapsed.
|
|
48
|
+
4. The character edits (substitutions + deletions + insertions) needed to turn the draft into the judge's version are counted with `jiwer`, along with the number of characters in the judge's version. Spaces count as characters.
|
|
49
|
+
|
|
50
|
+
Two numbers summarise a set of drafts:
|
|
51
|
+
|
|
52
|
+
- **AMEND**: corpus-level character edit rate, pooled over all drafts. Lower is better; 0 means nothing needed fixing.
|
|
53
|
+
|
|
54
|
+
```
|
|
55
|
+
AMEND = total character edits over all drafts / total characters in all judge versions
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Pooling means long drafts weigh more than short ones, as with corpus-level WER and TER.
|
|
59
|
+
- **AMEND@0**: the share of drafts that needed zero edits, i.e. drafts the user could send as-is.
|
|
60
|
+
|
|
61
|
+
Character edits are used rather than word edits because they track the user's typing effort: fixing "test" to "tests" costs 1 character, not a whole word.
|
|
62
|
+
|
|
63
|
+
### What the judge fixes
|
|
64
|
+
|
|
65
|
+
- Misrecognised or wrong words ("weight" → "wait", "chronic" → "cron")
|
|
66
|
+
- Missing or extra content of any length, including generated or hallucinated text
|
|
67
|
+
- Filler words ("like", "you know", "um") that the intended text left out
|
|
68
|
+
- Wrong names, numbers or dates, including misspelled names
|
|
69
|
+
- Anything that must be typed exactly: code identifiers, file names, commands, field and config values, product names, emails, URLs ("calculate prorated amount" → `calculateProratedAmount`, "node 20 alpine" → `node:20-alpine`)
|
|
70
|
+
- Wrong or slang units ("512 megs" → "512 MB")
|
|
71
|
+
|
|
72
|
+
### What the judge leaves alone
|
|
73
|
+
|
|
74
|
+
- Different wording with the same meaning: articles, singular/plural, tense, contractions, synonyms, word order
|
|
75
|
+
- Punctuation, capitalisation, line breaks, bullets, numbered lists, markdown
|
|
76
|
+
- Digits vs words, decimals vs fractions ("4" vs "four", "1.5" vs "1 1/2")
|
|
77
|
+
- Standard abbreviations ("tbsp", "lb", "mph", "Dr.")
|
|
78
|
+
- Hyphenation and compounding of ordinary words, US vs UK spelling
|
|
79
|
+
|
|
80
|
+
### Self-corrections
|
|
81
|
+
|
|
82
|
+
Self-corrections are not penalised. The judge also receives the spoken text, so if the draft keeps "Tuesday, no wait, Wednesday" and the intended text says "Wednesday", that is not an error. A draft that ends up with the wrong final value ("Tuesday") is still fixed.
|
|
83
|
+
|
|
84
|
+
The full prompt is in [`src/amend/prompts.py`](src/amend/prompts.py).
|
|
85
|
+
|
|
86
|
+
### Normalisation
|
|
87
|
+
|
|
88
|
+
Only sentence-level punctuation at the start or end of a word is removed (`. , ; : ! ?`, quotes, brackets, `*`, `` ` ``, `_`, `~`, bullets, dashes, ellipses). Punctuation that carries meaning is kept: `%`, `/`, `$`, `@`, `#`, `&`, `+`, `=`, leading dots and dashes (`.env`, `--verbose`), and anything inside a token (`24.9`, `1,450`, `2:15`, `node:20-alpine`, `start_date`, `https://acme.com/docs`).
|
|
89
|
+
|
|
90
|
+
| Input | Normalised |
|
|
91
|
+
|---|---|
|
|
92
|
+
| `Send it to ops@northwind.io, or visit https://acme.com/docs.` | `send it to ops@northwind.io or visit https://acme.com/docs` |
|
|
93
|
+
| `It's 24.9% APR, about $1,450/month (roughly).` | `it's 24.9% apr about $1,450/month roughly` |
|
|
94
|
+
| `Wait... what? — no, it's fine.` | `wait what no it's fine` |
|
|
95
|
+
|
|
96
|
+
## Installation
|
|
97
|
+
|
|
98
|
+
Requires Python 3.11+.
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
pip install amend-va
|
|
102
|
+
# or
|
|
103
|
+
uv pip install amend-va
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
The package installs as `amend-va` and is imported as `amend`.
|
|
107
|
+
|
|
108
|
+
For development from a clone:
|
|
109
|
+
|
|
110
|
+
```bash
|
|
111
|
+
git clone https://github.com/VoiceArenaAI/AMEND.git
|
|
112
|
+
cd AMEND
|
|
113
|
+
uv sync
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### Authentication
|
|
117
|
+
|
|
118
|
+
The judge calls the Anthropic API. Set your key before running:
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
export ANTHROPIC_API_KEY=sk-ant-...
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## Usage
|
|
125
|
+
|
|
126
|
+
### Python
|
|
127
|
+
|
|
128
|
+
One draft:
|
|
129
|
+
|
|
130
|
+
```python
|
|
131
|
+
from amend import score
|
|
132
|
+
|
|
133
|
+
result = score(
|
|
134
|
+
pred="Want to grab brunch Sunday? No way, Saturday. I'm free all mourning.",
|
|
135
|
+
intended="Want to grab brunch Saturday? I'm free all morning.",
|
|
136
|
+
spoken="Want to grab brunch Sunday, no wait, Saturday? I'm free all morning.",
|
|
137
|
+
)
|
|
138
|
+
# {'pred': '...', 'fixed': "... I'm free all morning.", 'edits': <int>, 'chars': <int>, 'amend': <float>}
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
Three arrays:
|
|
142
|
+
|
|
143
|
+
```python
|
|
144
|
+
from amend import score_arrays
|
|
145
|
+
|
|
146
|
+
results = score_arrays(preds, intendeds, spokens, mode="batch")
|
|
147
|
+
# one dict per draft: {'pred', 'fixed', 'edits', 'chars', 'amend'}
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
A pandas DataFrame, with one or more prediction columns:
|
|
151
|
+
|
|
152
|
+
```python
|
|
153
|
+
import pandas as pd
|
|
154
|
+
from amend import score_dataframe
|
|
155
|
+
|
|
156
|
+
df = pd.read_csv("all_preds.csv")
|
|
157
|
+
out = score_dataframe(
|
|
158
|
+
df,
|
|
159
|
+
pred_cols=["apple", "wispr"],
|
|
160
|
+
intended_col="intended_text",
|
|
161
|
+
spoken_col="spoken_text",
|
|
162
|
+
mode="sync",
|
|
163
|
+
)
|
|
164
|
+
# adds <col>_fixed, <col>_edits, <col>_chars, <col>_amend for each column
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
The metric alone, without the judge:
|
|
168
|
+
|
|
169
|
+
```python
|
|
170
|
+
from amend import amend, char_edits, pooled
|
|
171
|
+
|
|
172
|
+
char_edits("the weight was long", "The wait was long.") # (3, 17)
|
|
173
|
+
amend("the weight was long", "The wait was long.") # 0.1765
|
|
174
|
+
pooled(out["apple_edits"], out["apple_chars"]) # corpus-level AMEND
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
### Command line
|
|
178
|
+
|
|
179
|
+
```bash
|
|
180
|
+
amend data.csv -p apple claude wispr -o scored.csv
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
| Option | Default | Meaning |
|
|
184
|
+
|---|---|---|
|
|
185
|
+
| `-p, --pred-col` | required | one or more prediction columns |
|
|
186
|
+
| `-i, --intended-col` | `intended_text` | intended text column |
|
|
187
|
+
| `-s, --spoken-col` | `spoken_text` | spoken text column |
|
|
188
|
+
| `-v, --version` | `v1` | prompt version |
|
|
189
|
+
| `-m, --mode` | `sync` | `sync` or `batch` |
|
|
190
|
+
| `-o, --out` | required | output CSV |
|
|
191
|
+
| `--model` | `claude-sonnet-5-5` | judge model |
|
|
192
|
+
| `--effort` | `medium` | judge effort level |
|
|
193
|
+
| `--workers` | `8` | parallel requests in sync mode |
|
|
194
|
+
| `--limit` | all rows | score only the first N rows |
|
|
195
|
+
| `--retries` | `3` | sync re-runs of failed drafts after the main run |
|
|
196
|
+
|
|
197
|
+
The output CSV is the input plus, for each prediction column:
|
|
198
|
+
|
|
199
|
+
| Column | Meaning |
|
|
200
|
+
|---|---|
|
|
201
|
+
| `<col>_fixed` | the judge's minimally edited draft |
|
|
202
|
+
| `<col>_edits` | character edits between the draft and `<col>_fixed` |
|
|
203
|
+
| `<col>_chars` | characters in the normalised `<col>_fixed` |
|
|
204
|
+
| `<col>_amend` | that draft's own edit rate, `edits / chars` |
|
|
205
|
+
|
|
206
|
+
A summary is printed, with AMEND pooled over all rows:
|
|
207
|
+
|
|
208
|
+
```
|
|
209
|
+
pred_col rows failed char_edits chars AMEND AMEND@0
|
|
210
|
+
wispr 750 0 1464 185012 0.0079 0.6627
|
|
211
|
+
apple 749 1 4985 188412 0.0265 0.3044
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
### Sync vs batch
|
|
215
|
+
|
|
216
|
+
| | Sync | Batch |
|
|
217
|
+
|---|---|---|
|
|
218
|
+
| How | parallel requests (`--workers`) | Anthropic Message Batches API |
|
|
219
|
+
| Price | standard | 50% of standard |
|
|
220
|
+
| Speed | minutes | usually under an hour, up to 24 hours |
|
|
221
|
+
| Refusals | rerun on a fallback model automatically | marked as failed |
|
|
222
|
+
|
|
223
|
+
In both modes identical prompts are sent once, so the same draft from two tools, or for two speakers, is only paid for once.
|
|
224
|
+
|
|
225
|
+
## Failed rows
|
|
226
|
+
|
|
227
|
+
A draft is marked failed, with empty `fixed`, `edits`, `chars` and `amend`, when the judge refuses, the response is truncated or not valid JSON, or the batch request errors or expires. After the main run, in either mode, failed drafts are re-sent in sync mode up to `retries` times (default 3; `--retries` on the CLI, `retries=` in Python). Drafts that still fail are excluded from AMEND and AMEND@0 and counted in the `failed` column.
|
|
228
|
+
|
|
229
|
+
If the judge's version is empty, the draft contributes its own length as edits and 0 characters to the pooled AMEND, and its per-draft `amend` is 0 when the draft is also empty and 1 otherwise.
|
|
230
|
+
|
|
231
|
+
## Limitations
|
|
232
|
+
|
|
233
|
+
- **Judge noise.** The judge's model doesn't accept `temperature`, so repeated runs can differ slightly. Measure run-to-run variance on a sample before reading small gaps between tools.
|
|
234
|
+
- **Casing is ignored.** Text is lowercased, so an identifier that differs only in case (`pgbouncer` vs `PgBouncer`) is not penalised.
|
|
235
|
+
- **CER, not TER.** Unlike HTER, there is no shift operation: moving a phrase counts as a deletion plus an insertion.
|
|
236
|
+
- **Deleting text costs every character.** Removing a long hallucinated passage is one select-and-delete for a person, but counts as one edit per character.
|
|
237
|
+
- **A draft's `amend` can exceed 1** when the draft is much longer than the judge's version, for example when a tool appends a long generated answer.
|
|
238
|
+
|
|
239
|
+
## License
|
|
240
|
+
|
|
241
|
+
Apache License 2.0. See [LICENSE](LICENSE).
|
amend_va-0.1.0/README.md
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
# AMEND
|
|
2
|
+
|
|
3
|
+
**AMEND** (Aggregate Minimum Edits Needed per Draft) measures how much a user would have to fix in a dictation tool's output before it is usable.
|
|
4
|
+
|
|
5
|
+
Word error rate (WER) compares a transcript with a single reference, so it penalises every legitimate difference: digits vs words, a resolved self-correction, a reworded phrase. AMEND instead asks a different question: *given what the user meant to write, what is the smallest set of edits that makes this draft acceptable?*
|
|
6
|
+
|
|
7
|
+
## Inspiration: HTER
|
|
8
|
+
|
|
9
|
+
AMEND is inspired by **HTER** (Human-targeted Translation Edit Rate) from machine translation evaluation ([Snover et al., 2006](https://aclanthology.org/2006.amta-papers.25/)).
|
|
10
|
+
|
|
11
|
+
In HTER, a human annotator takes a system's translation and edits it, as little as possible, until it is fluent and means the same as the reference. That edited version becomes a *targeted reference* for that output. The score is the edit rate between the system output and its own targeted reference. Because the target is built from the output itself, a correct translation that is worded differently from the reference costs nothing. Only edits a human actually needed are counted.
|
|
12
|
+
|
|
13
|
+
AMEND applies the same idea to dictation, with an LLM judge in the role of the human annotator:
|
|
14
|
+
|
|
15
|
+
| | HTER | AMEND |
|
|
16
|
+
|---|---|---|
|
|
17
|
+
| Output being scored | MT translation | Dictation tool's draft |
|
|
18
|
+
| Ground truth | Reference translation | Intended text, plus the spoken text |
|
|
19
|
+
| Who builds the targeted reference | Human annotator | LLM judge (`claude-sonnet-5-5`) |
|
|
20
|
+
| Edit rate | TER (word level, with shifts) | CER (character level, via `jiwer`) |
|
|
21
|
+
|
|
22
|
+
## How it works
|
|
23
|
+
|
|
24
|
+
For each draft:
|
|
25
|
+
|
|
26
|
+
1. The judge receives the **spoken text** (a verbatim transcript of what the user said), the **intended text** and the **draft**.
|
|
27
|
+
2. It returns the draft with the **minimum edits** needed for it to serve the same purpose as the intended text.
|
|
28
|
+
3. Both the draft and the judge's version are normalised: Unicode NFKC, lowercased, sentence punctuation at word edges stripped, whitespace collapsed.
|
|
29
|
+
4. The character edits (substitutions + deletions + insertions) needed to turn the draft into the judge's version are counted with `jiwer`, along with the number of characters in the judge's version. Spaces count as characters.
|
|
30
|
+
|
|
31
|
+
Two numbers summarise a set of drafts:
|
|
32
|
+
|
|
33
|
+
- **AMEND**: corpus-level character edit rate, pooled over all drafts. Lower is better; 0 means nothing needed fixing.
|
|
34
|
+
|
|
35
|
+
```
|
|
36
|
+
AMEND = total character edits over all drafts / total characters in all judge versions
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Pooling means long drafts weigh more than short ones, as with corpus-level WER and TER.
|
|
40
|
+
- **AMEND@0**: the share of drafts that needed zero edits, i.e. drafts the user could send as-is.
|
|
41
|
+
|
|
42
|
+
Character edits are used rather than word edits because they track the user's typing effort: fixing "test" to "tests" costs 1 character, not a whole word.
|
|
43
|
+
|
|
44
|
+
### What the judge fixes
|
|
45
|
+
|
|
46
|
+
- Misrecognised or wrong words ("weight" → "wait", "chronic" → "cron")
|
|
47
|
+
- Missing or extra content of any length, including generated or hallucinated text
|
|
48
|
+
- Filler words ("like", "you know", "um") that the intended text left out
|
|
49
|
+
- Wrong names, numbers or dates, including misspelled names
|
|
50
|
+
- Anything that must be typed exactly: code identifiers, file names, commands, field and config values, product names, emails, URLs ("calculate prorated amount" → `calculateProratedAmount`, "node 20 alpine" → `node:20-alpine`)
|
|
51
|
+
- Wrong or slang units ("512 megs" → "512 MB")
|
|
52
|
+
|
|
53
|
+
### What the judge leaves alone
|
|
54
|
+
|
|
55
|
+
- Different wording with the same meaning: articles, singular/plural, tense, contractions, synonyms, word order
|
|
56
|
+
- Punctuation, capitalisation, line breaks, bullets, numbered lists, markdown
|
|
57
|
+
- Digits vs words, decimals vs fractions ("4" vs "four", "1.5" vs "1 1/2")
|
|
58
|
+
- Standard abbreviations ("tbsp", "lb", "mph", "Dr.")
|
|
59
|
+
- Hyphenation and compounding of ordinary words, US vs UK spelling
|
|
60
|
+
|
|
61
|
+
### Self-corrections
|
|
62
|
+
|
|
63
|
+
Self-corrections are not penalised. The judge also receives the spoken text, so if the draft keeps "Tuesday, no wait, Wednesday" and the intended text says "Wednesday", that is not an error. A draft that ends up with the wrong final value ("Tuesday") is still fixed.
|
|
64
|
+
|
|
65
|
+
The full prompt is in [`src/amend/prompts.py`](src/amend/prompts.py).
|
|
66
|
+
|
|
67
|
+
### Normalisation
|
|
68
|
+
|
|
69
|
+
Only sentence-level punctuation at the start or end of a word is removed (`. , ; : ! ?`, quotes, brackets, `*`, `` ` ``, `_`, `~`, bullets, dashes, ellipses). Punctuation that carries meaning is kept: `%`, `/`, `$`, `@`, `#`, `&`, `+`, `=`, leading dots and dashes (`.env`, `--verbose`), and anything inside a token (`24.9`, `1,450`, `2:15`, `node:20-alpine`, `start_date`, `https://acme.com/docs`).
|
|
70
|
+
|
|
71
|
+
| Input | Normalised |
|
|
72
|
+
|---|---|
|
|
73
|
+
| `Send it to ops@northwind.io, or visit https://acme.com/docs.` | `send it to ops@northwind.io or visit https://acme.com/docs` |
|
|
74
|
+
| `It's 24.9% APR, about $1,450/month (roughly).` | `it's 24.9% apr about $1,450/month roughly` |
|
|
75
|
+
| `Wait... what? — no, it's fine.` | `wait what no it's fine` |
|
|
76
|
+
|
|
77
|
+
## Installation
|
|
78
|
+
|
|
79
|
+
Requires Python 3.11+.
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
pip install amend-va
|
|
83
|
+
# or
|
|
84
|
+
uv pip install amend-va
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
The package installs as `amend-va` and is imported as `amend`.
|
|
88
|
+
|
|
89
|
+
For development from a clone:
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
git clone https://github.com/VoiceArenaAI/AMEND.git
|
|
93
|
+
cd AMEND
|
|
94
|
+
uv sync
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### Authentication
|
|
98
|
+
|
|
99
|
+
The judge calls the Anthropic API. Set your key before running:
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
export ANTHROPIC_API_KEY=sk-ant-...
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Usage
|
|
106
|
+
|
|
107
|
+
### Python
|
|
108
|
+
|
|
109
|
+
One draft:
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
from amend import score
|
|
113
|
+
|
|
114
|
+
result = score(
|
|
115
|
+
pred="Want to grab brunch Sunday? No way, Saturday. I'm free all mourning.",
|
|
116
|
+
intended="Want to grab brunch Saturday? I'm free all morning.",
|
|
117
|
+
spoken="Want to grab brunch Sunday, no wait, Saturday? I'm free all morning.",
|
|
118
|
+
)
|
|
119
|
+
# {'pred': '...', 'fixed': "... I'm free all morning.", 'edits': <int>, 'chars': <int>, 'amend': <float>}
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Three arrays:
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
from amend import score_arrays
|
|
126
|
+
|
|
127
|
+
results = score_arrays(preds, intendeds, spokens, mode="batch")
|
|
128
|
+
# one dict per draft: {'pred', 'fixed', 'edits', 'chars', 'amend'}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
A pandas DataFrame, with one or more prediction columns:
|
|
132
|
+
|
|
133
|
+
```python
|
|
134
|
+
import pandas as pd
|
|
135
|
+
from amend import score_dataframe
|
|
136
|
+
|
|
137
|
+
df = pd.read_csv("all_preds.csv")
|
|
138
|
+
out = score_dataframe(
|
|
139
|
+
df,
|
|
140
|
+
pred_cols=["apple", "wispr"],
|
|
141
|
+
intended_col="intended_text",
|
|
142
|
+
spoken_col="spoken_text",
|
|
143
|
+
mode="sync",
|
|
144
|
+
)
|
|
145
|
+
# adds <col>_fixed, <col>_edits, <col>_chars, <col>_amend for each column
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
The metric alone, without the judge:
|
|
149
|
+
|
|
150
|
+
```python
|
|
151
|
+
from amend import amend, char_edits, pooled
|
|
152
|
+
|
|
153
|
+
char_edits("the weight was long", "The wait was long.") # (3, 17)
|
|
154
|
+
amend("the weight was long", "The wait was long.") # 0.1765
|
|
155
|
+
pooled(out["apple_edits"], out["apple_chars"]) # corpus-level AMEND
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
### Command line
|
|
159
|
+
|
|
160
|
+
```bash
|
|
161
|
+
amend data.csv -p apple claude wispr -o scored.csv
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
| Option | Default | Meaning |
|
|
165
|
+
|---|---|---|
|
|
166
|
+
| `-p, --pred-col` | required | one or more prediction columns |
|
|
167
|
+
| `-i, --intended-col` | `intended_text` | intended text column |
|
|
168
|
+
| `-s, --spoken-col` | `spoken_text` | spoken text column |
|
|
169
|
+
| `-v, --version` | `v1` | prompt version |
|
|
170
|
+
| `-m, --mode` | `sync` | `sync` or `batch` |
|
|
171
|
+
| `-o, --out` | required | output CSV |
|
|
172
|
+
| `--model` | `claude-sonnet-5-5` | judge model |
|
|
173
|
+
| `--effort` | `medium` | judge effort level |
|
|
174
|
+
| `--workers` | `8` | parallel requests in sync mode |
|
|
175
|
+
| `--limit` | all rows | score only the first N rows |
|
|
176
|
+
| `--retries` | `3` | sync re-runs of failed drafts after the main run |
|
|
177
|
+
|
|
178
|
+
The output CSV is the input plus, for each prediction column:
|
|
179
|
+
|
|
180
|
+
| Column | Meaning |
|
|
181
|
+
|---|---|
|
|
182
|
+
| `<col>_fixed` | the judge's minimally edited draft |
|
|
183
|
+
| `<col>_edits` | character edits between the draft and `<col>_fixed` |
|
|
184
|
+
| `<col>_chars` | characters in the normalised `<col>_fixed` |
|
|
185
|
+
| `<col>_amend` | that draft's own edit rate, `edits / chars` |
|
|
186
|
+
|
|
187
|
+
A summary is printed, with AMEND pooled over all rows:
|
|
188
|
+
|
|
189
|
+
```
|
|
190
|
+
pred_col rows failed char_edits chars AMEND AMEND@0
|
|
191
|
+
wispr 750 0 1464 185012 0.0079 0.6627
|
|
192
|
+
apple 749 1 4985 188412 0.0265 0.3044
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
### Sync vs batch
|
|
196
|
+
|
|
197
|
+
| | Sync | Batch |
|
|
198
|
+
|---|---|---|
|
|
199
|
+
| How | parallel requests (`--workers`) | Anthropic Message Batches API |
|
|
200
|
+
| Price | standard | 50% of standard |
|
|
201
|
+
| Speed | minutes | usually under an hour, up to 24 hours |
|
|
202
|
+
| Refusals | rerun on a fallback model automatically | marked as failed |
|
|
203
|
+
|
|
204
|
+
In both modes identical prompts are sent once, so the same draft from two tools, or for two speakers, is only paid for once.
|
|
205
|
+
|
|
206
|
+
## Failed rows
|
|
207
|
+
|
|
208
|
+
A draft is marked failed, with empty `fixed`, `edits`, `chars` and `amend`, when the judge refuses, the response is truncated or not valid JSON, or the batch request errors or expires. After the main run, in either mode, failed drafts are re-sent in sync mode up to `retries` times (default 3; `--retries` on the CLI, `retries=` in Python). Drafts that still fail are excluded from AMEND and AMEND@0 and counted in the `failed` column.
|
|
209
|
+
|
|
210
|
+
If the judge's version is empty, the draft contributes its own length as edits and 0 characters to the pooled AMEND, and its per-draft `amend` is 0 when the draft is also empty and 1 otherwise.
|
|
211
|
+
|
|
212
|
+
## Limitations
|
|
213
|
+
|
|
214
|
+
- **Judge noise.** The judge's model doesn't accept `temperature`, so repeated runs can differ slightly. Measure run-to-run variance on a sample before reading small gaps between tools.
|
|
215
|
+
- **Casing is ignored.** Text is lowercased, so an identifier that differs only in case (`pgbouncer` vs `PgBouncer`) is not penalised.
|
|
216
|
+
- **CER, not TER.** Unlike HTER, there is no shift operation: moving a phrase counts as a deletion plus an insertion.
|
|
217
|
+
- **Deleting text costs every character.** Removing a long hallucinated passage is one select-and-delete for a person, but counts as one edit per character.
|
|
218
|
+
- **A draft's `amend` can exceed 1** when the draft is much longer than the judge's version, for example when a tool appends a long generated answer.
|
|
219
|
+
|
|
220
|
+
## License
|
|
221
|
+
|
|
222
|
+
Apache License 2.0. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "amend-va"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "AMEND and AMEND@0: an LLM-judge minimum-edit metric for dictation tools"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
requires-python = ">=3.11"
|
|
9
|
+
dependencies = [
|
|
10
|
+
"anthropic>=2.6.0",
|
|
11
|
+
"jiwer>=4.0.0",
|
|
12
|
+
"pandas>=3.1.1",
|
|
13
|
+
]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Operating System :: OS Independent",
|
|
17
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[[project.authors]]
|
|
21
|
+
name = "manasdhir976"
|
|
22
|
+
email = "manas@joshtalks.com"
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
Homepage = "https://github.com/VoiceArenaAI/AMEND"
|
|
26
|
+
Repository = "https://github.com/VoiceArenaAI/AMEND"
|
|
27
|
+
|
|
28
|
+
[project.scripts]
|
|
29
|
+
amend = "amend.cli:main"
|
|
30
|
+
|
|
31
|
+
[build-system]
|
|
32
|
+
requires = ["uv_build>=0.11.8,<0.12.0"]
|
|
33
|
+
build-backend = "uv_build"
|
|
34
|
+
|
|
35
|
+
[tool.uv.build-backend]
|
|
36
|
+
module-name = "amend"
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "amend-va"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "AMEND and AMEND@0: an LLM-judge minimum-edit metric for dictation tools"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "Apache-2.0"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
authors = [
|
|
9
|
+
{ name = "manasdhir976", email = "manas@joshtalks.com" }
|
|
10
|
+
]
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
|
+
dependencies = [
|
|
13
|
+
"anthropic>=2.6.0",
|
|
14
|
+
"jiwer>=4.0.0",
|
|
15
|
+
"pandas>=3.1.1",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
classifiers = [
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Operating System :: OS Independent",
|
|
21
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
Homepage = "https://github.com/VoiceArenaAI/AMEND"
|
|
26
|
+
Repository = "https://github.com/VoiceArenaAI/AMEND"
|
|
27
|
+
|
|
28
|
+
[project.scripts]
|
|
29
|
+
amend = "amend.cli:main"
|
|
30
|
+
|
|
31
|
+
[build-system]
|
|
32
|
+
requires = ["uv_build>=0.11.8,<0.12.0"]
|
|
33
|
+
build-backend = "uv_build"
|
|
34
|
+
|
|
35
|
+
[tool.uv.build-backend]
|
|
36
|
+
module-name = "amend"
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
from .api import score, score_arrays, score_dataframe
|
|
2
|
+
from .judge import Judge
|
|
3
|
+
from .metric import amend, char_edits, normalize, pooled
|
|
4
|
+
from .prompts import build_prompt
|
|
5
|
+
|
|
6
|
+
__all__ = ["score", "score_arrays", "score_dataframe", "Judge", "amend", "char_edits", "pooled", "normalize", "build_prompt"]
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
from typing import Sequence
|
|
2
|
+
|
|
3
|
+
import pandas as pd
|
|
4
|
+
|
|
5
|
+
from .judge import Judge
|
|
6
|
+
from .metric import char_edits
|
|
7
|
+
from .prompts import build_prompt
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _judge(judge: Judge | None, **kwargs) -> Judge:
|
|
11
|
+
return judge or Judge(**kwargs)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _log(judge, msg: str) -> None:
|
|
15
|
+
if hasattr(judge, "_log"):
|
|
16
|
+
judge._log(msg)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def score_arrays(
|
|
20
|
+
preds: Sequence[str],
|
|
21
|
+
intendeds: Sequence[str],
|
|
22
|
+
spokens: Sequence[str],
|
|
23
|
+
version: str = "v1",
|
|
24
|
+
mode: str = "sync",
|
|
25
|
+
judge: Judge | None = None,
|
|
26
|
+
retries: int = 3,
|
|
27
|
+
**judge_kwargs,
|
|
28
|
+
) -> list[dict]:
|
|
29
|
+
if not (len(preds) == len(intendeds) == len(spokens)):
|
|
30
|
+
raise ValueError("preds, intendeds and spokens must have the same length")
|
|
31
|
+
judge = _judge(judge, **judge_kwargs)
|
|
32
|
+
prompts = [build_prompt(i, p, s, version) for p, i, s in zip(preds, intendeds, spokens)]
|
|
33
|
+
fixed = judge.fix_many(prompts, mode=mode)
|
|
34
|
+
|
|
35
|
+
def failed() -> list[int]:
|
|
36
|
+
return [k for k, f in enumerate(fixed) if f is None]
|
|
37
|
+
|
|
38
|
+
for attempt in range(1, retries + 1):
|
|
39
|
+
bad = failed()
|
|
40
|
+
if not bad:
|
|
41
|
+
break
|
|
42
|
+
_log(judge, f"retry {attempt}/{retries}: re-running {len(bad)} failed drafts in sync mode")
|
|
43
|
+
for k, f in zip(bad, judge.fix_many([prompts[k] for k in bad], mode="sync")):
|
|
44
|
+
fixed[k] = f
|
|
45
|
+
bad = failed()
|
|
46
|
+
if bad:
|
|
47
|
+
_log(judge, f"{len(bad)} drafts still failed after {retries} retries")
|
|
48
|
+
out = []
|
|
49
|
+
for p, f in zip(preds, fixed):
|
|
50
|
+
if f is None:
|
|
51
|
+
out.append({"pred": p, "fixed": None, "edits": None, "chars": None, "amend": None})
|
|
52
|
+
continue
|
|
53
|
+
e, c = char_edits(p, f)
|
|
54
|
+
out.append({"pred": p, "fixed": f, "edits": e, "chars": c, "amend": e / c if c else float(e > 0)})
|
|
55
|
+
return out
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def score(
|
|
59
|
+
pred: str,
|
|
60
|
+
intended: str,
|
|
61
|
+
spoken: str,
|
|
62
|
+
version: str = "v1",
|
|
63
|
+
judge: Judge | None = None,
|
|
64
|
+
retries: int = 3,
|
|
65
|
+
**judge_kwargs,
|
|
66
|
+
) -> dict:
|
|
67
|
+
return score_arrays([pred], [intended], [spoken], version, "sync", judge, retries, **judge_kwargs)[0]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def score_dataframe(
|
|
71
|
+
df: pd.DataFrame,
|
|
72
|
+
pred_cols: str | Sequence[str],
|
|
73
|
+
intended_col: str = "intended_text",
|
|
74
|
+
spoken_col: str = "spoken_text",
|
|
75
|
+
version: str = "v1",
|
|
76
|
+
mode: str = "sync",
|
|
77
|
+
judge: Judge | None = None,
|
|
78
|
+
retries: int = 3,
|
|
79
|
+
**judge_kwargs,
|
|
80
|
+
) -> pd.DataFrame:
|
|
81
|
+
cols = [pred_cols] if isinstance(pred_cols, str) else list(pred_cols)
|
|
82
|
+
out = df.copy()
|
|
83
|
+
n = len(df)
|
|
84
|
+
preds, intendeds, spokens = [], [], []
|
|
85
|
+
for c in cols:
|
|
86
|
+
preds += df[c].fillna("").astype(str).tolist()
|
|
87
|
+
intendeds += df[intended_col].fillna("").astype(str).tolist()
|
|
88
|
+
spokens += df[spoken_col].fillna("").astype(str).tolist()
|
|
89
|
+
results = score_arrays(preds, intendeds, spokens, version, mode, _judge(judge, **judge_kwargs), retries)
|
|
90
|
+
for k, c in enumerate(cols):
|
|
91
|
+
part = results[k * n : (k + 1) * n]
|
|
92
|
+
out[f"{c}_fixed"] = [r["fixed"] for r in part]
|
|
93
|
+
out[f"{c}_edits"] = [r["edits"] for r in part]
|
|
94
|
+
out[f"{c}_chars"] = [r["chars"] for r in part]
|
|
95
|
+
out[f"{c}_amend"] = [r["amend"] for r in part]
|
|
96
|
+
return out
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import sys
|
|
3
|
+
|
|
4
|
+
import pandas as pd
|
|
5
|
+
|
|
6
|
+
from .api import score_dataframe
|
|
7
|
+
from .judge import EFFORT, MODEL, Judge
|
|
8
|
+
from .metric import pooled
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def main(argv: list[str] | None = None) -> int:
|
|
12
|
+
ap = argparse.ArgumentParser(
|
|
13
|
+
prog="amend",
|
|
14
|
+
description="AMEND: an LLM judge applies the minimum edits to each prediction, "
|
|
15
|
+
"then AMEND (CER between the prediction and the judge output) is reported per row.",
|
|
16
|
+
)
|
|
17
|
+
ap.add_argument("csv", help="input CSV")
|
|
18
|
+
ap.add_argument("-p", "--pred-col", nargs="+", required=True, help="prediction column(s)")
|
|
19
|
+
ap.add_argument("-i", "--intended-col", default="intended_text")
|
|
20
|
+
ap.add_argument("-s", "--spoken-col", default="spoken_text", help="spoken text column")
|
|
21
|
+
ap.add_argument("-v", "--version", choices=["v1"], default="v1", help="prompt version")
|
|
22
|
+
ap.add_argument("-m", "--mode", choices=["sync", "batch"], default="sync")
|
|
23
|
+
ap.add_argument("-o", "--out", required=True, help="output CSV")
|
|
24
|
+
ap.add_argument("--model", default=MODEL)
|
|
25
|
+
ap.add_argument("--effort", default=EFFORT)
|
|
26
|
+
ap.add_argument("--workers", type=int, default=8, help="parallel requests in sync mode")
|
|
27
|
+
ap.add_argument("--limit", type=int, default=None, help="score only the first N rows")
|
|
28
|
+
ap.add_argument("--retries", type=int, default=3, help="sync re-runs of failed drafts after the main run")
|
|
29
|
+
a = ap.parse_args(argv)
|
|
30
|
+
|
|
31
|
+
df = pd.read_csv(a.csv, dtype=str, keep_default_na=False)
|
|
32
|
+
if a.spoken_col not in df.columns:
|
|
33
|
+
ap.error(f"spoken text column {a.spoken_col!r} not found (set --spoken-col)")
|
|
34
|
+
if a.limit:
|
|
35
|
+
df = df.head(a.limit)
|
|
36
|
+
judge = Judge(model=a.model, effort=a.effort, workers=a.workers, verbose=True)
|
|
37
|
+
out = score_dataframe(df, a.pred_col, a.intended_col, a.spoken_col, a.version, a.mode, judge, a.retries)
|
|
38
|
+
out.to_csv(a.out, index=False)
|
|
39
|
+
|
|
40
|
+
summary = pd.DataFrame(
|
|
41
|
+
{
|
|
42
|
+
"pred_col": c,
|
|
43
|
+
"rows": out[f"{c}_amend"].notna().sum(),
|
|
44
|
+
"failed": out[f"{c}_amend"].isna().sum(),
|
|
45
|
+
"char_edits": int(out[f"{c}_edits"].sum()),
|
|
46
|
+
"chars": int(out[f"{c}_chars"].sum()),
|
|
47
|
+
"AMEND": pooled(out[f"{c}_edits"].dropna(), out[f"{c}_chars"].dropna()),
|
|
48
|
+
"AMEND@0": (out[f"{c}_edits"].dropna() == 0).mean(),
|
|
49
|
+
}
|
|
50
|
+
for c in a.pred_col
|
|
51
|
+
).sort_values("AMEND")
|
|
52
|
+
print(summary.to_string(index=False, float_format=lambda x: f"{x:.4f}"))
|
|
53
|
+
print(f"wrote {a.out}", file=sys.stderr)
|
|
54
|
+
return 0
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
if __name__ == "__main__":
|
|
58
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import sys
|
|
3
|
+
import time
|
|
4
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
5
|
+
|
|
6
|
+
import anthropic
|
|
7
|
+
from anthropic.types.message_create_params import MessageCreateParamsNonStreaming
|
|
8
|
+
from anthropic.types.messages.batch_create_params import Request
|
|
9
|
+
|
|
10
|
+
MODEL = "claude-sonnet-5-5"
|
|
11
|
+
EFFORT = "medium"
|
|
12
|
+
MAX_TOKENS = 16000
|
|
13
|
+
BATCH_CHUNK = 10000
|
|
14
|
+
SCHEMA = {
|
|
15
|
+
"type": "json_schema",
|
|
16
|
+
"schema": {
|
|
17
|
+
"type": "object",
|
|
18
|
+
"properties": {"fixed": {"type": "string"}},
|
|
19
|
+
"required": ["fixed"],
|
|
20
|
+
"additionalProperties": False,
|
|
21
|
+
},
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _text(message) -> str | None:
|
|
26
|
+
if message.stop_reason != "end_turn":
|
|
27
|
+
return None
|
|
28
|
+
raw = "".join(b.text for b in message.content if b.type == "text")
|
|
29
|
+
try:
|
|
30
|
+
return json.loads(raw)["fixed"].strip()
|
|
31
|
+
except (ValueError, KeyError, TypeError):
|
|
32
|
+
return None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class Judge:
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
model: str = MODEL,
|
|
39
|
+
effort: str = EFFORT,
|
|
40
|
+
max_tokens: int = MAX_TOKENS,
|
|
41
|
+
client: anthropic.Anthropic | None = None,
|
|
42
|
+
workers: int = 8,
|
|
43
|
+
poll_seconds: int = 30,
|
|
44
|
+
verbose: bool = False,
|
|
45
|
+
):
|
|
46
|
+
self.model = model
|
|
47
|
+
self.effort = effort
|
|
48
|
+
self.max_tokens = max_tokens
|
|
49
|
+
self.client = client or anthropic.Anthropic()
|
|
50
|
+
self.workers = workers
|
|
51
|
+
self.poll_seconds = poll_seconds
|
|
52
|
+
self.verbose = verbose
|
|
53
|
+
|
|
54
|
+
def _log(self, msg: str) -> None:
|
|
55
|
+
if self.verbose:
|
|
56
|
+
print(msg, file=sys.stderr, flush=True)
|
|
57
|
+
|
|
58
|
+
def fix(self, prompt: str) -> str | None:
|
|
59
|
+
try:
|
|
60
|
+
message = self.client.beta.messages.create(
|
|
61
|
+
model=self.model,
|
|
62
|
+
max_tokens=self.max_tokens,
|
|
63
|
+
output_config={"effort": self.effort, "format": SCHEMA},
|
|
64
|
+
betas=["server-side-fallback-2026-07-01"],
|
|
65
|
+
fallbacks="default",
|
|
66
|
+
messages=[{"role": "user", "content": prompt}],
|
|
67
|
+
)
|
|
68
|
+
except anthropic.APIError as e:
|
|
69
|
+
self._log(f"request failed: {type(e).__name__}: {e}")
|
|
70
|
+
return None
|
|
71
|
+
text = _text(message)
|
|
72
|
+
if text is None:
|
|
73
|
+
self._log(f"unusable response: stop_reason={message.stop_reason}")
|
|
74
|
+
return text
|
|
75
|
+
|
|
76
|
+
def fix_many(self, prompts: list[str], mode: str = "sync") -> list[str | None]:
|
|
77
|
+
unique = list(dict.fromkeys(prompts))
|
|
78
|
+
if mode == "sync":
|
|
79
|
+
results = self._sync(unique)
|
|
80
|
+
elif mode == "batch":
|
|
81
|
+
results = self._batch(unique)
|
|
82
|
+
else:
|
|
83
|
+
raise ValueError(f"unknown mode {mode!r}, expected 'sync' or 'batch'")
|
|
84
|
+
lookup = dict(zip(unique, results))
|
|
85
|
+
return [lookup[p] for p in prompts]
|
|
86
|
+
|
|
87
|
+
def _sync(self, prompts: list[str]) -> list[str | None]:
|
|
88
|
+
done = 0
|
|
89
|
+
|
|
90
|
+
def run(p: str) -> str | None:
|
|
91
|
+
nonlocal done
|
|
92
|
+
out = self.fix(p)
|
|
93
|
+
done += 1
|
|
94
|
+
self._log(f"sync {done}/{len(prompts)}")
|
|
95
|
+
return out
|
|
96
|
+
|
|
97
|
+
with ThreadPoolExecutor(max_workers=self.workers) as ex:
|
|
98
|
+
return list(ex.map(run, prompts))
|
|
99
|
+
|
|
100
|
+
def _batch(self, prompts: list[str]) -> list[str | None]:
|
|
101
|
+
results: list[str | None] = [None] * len(prompts)
|
|
102
|
+
for start in range(0, len(prompts), BATCH_CHUNK):
|
|
103
|
+
chunk = prompts[start : start + BATCH_CHUNK]
|
|
104
|
+
requests = [
|
|
105
|
+
Request(
|
|
106
|
+
custom_id=f"r{start + i}",
|
|
107
|
+
params=MessageCreateParamsNonStreaming(
|
|
108
|
+
model=self.model,
|
|
109
|
+
max_tokens=self.max_tokens,
|
|
110
|
+
output_config={"effort": self.effort, "format": SCHEMA},
|
|
111
|
+
messages=[{"role": "user", "content": p}],
|
|
112
|
+
),
|
|
113
|
+
)
|
|
114
|
+
for i, p in enumerate(chunk)
|
|
115
|
+
]
|
|
116
|
+
batch = self.client.messages.batches.create(requests=requests)
|
|
117
|
+
self._log(f"batch {batch.id} submitted with {len(requests)} requests")
|
|
118
|
+
while batch.processing_status != "ended":
|
|
119
|
+
time.sleep(self.poll_seconds)
|
|
120
|
+
batch = self.client.messages.batches.retrieve(batch.id)
|
|
121
|
+
c = batch.request_counts
|
|
122
|
+
self._log(f"batch {batch.id} {batch.processing_status} processing={c.processing} succeeded={c.succeeded} errored={c.errored}")
|
|
123
|
+
for item in self.client.messages.batches.results(batch.id):
|
|
124
|
+
idx = int(item.custom_id[1:])
|
|
125
|
+
if item.result.type == "succeeded":
|
|
126
|
+
results[idx] = _text(item.result.message)
|
|
127
|
+
else:
|
|
128
|
+
self._log(f"{item.custom_id} {item.result.type}")
|
|
129
|
+
return results
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import re
|
|
2
|
+
import unicodedata
|
|
3
|
+
|
|
4
|
+
import jiwer
|
|
5
|
+
|
|
6
|
+
_QUOTES = str.maketrans({"’": "'", "‘": "'", "“": '"', "”": '"'})
|
|
7
|
+
_LEAD = "\"'([{<*_`~•·…—–,;:!?"
|
|
8
|
+
_TRAIL = "\"')]}>*_`~•·…—–,;:!?.-"
|
|
9
|
+
_JUNK = set(_LEAD) | set(_TRAIL) | set("#")
|
|
10
|
+
_ELLIPSIS = re.compile(r"\.{2,}")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _clean(token: str) -> str:
|
|
14
|
+
token = _ELLIPSIS.sub(" ", token).strip()
|
|
15
|
+
if not token or all(ch in _JUNK for ch in token):
|
|
16
|
+
return ""
|
|
17
|
+
return token.lstrip(_LEAD).rstrip(_TRAIL)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def normalize(text: str | None) -> str:
|
|
21
|
+
if not text:
|
|
22
|
+
return ""
|
|
23
|
+
text = unicodedata.normalize("NFKC", text).translate(_QUOTES).lower()
|
|
24
|
+
tokens = (_clean(t) for t in _ELLIPSIS.sub(" ", text).split())
|
|
25
|
+
return " ".join(t for t in tokens if t)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def char_edits(pred: str | None, fixed: str | None) -> tuple[int, int]:
|
|
29
|
+
ref = normalize(fixed)
|
|
30
|
+
hyp = normalize(pred)
|
|
31
|
+
if not ref:
|
|
32
|
+
return len(hyp), 0
|
|
33
|
+
if not hyp:
|
|
34
|
+
return len(ref), len(ref)
|
|
35
|
+
o = jiwer.process_characters(ref, hyp)
|
|
36
|
+
return o.substitutions + o.deletions + o.insertions, o.hits + o.substitutions + o.deletions
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def amend(pred: str | None, fixed: str | None) -> float:
|
|
40
|
+
edits, chars = char_edits(pred, fixed)
|
|
41
|
+
if not chars:
|
|
42
|
+
return 0.0 if not edits else 1.0
|
|
43
|
+
return edits / chars
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def pooled(edits, chars) -> float:
|
|
47
|
+
edits, chars = sum(edits), sum(chars)
|
|
48
|
+
return edits / chars if chars else 0.0
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
BASE = """You are evaluating the output of a dictation tool. You will be given the INTENDED text
|
|
2
|
+
(what the user wanted to end up with) and the DRAFT (what the dictation tool produced).
|
|
3
|
+
|
|
4
|
+
Your job: find what the user would actually have to fix in the DRAFT so that it serves
|
|
5
|
+
the same purpose as the INTENDED text, and fix only that, using the fewest possible
|
|
6
|
+
word edits. The DRAFT does not need the same wording as the INTENDED text. If a reader
|
|
7
|
+
would understand the same thing and act the same way, leave it as it is.
|
|
8
|
+
|
|
9
|
+
Fix these (they change the meaning, or the user would have to retype them):
|
|
10
|
+
- Misrecognized or wrong words ("weight" -> "wait", "offensive" -> "defensive",
|
|
11
|
+
"chronic" -> "cron")
|
|
12
|
+
- Missing or extra content of any length. Add anything the INTENDED text says that the
|
|
13
|
+
DRAFT is missing, and delete anything the tool added that is not in the INTENDED text
|
|
14
|
+
(for example an answer it generated, invented content, or repeated text)
|
|
15
|
+
- Filler words ("like", "you know", "um") that the INTENDED text left out
|
|
16
|
+
- Wrong names, numbers or dates, including misspelled names
|
|
17
|
+
- Anything that must be written exactly: code identifiers, file names, commands, field
|
|
18
|
+
and config values, product names, emails and URLs. Make them match the INTENDED text
|
|
19
|
+
exactly ("calculate prorated amount" -> "calculateProratedAmount",
|
|
20
|
+
"start date" -> "start_date", "billing ts" -> "billing.ts",
|
|
21
|
+
"node 20 alpine" -> "node:20-alpine", "PG Bouncer" -> "PgBouncer")
|
|
22
|
+
- A wrong unit, or an informal/slang unit ("512 megs" -> "512 MB")
|
|
23
|
+
|
|
24
|
+
Do NOT fix these (same meaning, or only formatting):
|
|
25
|
+
- Different wording with the same meaning: articles, singular/plural, tense or
|
|
26
|
+
contraction changes that keep the meaning ("a" vs "the", "note" vs "notes",
|
|
27
|
+
"that handles" vs "that'd handle"), synonyms, paraphrases and word-order changes
|
|
28
|
+
("I'll mention" vs "I want to mention")
|
|
29
|
+
- Punctuation, capitalization, line breaks, bullets, numbered lists, markdown
|
|
30
|
+
- Numbers written as digits vs words, or as decimals vs fractions ("4" vs "four",
|
|
31
|
+
"1" vs "one", "$1,450" vs "fourteen fifty", "1.5" vs "1 1/2")
|
|
32
|
+
- Standard abbreviations ("tbsp" vs "tablespoons", "lb" vs "pound",
|
|
33
|
+
"mph" vs "miles an hour", "Dr." vs "Doctor")
|
|
34
|
+
- Hyphenation and compounding of ordinary words ("short-staffed" vs "short staffed")
|
|
35
|
+
- Contractions vs full forms ("we're" vs "we are")
|
|
36
|
+
- US vs UK spelling
|
|
37
|
+
|
|
38
|
+
Rules:
|
|
39
|
+
- Leave every part of the DRAFT that does not need fixing exactly as it is.
|
|
40
|
+
- When you insert or replace words, match the formatting style of the surrounding
|
|
41
|
+
DRAFT text.
|
|
42
|
+
- Make each fix as small as possible: replace one word rather than rewriting the
|
|
43
|
+
sentence around it. But fix a missing or extra passage in full.
|
|
44
|
+
- If the DRAFT is empty, "fixed" is the INTENDED text.
|
|
45
|
+
{lenient}
|
|
46
|
+
{spoken}<intended>
|
|
47
|
+
{intended}
|
|
48
|
+
</intended>
|
|
49
|
+
|
|
50
|
+
<draft>
|
|
51
|
+
{draft}
|
|
52
|
+
</draft>
|
|
53
|
+
|
|
54
|
+
Respond with JSON whose "fixed" field holds only the corrected draft text, with no
|
|
55
|
+
explanation, notes or reasoning in it. If no changes are needed, "fixed" is the DRAFT
|
|
56
|
+
exactly as given."""
|
|
57
|
+
|
|
58
|
+
LENIENT = """
|
|
59
|
+
You are also given SPOKEN: a verbatim transcript of what the user actually said,
|
|
60
|
+
including any self-corrections. A self-correction can replace something ("Tuesday,
|
|
61
|
+
no wait, Wednesday", "ten AM, sorry, ten thirty", "five times, no, make it three")
|
|
62
|
+
or retract something ("get milk and eggs, oh wait, we have eggs, take that off").
|
|
63
|
+
|
|
64
|
+
Self-corrections are lenient. If a difference between the DRAFT and the INTENDED
|
|
65
|
+
text exists only because the DRAFT kept a self-correction from SPOKEN (for example
|
|
66
|
+
it kept both the original and the corrected version, kept a retracted item together
|
|
67
|
+
with the retraction, or kept cue words such as "no wait", "sorry", "actually no",
|
|
68
|
+
"no, make it", "I mean", "scratch that", "take that off"), leave it unchanged.
|
|
69
|
+
It is not an error.
|
|
70
|
+
|
|
71
|
+
This takes priority over the rule about extra content. Keep a kept self-correction
|
|
72
|
+
whole: the original, the cue words and the correction. This applies even if the cue
|
|
73
|
+
words were misheard ("wait now" for "wait no", "no way" for "no wait"). Never delete
|
|
74
|
+
only part of it.
|
|
75
|
+
|
|
76
|
+
But if the DRAFT ends up with the wrong final value, fix it. For example, it kept
|
|
77
|
+
"Tuesday" and dropped the correction to "Wednesday", or it mixed the two up.
|
|
78
|
+
Everything else follows the normal rules above.
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
VERSIONS = ("v1",)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def build_prompt(intended: str, pred: str, spoken: str, version: str = "v1") -> str:
|
|
85
|
+
if version not in VERSIONS:
|
|
86
|
+
raise ValueError(f"unknown version {version!r}, expected one of {VERSIONS}")
|
|
87
|
+
if spoken is None:
|
|
88
|
+
raise ValueError("the spoken text is required")
|
|
89
|
+
return BASE.format(
|
|
90
|
+
lenient=LENIENT,
|
|
91
|
+
spoken=f"<spoken>\n{spoken}\n</spoken>\n\n",
|
|
92
|
+
intended=intended or "",
|
|
93
|
+
draft=pred or "",
|
|
94
|
+
)
|
|
File without changes
|