ModerRAS commited on
Commit
d8ddb0b
·
1 Parent(s): 0944d16

fix(dataset): repair training-set alignment + relabel teneighty as GROUP; add Rust repair tool

Browse files
.gitignore CHANGED
@@ -22,3 +22,8 @@ reports/
22
  reports/generated/
23
  target/
24
  **/target/
 
 
 
 
 
 
22
  reports/generated/
23
  target/
24
  **/target/
25
+
26
+ # 本地工作/审计产物,不入库
27
+ .workbuddy/
28
+ data/repair_report.json
29
+ data/dmhy_weak_char.repaired.manifest.json
datasets/AnimeName CHANGED
@@ -1 +1 @@
1
- Subproject commit 6d94ea67d836aa79325e280f4600f91689ba0e4a
 
1
+ Subproject commit 061e59eddd03a157cb6b2deb13c4dc964630d4a4
tools/repair_bracket_mismatch/Cargo.lock ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is automatically @generated by Cargo.
2
+ # It is not intended for manual editing.
3
+ version = 4
4
+
5
+ [[package]]
6
+ name = "anifilebert-repair-bracket-mismatch"
7
+ version = "0.1.0"
8
+ dependencies = [
9
+ "anyhow",
10
+ "clap",
11
+ "serde",
12
+ "serde_json",
13
+ ]
14
+
15
+ [[package]]
16
+ name = "anstream"
17
+ version = "1.0.0"
18
+ source = "registry+https://github.com/rust-lang/crates.io-index"
19
+ checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
20
+ dependencies = [
21
+ "anstyle",
22
+ "anstyle-parse",
23
+ "anstyle-query",
24
+ "anstyle-wincon",
25
+ "colorchoice",
26
+ "is_terminal_polyfill",
27
+ "utf8parse",
28
+ ]
29
+
30
+ [[package]]
31
+ name = "anstyle"
32
+ version = "1.0.14"
33
+ source = "registry+https://github.com/rust-lang/crates.io-index"
34
+ checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
35
+
36
+ [[package]]
37
+ name = "anstyle-parse"
38
+ version = "1.0.0"
39
+ source = "registry+https://github.com/rust-lang/crates.io-index"
40
+ checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
41
+ dependencies = [
42
+ "utf8parse",
43
+ ]
44
+
45
+ [[package]]
46
+ name = "anstyle-query"
47
+ version = "1.1.5"
48
+ source = "registry+https://github.com/rust-lang/crates.io-index"
49
+ checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
50
+ dependencies = [
51
+ "windows-sys",
52
+ ]
53
+
54
+ [[package]]
55
+ name = "anstyle-wincon"
56
+ version = "3.0.11"
57
+ source = "registry+https://github.com/rust-lang/crates.io-index"
58
+ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
59
+ dependencies = [
60
+ "anstyle",
61
+ "once_cell_polyfill",
62
+ "windows-sys",
63
+ ]
64
+
65
+ [[package]]
66
+ name = "anyhow"
67
+ version = "1.0.104"
68
+ source = "registry+https://github.com/rust-lang/crates.io-index"
69
+ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
70
+
71
+ [[package]]
72
+ name = "clap"
73
+ version = "4.6.5"
74
+ source = "registry+https://github.com/rust-lang/crates.io-index"
75
+ checksum = "301b56658598e48f3648647ac6fc887be7e7108eddfa4e9b63fcf3ec58c0cadf"
76
+ dependencies = [
77
+ "clap_builder",
78
+ "clap_derive",
79
+ ]
80
+
81
+ [[package]]
82
+ name = "clap_builder"
83
+ version = "4.6.5"
84
+ source = "registry+https://github.com/rust-lang/crates.io-index"
85
+ checksum = "94a65403d1a1bd28f7dc68eb8506e8874808ee5eecb59298de588e2e1407a078"
86
+ dependencies = [
87
+ "anstream",
88
+ "anstyle",
89
+ "clap_lex",
90
+ "strsim",
91
+ ]
92
+
93
+ [[package]]
94
+ name = "clap_derive"
95
+ version = "4.6.4"
96
+ source = "registry+https://github.com/rust-lang/crates.io-index"
97
+ checksum = "d012d2b9d65aca7f18f4d9878a045bc17899bba951561ba5ec3c2ba1eed9a061"
98
+ dependencies = [
99
+ "heck",
100
+ "proc-macro2",
101
+ "quote",
102
+ "syn",
103
+ ]
104
+
105
+ [[package]]
106
+ name = "clap_lex"
107
+ version = "1.1.0"
108
+ source = "registry+https://github.com/rust-lang/crates.io-index"
109
+ checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
110
+
111
+ [[package]]
112
+ name = "colorchoice"
113
+ version = "1.0.5"
114
+ source = "registry+https://github.com/rust-lang/crates.io-index"
115
+ checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
116
+
117
+ [[package]]
118
+ name = "heck"
119
+ version = "0.5.0"
120
+ source = "registry+https://github.com/rust-lang/crates.io-index"
121
+ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
122
+
123
+ [[package]]
124
+ name = "is_terminal_polyfill"
125
+ version = "1.70.2"
126
+ source = "registry+https://github.com/rust-lang/crates.io-index"
127
+ checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
128
+
129
+ [[package]]
130
+ name = "itoa"
131
+ version = "1.0.18"
132
+ source = "registry+https://github.com/rust-lang/crates.io-index"
133
+ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
134
+
135
+ [[package]]
136
+ name = "memchr"
137
+ version = "2.8.3"
138
+ source = "registry+https://github.com/rust-lang/crates.io-index"
139
+ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
140
+
141
+ [[package]]
142
+ name = "once_cell_polyfill"
143
+ version = "1.70.2"
144
+ source = "registry+https://github.com/rust-lang/crates.io-index"
145
+ checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
146
+
147
+ [[package]]
148
+ name = "proc-macro2"
149
+ version = "1.0.107"
150
+ source = "registry+https://github.com/rust-lang/crates.io-index"
151
+ checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
152
+ dependencies = [
153
+ "unicode-ident",
154
+ ]
155
+
156
+ [[package]]
157
+ name = "quote"
158
+ version = "1.0.47"
159
+ source = "registry+https://github.com/rust-lang/crates.io-index"
160
+ checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
161
+ dependencies = [
162
+ "proc-macro2",
163
+ ]
164
+
165
+ [[package]]
166
+ name = "serde"
167
+ version = "1.0.229"
168
+ source = "registry+https://github.com/rust-lang/crates.io-index"
169
+ checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
170
+ dependencies = [
171
+ "serde_core",
172
+ "serde_derive",
173
+ ]
174
+
175
+ [[package]]
176
+ name = "serde_core"
177
+ version = "1.0.229"
178
+ source = "registry+https://github.com/rust-lang/crates.io-index"
179
+ checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
180
+ dependencies = [
181
+ "serde_derive",
182
+ ]
183
+
184
+ [[package]]
185
+ name = "serde_derive"
186
+ version = "1.0.229"
187
+ source = "registry+https://github.com/rust-lang/crates.io-index"
188
+ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
189
+ dependencies = [
190
+ "proc-macro2",
191
+ "quote",
192
+ "syn",
193
+ ]
194
+
195
+ [[package]]
196
+ name = "serde_json"
197
+ version = "1.0.151"
198
+ source = "registry+https://github.com/rust-lang/crates.io-index"
199
+ checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
200
+ dependencies = [
201
+ "itoa",
202
+ "memchr",
203
+ "serde",
204
+ "serde_core",
205
+ "zmij",
206
+ ]
207
+
208
+ [[package]]
209
+ name = "strsim"
210
+ version = "0.11.1"
211
+ source = "registry+https://github.com/rust-lang/crates.io-index"
212
+ checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
213
+
214
+ [[package]]
215
+ name = "syn"
216
+ version = "3.0.3"
217
+ source = "registry+https://github.com/rust-lang/crates.io-index"
218
+ checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"
219
+ dependencies = [
220
+ "proc-macro2",
221
+ "quote",
222
+ "unicode-ident",
223
+ ]
224
+
225
+ [[package]]
226
+ name = "unicode-ident"
227
+ version = "1.0.24"
228
+ source = "registry+https://github.com/rust-lang/crates.io-index"
229
+ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
230
+
231
+ [[package]]
232
+ name = "utf8parse"
233
+ version = "0.2.2"
234
+ source = "registry+https://github.com/rust-lang/crates.io-index"
235
+ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
236
+
237
+ [[package]]
238
+ name = "windows-link"
239
+ version = "0.2.1"
240
+ source = "registry+https://github.com/rust-lang/crates.io-index"
241
+ checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
242
+
243
+ [[package]]
244
+ name = "windows-sys"
245
+ version = "0.61.2"
246
+ source = "registry+https://github.com/rust-lang/crates.io-index"
247
+ checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
248
+ dependencies = [
249
+ "windows-link",
250
+ ]
251
+
252
+ [[package]]
253
+ name = "zmij"
254
+ version = "1.0.23"
255
+ source = "registry+https://github.com/rust-lang/crates.io-index"
256
+ checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
tools/repair_bracket_mismatch/Cargo.toml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ [package]
2
+ name = "anifilebert-repair-bracket-mismatch"
3
+ version = "0.1.0"
4
+ edition = "2021"
5
+
6
+ [dependencies]
7
+ anyhow = "1.0"
8
+ clap = { version = "4.5", features = ["derive"] }
9
+ serde = { version = "1.0", features = ["derive"] }
10
+ serde_json = "1.0"
tools/repair_bracket_mismatch/src/main.rs ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use std::collections::BTreeMap;
2
+ use std::fs::{self, File};
3
+ use std::io::{self, BufRead, BufReader, BufWriter, Write};
4
+ use std::path::PathBuf;
5
+ use std::sync::LazyLock;
6
+
7
+ use anyhow::{Context, Result};
8
+ use clap::Parser;
9
+ use serde::Deserialize;
10
+ use serde_json::{json, Value};
11
+
12
+ #[derive(Parser)]
13
+ #[command(about = "Repair bracket/case misalignment and mislabeled release groups in the DMHY char-level dataset")]
14
+ struct Args {
15
+ #[arg(long, default_value = "datasets\\AnimeName\\dmhy_weak_char.jsonl")]
16
+ input: PathBuf,
17
+ #[arg(long, default_value = "data\\dmhy_weak_char.repaired.jsonl")]
18
+ output: PathBuf,
19
+ #[arg(long, default_value = "data\\repair_report.json")]
20
+ report: PathBuf,
21
+ /// Compute and print statistics without writing the repaired dataset.
22
+ #[arg(long)]
23
+ dry_run: bool,
24
+ }
25
+
26
+ #[derive(Deserialize)]
27
+ struct Record {
28
+ filename: String,
29
+ #[serde(default)]
30
+ tokens: Vec<String>,
31
+ labels: Vec<String>,
32
+ #[serde(default)]
33
+ template: Option<String>,
34
+ #[serde(default)]
35
+ tokenizer_variant: Option<String>,
36
+ }
37
+
38
+ /// Release groups that appear un-bracketed as a filename prefix and were found
39
+ /// mislabeled as TITLE. Extend this list as more groups are confirmed.
40
+ static KNOWN_GROUPS: LazyLock<Vec<String>> = LazyLock::new(|| vec!["teneighty".to_string()]);
41
+
42
+ #[derive(Clone, Copy, PartialEq)]
43
+ enum AlignKind {
44
+ Bracket,
45
+ Case,
46
+ }
47
+
48
+ #[derive(Default)]
49
+ struct Stats {
50
+ total: usize,
51
+ already_ok: usize,
52
+ normalized: usize,
53
+ repaired_bracket: usize,
54
+ repaired_case: usize,
55
+ unrepairable: usize,
56
+ group_relabeled: usize,
57
+ examples: BTreeMap<String, Vec<Value>>,
58
+ }
59
+
60
+ fn main() -> Result<()> {
61
+ let args = Args::parse();
62
+
63
+ let input = File::open(&args.input)
64
+ .with_context(|| format!("failed to open {}", args.input.display()))?;
65
+ let reader = BufReader::new(input);
66
+
67
+ if !args.dry_run {
68
+ if let Some(parent) = args.output.parent() {
69
+ if !parent.as_os_str().is_empty() {
70
+ fs::create_dir_all(parent)
71
+ .with_context(|| format!("failed to create {}", parent.display()))?;
72
+ }
73
+ }
74
+ }
75
+
76
+ let mut out: Box<dyn Write> = if args.dry_run {
77
+ Box::new(io::sink())
78
+ } else {
79
+ let f = File::create(&args.output)
80
+ .with_context(|| format!("failed to create {}", args.output.display()))?;
81
+ Box::new(BufWriter::new(f))
82
+ };
83
+
84
+ let mut stats = Stats::default();
85
+
86
+ for (lineno, line) in reader.lines().enumerate() {
87
+ let line = line.with_context(|| format!("failed to read line {}", lineno + 1))?;
88
+ if line.trim().is_empty() {
89
+ continue;
90
+ }
91
+ let rec: Record = serde_json::from_str(&line)
92
+ .with_context(|| format!("failed to parse line {}", lineno + 1))?;
93
+ stats.total += 1;
94
+
95
+ let old_joined: String = rec.tokens.concat();
96
+ let fn_chars: Vec<char> = rec.filename.chars().collect();
97
+ let perfectly_aligned = rec.filename == old_joined
98
+ && rec.tokens.len() == fn_chars.len()
99
+ && rec.labels.len() == rec.tokens.len();
100
+
101
+ if perfectly_aligned {
102
+ let new_tokens = rec.tokens.clone();
103
+ let mut new_labels = rec.labels.clone();
104
+ if relabel_groups(&new_tokens, &mut new_labels) {
105
+ stats.group_relabeled += 1;
106
+ push_example(
107
+ &mut stats,
108
+ "group_relabeled",
109
+ &rec.filename,
110
+ &rec.tokens,
111
+ &rec.labels,
112
+ &new_tokens,
113
+ &new_labels,
114
+ );
115
+ }
116
+ stats.already_ok += 1;
117
+ if !args.dry_run {
118
+ write_record(
119
+ &mut out,
120
+ &rec.filename,
121
+ &new_tokens,
122
+ &new_labels,
123
+ rec.template.as_deref(),
124
+ rec.tokenizer_variant.as_deref(),
125
+ )?;
126
+ }
127
+ continue;
128
+ }
129
+
130
+ match align_to_filename(&rec.filename, &rec.tokens, &rec.labels) {
131
+ Some((new_tokens, new_labels, kind)) => {
132
+ let mut final_labels = new_labels;
133
+ let grp = relabel_groups(&new_tokens, &mut final_labels);
134
+
135
+ if rec.filename == old_joined && rec.tokens.len() != fn_chars.len() {
136
+ // Content identical but token granularity was not char-level.
137
+ stats.normalized += 1;
138
+ push_example(
139
+ &mut stats,
140
+ "normalized",
141
+ &rec.filename,
142
+ &rec.tokens,
143
+ &rec.labels,
144
+ &new_tokens,
145
+ &final_labels,
146
+ );
147
+ } else if kind == AlignKind::Case {
148
+ stats.repaired_case += 1;
149
+ push_example(
150
+ &mut stats,
151
+ "repaired_case",
152
+ &rec.filename,
153
+ &rec.tokens,
154
+ &rec.labels,
155
+ &new_tokens,
156
+ &final_labels,
157
+ );
158
+ } else {
159
+ stats.repaired_bracket += 1;
160
+ push_example(
161
+ &mut stats,
162
+ "repaired_bracket",
163
+ &rec.filename,
164
+ &rec.tokens,
165
+ &rec.labels,
166
+ &new_tokens,
167
+ &final_labels,
168
+ );
169
+ }
170
+
171
+ if grp {
172
+ stats.group_relabeled += 1;
173
+ push_example(
174
+ &mut stats,
175
+ "group_relabeled",
176
+ &rec.filename,
177
+ &rec.tokens,
178
+ &rec.labels,
179
+ &new_tokens,
180
+ &final_labels,
181
+ );
182
+ }
183
+
184
+ if !args.dry_run {
185
+ write_record(
186
+ &mut out,
187
+ &rec.filename,
188
+ &new_tokens,
189
+ &final_labels,
190
+ rec.template.as_deref(),
191
+ rec.tokenizer_variant.as_deref(),
192
+ )?;
193
+ }
194
+ }
195
+ None => {
196
+ stats.unrepairable += 1;
197
+ push_example(
198
+ &mut stats,
199
+ "unrepairable",
200
+ &rec.filename,
201
+ &rec.tokens,
202
+ &rec.labels,
203
+ &rec.tokens,
204
+ &rec.labels,
205
+ );
206
+ if !args.dry_run {
207
+ write_record(
208
+ &mut out,
209
+ &rec.filename,
210
+ &rec.tokens,
211
+ &rec.labels,
212
+ rec.template.as_deref(),
213
+ rec.tokenizer_variant.as_deref(),
214
+ )?;
215
+ }
216
+ }
217
+ }
218
+ }
219
+ out.flush()?;
220
+
221
+ let summary = json!({
222
+ "total": stats.total,
223
+ "already_ok": stats.already_ok,
224
+ "normalized": stats.normalized,
225
+ "repaired_bracket": stats.repaired_bracket,
226
+ "repaired_case": stats.repaired_case,
227
+ "unrepairable": stats.unrepairable,
228
+ "group_relabeled": stats.group_relabeled,
229
+ });
230
+
231
+ if args.dry_run {
232
+ let report = json!({
233
+ "input": args.input.display().to_string(),
234
+ "dry_run": true,
235
+ "summary": summary,
236
+ "examples": stats.examples,
237
+ });
238
+ println!("{}", serde_json::to_string_pretty(&report)?);
239
+ } else {
240
+ let report = json!({
241
+ "input": args.input.display().to_string(),
242
+ "output": args.output.display().to_string(),
243
+ "dry_run": false,
244
+ "summary": summary,
245
+ "examples": stats.examples,
246
+ });
247
+ let rf = File::create(&args.report)
248
+ .with_context(|| format!("failed to create {}", args.report.display()))?;
249
+ serde_json::to_writer_pretty(BufWriter::new(rf), &report)?;
250
+ println!("{}", serde_json::to_string_pretty(&summary)?);
251
+ println!("wrote repaired dataset -> {}", args.output.display());
252
+ println!("wrote report -> {}", args.report.display());
253
+ }
254
+
255
+ Ok(())
256
+ }
257
+
258
+ /// Reconstruct character-level tokens/labels from `filename`, projecting the
259
+ /// old character-level labels onto the filename characters. Characters present
260
+ /// in `filename` but absent from the joined old tokens (e.g. dropped brackets)
261
+ /// become `O`; case-only differences are tolerated.
262
+ fn align_to_filename(
263
+ filename: &str,
264
+ old_tokens: &[String],
265
+ old_labels: &[String],
266
+ ) -> Option<(Vec<String>, Vec<String>, AlignKind)> {
267
+ let mut old_chars: Vec<char> = Vec::new();
268
+ for t in old_tokens {
269
+ for c in t.chars() {
270
+ old_chars.push(c);
271
+ }
272
+ }
273
+ if old_chars.len() != old_labels.len() {
274
+ return None;
275
+ }
276
+ let fn_chars: Vec<char> = filename.chars().collect();
277
+ if fn_chars.len() < old_chars.len() {
278
+ // filename is missing characters relative to the labels -> cannot repair
279
+ return None;
280
+ }
281
+
282
+ let mut new_labels = Vec::with_capacity(fn_chars.len());
283
+ let mut o_ptr = 0usize;
284
+ let mut had_case = false;
285
+
286
+ for &ch in &fn_chars {
287
+ if o_ptr < old_chars.len() && old_chars[o_ptr] == ch {
288
+ new_labels.push(old_labels[o_ptr].clone());
289
+ o_ptr += 1;
290
+ } else if o_ptr < old_chars.len()
291
+ && old_chars[o_ptr].to_lowercase().eq(ch.to_lowercase())
292
+ && old_chars[o_ptr] != ch
293
+ {
294
+ // case-only difference (e.g. filename `s02e01` vs labels `S02E01`)
295
+ new_labels.push(old_labels[o_ptr].clone());
296
+ o_ptr += 1;
297
+ had_case = true;
298
+ } else {
299
+ // character inserted relative to old (typically a bracket)
300
+ new_labels.push("O".to_string());
301
+ }
302
+ }
303
+
304
+ if o_ptr != old_chars.len() {
305
+ // some old characters were never matched -> real deletion -> unrepairable
306
+ return None;
307
+ }
308
+
309
+ let new_tokens = fn_chars.iter().map(|c| c.to_string()).collect();
310
+ let kind = if had_case {
311
+ AlignKind::Case
312
+ } else {
313
+ AlignKind::Bracket
314
+ };
315
+ Some((new_tokens, new_labels, kind))
316
+ }
317
+
318
+ /// Rewrite a leading known release-group span (currently labeled TITLE_*) as
319
+ /// GROUP. Returns true if any labels were changed.
320
+ fn relabel_groups(tokens: &[String], labels: &mut [String]) -> bool {
321
+ let n = tokens.len();
322
+ if n == 0 {
323
+ return false;
324
+ }
325
+ let start = match (0..n).find(|&i| labels[i] != "O") {
326
+ Some(s) => s,
327
+ None => return false,
328
+ };
329
+ let lab0 = labels[start].clone();
330
+ if !lab0.starts_with("B-") {
331
+ // Not at the start of a BIO span; leave it alone.
332
+ return false;
333
+ }
334
+ let entity = lab0[2..].to_string();
335
+ let continuation = format!("I-{entity}");
336
+ let mut end = start;
337
+ while end + 1 < n && labels[end + 1] == continuation {
338
+ end += 1;
339
+ }
340
+ let span_text: String = tokens[start..=end].concat();
341
+ if !KNOWN_GROUPS.iter().any(|g| g == &span_text) {
342
+ return false;
343
+ }
344
+ labels[start] = "B-GROUP".to_string();
345
+ for i in (start + 1)..=end {
346
+ labels[i] = "I-GROUP".to_string();
347
+ }
348
+ true
349
+ }
350
+
351
+ fn write_record<W: Write>(
352
+ w: &mut W,
353
+ filename: &str,
354
+ tokens: &[String],
355
+ labels: &[String],
356
+ template: Option<&str>,
357
+ variant: Option<&str>,
358
+ ) -> Result<()> {
359
+ let obj = json!({
360
+ "filename": filename,
361
+ "tokens": tokens,
362
+ "labels": labels,
363
+ "template": template,
364
+ "tokenizer_variant": variant,
365
+ });
366
+ serde_json::to_writer(&mut *w, &obj)?;
367
+ w.write_all(b"\n")?;
368
+ Ok(())
369
+ }
370
+
371
+ fn push_example(
372
+ stats: &mut Stats,
373
+ key: &str,
374
+ filename: &str,
375
+ before_tokens: &[String],
376
+ before_labels: &[String],
377
+ after_tokens: &[String],
378
+ after_labels: &[String],
379
+ ) {
380
+ let arr = stats.examples.entry(key.to_string()).or_default();
381
+ if arr.len() >= 25 {
382
+ return;
383
+ }
384
+ arr.push(json!({
385
+ "filename": filename,
386
+ "before": spans_text(before_tokens, before_labels),
387
+ "after": spans_text(after_tokens, after_labels),
388
+ }));
389
+ }
390
+
391
+ fn spans_text(tokens: &[String], labels: &[String]) -> String {
392
+ let mut out = String::new();
393
+ let mut i = 0;
394
+ while i < labels.len() {
395
+ let lab = labels[i].clone();
396
+ if lab == "O" {
397
+ let mut j = i;
398
+ while j + 1 < labels.len() && labels[j + 1] == "O" {
399
+ j += 1;
400
+ }
401
+ let text: String = tokens[i..=j].concat();
402
+ out.push_str(&format!(" {text}[O]"));
403
+ i = j + 1;
404
+ continue;
405
+ }
406
+ if !lab.starts_with("B-") {
407
+ // lone I- without a preceding B-: render as its own span
408
+ let mut j = i;
409
+ while j + 1 < labels.len() && labels[j + 1] == lab {
410
+ j += 1;
411
+ }
412
+ let text: String = tokens[i..=j].concat();
413
+ out.push_str(&format!(" {text}[{lab}]"));
414
+ i = j + 1;
415
+ continue;
416
+ }
417
+ let entity = lab[2..].to_string();
418
+ let continuation = format!("I-{entity}");
419
+ let mut j = i;
420
+ while j + 1 < labels.len() && labels[j + 1] == continuation {
421
+ j += 1;
422
+ }
423
+ let text: String = tokens[i..=j].concat();
424
+ out.push_str(&format!(" {text}[{lab}]"));
425
+ i = j + 1;
426
+ }
427
+ out.trim_start().to_string()
428
+ }