@chaffjs/lang-ja 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/citation.d.ts +17 -1
  2. package/dist/citation.d.ts.map +1 -1
  3. package/dist/citation.js +22 -49
  4. package/dist/citation.js.map +1 -1
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +2 -5
  7. package/dist/index.js.map +1 -1
  8. package/dist/pos.d.ts.map +1 -1
  9. package/dist/pos.js +48 -12
  10. package/dist/pos.js.map +1 -1
  11. package/dist/quantities.d.ts +8 -0
  12. package/dist/quantities.d.ts.map +1 -1
  13. package/dist/quantities.js +53 -6
  14. package/dist/quantities.js.map +1 -1
  15. package/dist/section-reference.d.ts +14 -0
  16. package/dist/section-reference.d.ts.map +1 -0
  17. package/dist/section-reference.js +37 -0
  18. package/dist/section-reference.js.map +1 -0
  19. package/dist/sentence-split.d.ts +6 -0
  20. package/dist/sentence-split.d.ts.map +1 -0
  21. package/dist/sentence-split.js +114 -0
  22. package/dist/sentence-split.js.map +1 -0
  23. package/dist/structure.d.ts.map +1 -1
  24. package/dist/structure.js +45 -57
  25. package/dist/structure.js.map +1 -1
  26. package/dist/surface-starts.d.ts +6 -0
  27. package/dist/surface-starts.d.ts.map +1 -0
  28. package/dist/surface-starts.js +15 -0
  29. package/dist/surface-starts.js.map +1 -0
  30. package/lexicons/ai-tell.yaml +3 -3
  31. package/lexicons/closing-cliche.yaml +1 -1
  32. package/lexicons/document-kind.yaml +26 -0
  33. package/lexicons/double-keigo.yaml +10 -10
  34. package/lexicons/kana-title-kind.yaml +5 -0
  35. package/lexicons/name-note.yaml +7 -0
  36. package/lexicons/not-section-after.yaml +19 -0
  37. package/lexicons/not-section-before.yaml +11 -0
  38. package/lexicons/sasete-itadaku.yaml +3 -3
  39. package/lexicons/self-prefix.yaml +6 -0
  40. package/lexicons/total-label.yaml +9 -0
  41. package/lexicons/weekday.yaml +11 -0
  42. package/package.json +1 -1
  43. package/src/citation.ts +37 -52
  44. package/src/index.ts +2 -7
  45. package/src/pos.ts +51 -11
  46. package/src/quantities.ts +60 -6
  47. package/src/section-reference.ts +56 -0
  48. package/src/sentence-split.ts +131 -0
  49. package/src/structure.ts +51 -60
  50. package/src/surface-starts.ts +13 -0
package/src/citation.ts CHANGED
@@ -1,45 +1,35 @@
1
- // 他の文書を指す参照。「民法第709条」の第709条はこの文書の条ではない。
1
+ import type { Lexicon } from "chaffjs/plugin";
2
+
3
+ // 他の文書を指す参照。「民法第709条」の第709条はこの文書の条ではない。どの語が文書の名前を作るかは語彙表が持つ。
4
+
5
+ export type CitationVocabulary = {
6
+ /** 文書の種類の語。長いものから当てる。 */
7
+ readonly kinds: readonly string[];
8
+ /** 題名に平仮名を挟む種類。 */
9
+ readonly kanaTitleKinds: readonly string[];
10
+ /** 名前と番地のあいだに挟まる括弧書き。 */
11
+ readonly notes: readonly RegExp[];
12
+ /** この文書自身を指す名前の頭。 */
13
+ readonly selfPrefixes: readonly string[];
14
+ };
2
15
 
3
- /** 文書の種類を表す語。名前がこれで終われば、その直後の「第N条」はその文書の条。長いものから当てる。 */
4
- const DOCUMENT_KINDS = [
5
- "ガイドライン",
6
- "契約書",
7
- "法律",
8
- "条例",
9
- "条約",
10
- "契約",
11
- "規約",
12
- "規程",
13
- "規則",
14
- "約款",
15
- "細則",
16
- "要綱",
17
- "要領",
18
- "指針",
19
- "基準",
20
- "協定",
21
- "覚書",
22
- "告示",
23
- "通達",
24
- "法",
25
- "令",
26
- ];
16
+ const patternsOf = (lexicon: Lexicon | undefined): string[] => (lexicon ?? []).map((entry) => entry.pattern);
27
17
 
28
- /** 「本契約」「当規約」はこの文書自身。「同法」は前に出た別の法令なので、他の文書。 */
29
- const SELF_PREFIXES = ["本", "当"];
18
+ export const citationVocabulary = (lexicons: Readonly<Record<string, Lexicon>>): CitationVocabulary => ({
19
+ kinds: patternsOf(lexicons["document-kind"]).sort((left, right) => right.length - left.length),
20
+ kanaTitleKinds: patternsOf(lexicons["kana-title-kind"]),
21
+ notes: patternsOf(lexicons["name-note"]).map((pattern) => new RegExp(`(?:${pattern})$`, "u")),
22
+ selfPrefixes: patternsOf(lexicons["self-prefix"]),
23
+ });
30
24
 
31
25
  const NAME_CHAR = /[\p{Script=Han}\p{Script=Katakana}ー・A-Za-z0-9]/u;
26
+ const TITLE_CHAR = /[\p{Script=Han}\p{Script=Katakana}\p{Script=Hiragana}ー・A-Za-z0-9]/u;
32
27
 
33
28
  /** 名前は長くても数十字。後ろ向きに読む長さを抑え、長い行で遅くならないようにする。 */
34
29
  const MAX_NAME_LENGTH = 30;
35
30
 
36
- /**
37
- * at の直前に書かれた文書名。「民法第709条」なら「民法」。この文書の条を指すなら undefined。
38
- * 名前が種類の語だけ(「契約第3条」)のときも、どの文書か決まらないので undefined にする。
39
- */
40
- /** 法律の題名は平仮名を挟む(「個人情報の保護に関する法律」)。「法律」で終わるときだけ、平仮名もさかのぼって読む。 */
41
- const TITLE_CHAR = /[\p{Script=Han}\p{Script=Katakana}\p{Script=Hiragana}ー・A-Za-z0-9]/u;
42
- const LAW_TITLE_END = "法律";
31
+ /** 名前の後ろの括弧書きが収まる長さ。後ろ向きに読む長さを抑える。 */
32
+ const MAX_NOTE_LENGTH = 100;
43
33
 
44
34
  const nameBefore = (text: string, at: number, char: RegExp): string => {
45
35
  let start = at;
@@ -47,26 +37,21 @@ const nameBefore = (text: string, at: number, char: RegExp): string => {
47
37
  return text.slice(start, at);
48
38
  };
49
39
 
50
- /**
51
- * 法令は題名の後に公布の番号を括弧で添える(「国家行政組織法(昭和二十三年法律第百二十号)第三条」)。
52
- * 括弧を飛ばして、その前の題名を読む。
53
- */
54
- /** 番号に略称を添えることもある(「(平成十三年法律第百四十号。以下この章において「独立行政法人等情報公開法」という。)」)。 */
55
- const LAW_NUMBER_NOTE = /((?:明治|大正|昭和|平成|令和)[^()]{1,24}号(?:。以下[^()]{1,60}という。)?)$/u;
56
-
57
- /** 公布の番号と略称の括弧が収まる長さ。後ろ向きに読む長さを抑える。 */
58
- const MAX_NOTE_LENGTH = 100;
59
-
60
- const beforeLawNumber = (text: string, at: number): number => {
61
- const note = LAW_NUMBER_NOTE.exec(text.slice(Math.max(0, at - MAX_NOTE_LENGTH), at));
62
- return note === null ? at : at - note[0].length;
40
+ const beforeNote = (text: string, at: number, notes: readonly RegExp[]): number => {
41
+ const window = text.slice(Math.max(0, at - MAX_NOTE_LENGTH), at);
42
+ const note = notes.flatMap((pattern) => pattern.exec(window) ?? [])[0];
43
+ return note === undefined ? at : at - note.length;
63
44
  };
64
45
 
65
- export const citedDocument = (text: string, reference: number): string | undefined => {
66
- const at = beforeLawNumber(text, reference);
46
+ /**
47
+ * reference の直前に書かれた文書名。「民法第709条」なら「民法」。この文書の条を指すなら undefined。
48
+ * 名前が種類の語だけ(「契約第3条」)のときも、どの文書か決まらないので undefined にする。
49
+ */
50
+ export const citedDocument = (text: string, reference: number, vocabulary: CitationVocabulary): string | undefined => {
51
+ const at = beforeNote(text, reference, vocabulary.notes);
67
52
  const plain = nameBefore(text, at, NAME_CHAR);
68
- const name = plain === LAW_TITLE_END ? nameBefore(text, at, TITLE_CHAR) : plain;
69
- const kind = DOCUMENT_KINDS.find((candidate) => name.endsWith(candidate));
53
+ const name = vocabulary.kanaTitleKinds.includes(plain) ? nameBefore(text, at, TITLE_CHAR) : plain;
54
+ const kind = vocabulary.kinds.find((candidate) => name.endsWith(candidate));
70
55
  if (kind === undefined || name.length === kind.length) return undefined;
71
- return SELF_PREFIXES.some((prefix) => name.startsWith(prefix)) ? undefined : name;
56
+ return vocabulary.selfPrefixes.some((prefix) => name.startsWith(prefix)) ? undefined : name;
72
57
  };
package/src/index.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { split, SentenceSplitterSyntax } from "sentence-splitter";
2
1
  import { loadLexicons } from "./lexicons.ts";
2
+ import { sentenceSpans } from "./sentence-split.ts";
3
3
  import { structure } from "./structure.ts";
4
4
  import { isReady, predicateOnly, prepare, tokenize } from "./pos.ts";
5
5
  import type { AdapterNeeds, LanguageAdapter, Segmentation, Sentence, Span } from "chaffjs/plugin";
@@ -23,11 +23,6 @@ const COUNTABLE = /\S/gu;
23
23
 
24
24
  const isOpen = (text: string): boolean => text.trim().length > 0 && !CLOSED.test(text);
25
25
 
26
- const rawSpans = (text: string): Span[] =>
27
- split(text)
28
- .filter((node) => node.type === SentenceSplitterSyntax.Sentence)
29
- .map((node) => ({ start: node.range[0], end: node.range[1] }));
30
-
31
26
  /**
32
27
  * 断片を繋ぐときは raw の連結ではなくオフセットを使う。
33
28
  * sentence-splitter は空白を別ノードに分けるため、raw を繋ぐと空白が落ちて文長が縮む。
@@ -84,7 +79,7 @@ export const adapter: LanguageAdapter = {
84
79
  lexicons: loadLexicons(),
85
80
  structure,
86
81
  segment: (text: string): Segmentation => {
87
- const sentences = merge(text, rawSpans(text));
82
+ const sentences = merge(text, sentenceSpans(text));
88
83
  return { sentences: isReady() ? withTokens(text, sentences) : sentences };
89
84
  },
90
85
  };
package/src/pos.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { surfaceStarts } from "./surface-starts.ts";
1
2
  import { createRequire } from "node:module";
2
3
  import { dirname, join } from "node:path";
3
4
  import type { Token } from "chaffjs/plugin";
@@ -123,11 +124,11 @@ export const prepare = async (): Promise<void> => {
123
124
  export const isReady = (): boolean => state.ready !== undefined;
124
125
 
125
126
  /**
126
- * span は渡した文字列の先頭を 0 とする。kuromoji の word_position は 1 始まりなので 1 引く。
127
+ * span は渡した文字列の先頭を 0 とする。位置は kuromoji の word_position ではなく、語の文字を本文と照らして決める(surface-starts.ts)。
127
128
  * 形の違うものが混ざったら、その 1 つを落とす。位置が NaN の token を下流に流さない。
128
129
  */
129
- const toToken = (morpheme: Morpheme): Token => ({
130
- span: { start: morpheme.word_position - 1, end: morpheme.word_position - 1 + morpheme.surface_form.length },
130
+ const toToken = (morpheme: Morpheme, start: number): Token => ({
131
+ span: { start, end: start + morpheme.surface_form.length },
131
132
  surface: morpheme.surface_form,
132
133
  // UD の日本語では「れる/られる」は AUX。IPADIC の「動詞,接尾」をそこへ寄せる。
133
134
  pos: isPassive(morpheme) ? "AUX" : upos(morpheme.pos, morpheme.pos_detail_1),
@@ -135,9 +136,35 @@ const toToken = (morpheme: Morpheme): Token => ({
135
136
  ...featuresOf(morpheme),
136
137
  });
137
138
 
139
+ /**
140
+ * 数(名詞,数)。UPOS では名詞に寄せるので、数であることは UD の NumType=Card で渡す。
141
+ * 決まった言い回し(二人三脚、三日坊主、一人ひとり、十分)は辞書が一語として持つので、数にはならない。
142
+ */
143
+ const NUMERAL_TEXT = /^[〇一二三四五六七八九十百千万億兆0-90-9.,.,]+$/u;
144
+
145
+ /** 「数年」「何人」の「数」「何」も名詞,数だが、決まった数ではない。数字の文字でできたものだけ。 */
146
+ const isNumeral = (morpheme: Morpheme): boolean => morpheme.pos === "名詞" && morpheme.pos_detail_1 === "数" && NUMERAL_TEXT.test(morpheme.surface_form);
147
+
148
+ /**
149
+ * 地名(IPADIC の「固有名詞,地域」)は NameType=Geo、地名に付く単位(「接尾,地域」の都・県・市・区・町)は NameType=GeoUnit。
150
+ * 住所は地名と単位が交互に続く。地名が単位を挟まずに続けば(東京大阪名古屋)、地名の並び。
151
+ */
152
+ const placeType = (morpheme: Morpheme): string | undefined => {
153
+ if (morpheme.pos !== "名詞" || detail2Of(morpheme) !== "地域") return undefined;
154
+ if (morpheme.pos_detail_1 === "固有名詞") return "Geo";
155
+ return morpheme.pos_detail_1 === "接尾" ? "GeoUnit" : undefined;
156
+ };
157
+
158
+ /** 数を数える単位(IPADIC の「接尾,助数詞」: 丁目・件・人)。UD では NounType=Class。 */
159
+ const isCounter = (morpheme: Morpheme): boolean => morpheme.pos === "名詞" && morpheme.pos_detail_1 === "接尾" && detail2Of(morpheme) === "助数詞";
160
+
138
161
  const featuresOf = (morpheme: Morpheme): { features?: Readonly<Record<string, string>> } => {
139
162
  if (isPassive(morpheme)) return { features: { Voice: "Pass" } };
140
163
  if (isDependentNoun(morpheme)) return { features: { NounType: "Dependent" } };
164
+ if (isNumeral(morpheme)) return { features: { NumType: "Card" } };
165
+ const place = placeType(morpheme);
166
+ if (place !== undefined) return { features: { NameType: place } };
167
+ if (isCounter(morpheme)) return { features: { NounType: "Class" } };
141
168
  return {};
142
169
  };
143
170
 
@@ -172,9 +199,19 @@ export const predicateOnly = (tokens: readonly Token[]): Token[] =>
172
199
  export const tokenize = (text: string): Token[] | undefined => {
173
200
  const tokenizer = state.ready;
174
201
  if (tokenizer === undefined) return undefined;
175
- return toArray(callMethod(tokenizer, "tokenize", [text]))
176
- .filter(isMorpheme)
177
- .map(toToken);
202
+ return placed(text, toArray(callMethod(tokenizer, "tokenize", [text])).filter(isMorpheme)).map(({ morpheme, start }) => toToken(morpheme, start));
203
+ };
204
+
205
+ /** 形態素と、本文の中での始まり。本文に見つからないものは落とす。 */
206
+ const placed = (text: string, raws: readonly Morpheme[]): { readonly morpheme: Morpheme; readonly start: number }[] => {
207
+ const starts = surfaceStarts(
208
+ text,
209
+ raws.map((raw) => raw.surface_form),
210
+ );
211
+ return raws.flatMap((morpheme, index) => {
212
+ const start = starts[index];
213
+ return start === undefined ? [] : [{ morpheme, start }];
214
+ });
178
215
  };
179
216
 
180
217
  /**
@@ -200,9 +237,12 @@ const detail2Of = (value: unknown): string => {
200
237
  export const morphemes = (text: string): Morph[] | undefined => {
201
238
  const tokenizer = state.ready;
202
239
  if (tokenizer === undefined) return undefined;
203
- return toArray(callMethod(tokenizer, "tokenize", [text])).flatMap((raw) => {
204
- if (!isMorpheme(raw)) return [];
205
- const start = raw.word_position - 1;
206
- return [{ start, end: start + raw.surface_form.length, surface: raw.surface_form, pos: raw.pos, detail1: raw.pos_detail_1, detail2: detail2Of(raw) }];
207
- });
240
+ return placed(text, toArray(callMethod(tokenizer, "tokenize", [text])).filter(isMorpheme)).map(({ morpheme: raw, start }) => ({
241
+ start,
242
+ end: start + raw.surface_form.length,
243
+ surface: raw.surface_form,
244
+ pos: raw.pos,
245
+ detail1: raw.pos_detail_1,
246
+ detail2: detail2Of(raw),
247
+ }));
208
248
  };
package/src/quantities.ts CHANGED
@@ -47,10 +47,17 @@ const isJoiner = (morphs: readonly Morph[], index: number): boolean => {
47
47
  return morph !== undefined && [".", ",", ".", ","].includes(morph.surface) && isNumeral(morphs[index - 1]) && isNumeral(morphs[index + 1]);
48
48
  };
49
49
 
50
+ /** 桁の語。「26.7 万行」「1.2 万円」のように、数と空白 1 つを挟んで書かれても同じ数の一部。兆は数として読めないので入れない。 */
51
+ const MULTIPLIERS = new Set(["万", "億"]);
52
+
53
+ /** 数と桁の語のあいだの空白 1 つ。 */
54
+ const isSpacedMultiplier = (morphs: readonly Morph[], index: number): boolean =>
55
+ isSpace(morphs[index]) && isNumeral(morphs[index - 1]) && MULTIPLIERS.has(morphs[index + 1]?.surface ?? "");
56
+
50
57
  /** index から始まる数の並びの終わり(含まない)。 */
51
58
  const runEnd = (morphs: readonly Morph[], index: number): number => {
52
59
  let end = index;
53
- while (isNumeral(morphs[end]) || isJoiner(morphs, end)) end += 1;
60
+ while (isNumeral(morphs[end]) || isJoiner(morphs, end) || isSpacedMultiplier(morphs, end)) end += 1;
54
61
  return end;
55
62
  };
56
63
 
@@ -62,6 +69,8 @@ const GAP = new Set([" ", "\t", "\u3000"]);
62
69
 
63
70
  const isSpace = (morph: Morph | undefined): morph is Morph => morph !== undefined && GAP.has(morph.surface);
64
71
 
72
+ const SPACES = /[ \t\u3000]/gu;
73
+
65
74
  /**
66
75
  * 「1.5 倍」の「倍」は、数とのあいだに空白があると解析器が普通の名詞と読む。
67
76
  * 空白を詰めて読み直し、数の直後に来る語が助数詞ならその語を返す。
@@ -88,7 +97,7 @@ const countedByMorphemes = (text: string, morphs: readonly Morph[]): Counted[] =
88
97
  const end = runEnd(morphs, index);
89
98
  const first = morphs[index];
90
99
  if (first !== undefined && end > index && !isOrdinal(morphs[index - 1])) {
91
- const number = text.slice(first.start, morphs[end - 1]?.end ?? first.end);
100
+ const number = text.slice(first.start, morphs[end - 1]?.end ?? first.end).replace(SPACES, "");
92
101
  const value = parseJapaneseNumber(number);
93
102
  const counter = counterAt(text, morphs, number, end);
94
103
  if (value !== undefined && counter !== undefined) found.push({ start: first.start, end: counter.end, value, unit: counter.unit });
@@ -98,14 +107,15 @@ const countedByMorphemes = (text: string, morphs: readonly Morph[]): Counted[] =
98
107
  return found;
99
108
  };
100
109
 
101
- const NUMBER_RUN = /[0-90-9][0-90-9.,]{0,15}|[〇一二三四五六七八九十百千万億]{1,12}/gu;
110
+ /** 算用数字は、すぐ後ろか空白 1 つを挟んだ桁の語(1.2万、1.2 万)まで一つの数。形態素の経路と同じ読み方。 */
111
+ const NUMBER_RUN = /[0-90-9][0-90-9.,]{0,15}(?:[ \t\u3000]?[万億])?|[〇一二三四五六七八九十百千万億]{1,12}/gu;
102
112
 
103
- const countedByTable = (text: string): Counted[] =>
113
+ export const countedByTable = (text: string): Counted[] =>
104
114
  [...text.matchAll(NUMBER_RUN)].flatMap((match) => {
105
115
  // 形態素の経路と同じく、数と単位のあいだの空白 1 つは詰めて読む。
106
116
  const after = match.index + match[0].length + (GAP.has(text[match.index + match[0].length] ?? "") ? 1 : 0);
107
117
  const unit = UNITS.find((candidate) => text.startsWith(candidate, after));
108
- const value = parseJapaneseNumber(toHalfWidth(match[0]));
118
+ const value = parseJapaneseNumber(toHalfWidth(match[0].replace(SPACES, "")));
109
119
  const ordinal = text[match.index - 1] === "第";
110
120
  return unit === undefined || value === undefined || ordinal ? [] : [{ start: match.index, end: after + unit.length, value, unit }];
111
121
  });
@@ -171,7 +181,51 @@ const toDates = (items: readonly Counted[]): { readonly dates: Mention[]; readon
171
181
  export const quantities = (text: string): Mention[] =>
172
182
  toDates(counted(text)).rest.map((item) => ({ start: item.start, end: item.end, attrs: { value: item.value, unit: item.unit } }));
173
183
 
174
- export const dates = (text: string): Mention[] => toDates(counted(text)).dates;
184
+ /** 日付のすぐ後ろに書いた曜日(「2026年10月1日(木)」「10月1日 木曜日」)。日曜日が 0。 */
185
+ const WEEKDAY_CHARS = "日月火水木金土";
186
+ const WEEKDAY_AFTER = /^[ \t\u3000]*(?:[((](?<paren>[日月火水木金土])(?:曜日?)?[))]|(?<word>[日月火水木金土])曜日)/u;
187
+
188
+ const weekdayAfter = (text: string, end: number): number | undefined => {
189
+ const groups = WEEKDAY_AFTER.exec(text.slice(end))?.groups;
190
+ const written = groups?.["paren"] ?? groups?.["word"];
191
+ return written === undefined ? undefined : WEEKDAY_CHARS.indexOf(written);
192
+ };
193
+
194
+ /** 元号の最初の年の前年(令和1年 = 2019 年)。元号で書いた日付を西暦の日付にする。 */
195
+ const ERA_BASE: Readonly<Record<string, number>> = { 令和: 2018, 平成: 1988, 昭和: 1925, 大正: 1911, 明治: 1867 };
196
+ const ERA_BEFORE = /(?<era>令和|平成|昭和|大正|明治)$/u;
197
+ /** 月の付いた日付の年を直す。年だけ(「昭和二十二年法律」)は 1000 に届かないので、はじめから日付でなく期間の数量。 */
198
+ const ERA_DATE = /^(?<year>\d{1,2})-(?<rest>.+)$/u;
199
+
200
+ /** 「令和元年10月1日」: 元年は数として読めないので、年の無い 10-01 になっている。その前の「元号 + 元年」を 1 年として足す。 */
201
+ const FIRST_YEAR_BEFORE = /(?<era>令和|平成|昭和|大正|明治)元年$/u;
202
+ const MONTH_DAY = /^\d{2}-\d{2}$/u;
203
+
204
+ const inFirstEraYear = (text: string, date: Mention): Mention | undefined => {
205
+ if (!MONTH_DAY.test(String(date.attrs["value"]))) return undefined;
206
+ const found = FIRST_YEAR_BEFORE.exec(text.slice(Math.max(0, date.start - 4), date.start));
207
+ const base = found?.groups?.["era"] === undefined ? undefined : ERA_BASE[found.groups["era"]];
208
+ if (found === null || base === undefined) return undefined;
209
+ return { ...date, start: date.start - found[0].length, attrs: { ...date.attrs, value: `${String(base + 1)}-${String(date.attrs["value"])}` } };
210
+ };
211
+
212
+ const inWesternYear = (text: string, date: Mention): Mention => {
213
+ const first = inFirstEraYear(text, date);
214
+ if (first !== undefined) return first;
215
+ const parts = ERA_DATE.exec(String(date.attrs["value"]))?.groups;
216
+ const era = ERA_BEFORE.exec(text.slice(Math.max(0, date.start - 2), date.start))?.groups?.["era"];
217
+ const base = era === undefined ? undefined : ERA_BASE[era];
218
+ if (parts === undefined || era === undefined || base === undefined) return date;
219
+ const value = `${String(base + Number(parts["year"]))}-${parts["rest"] ?? ""}`;
220
+ return { ...date, start: date.start - era.length, attrs: { ...date.attrs, value } };
221
+ };
222
+
223
+ export const dates = (text: string): Mention[] =>
224
+ toDates(counted(text)).dates.map((found) => {
225
+ const date = inWesternYear(text, found);
226
+ const weekday = weekdayAfter(text, date.end);
227
+ return weekday === undefined ? date : { ...date, attrs: { ...date.attrs, weekday } };
228
+ });
175
229
 
176
230
  /**
177
231
  * 「1.5 倍になった。」の 1.5 は章番号ではない。番号と続く語のあいだの空白を詰めて読み直し、
@@ -0,0 +1,56 @@
1
+ import type { Lexicon, Mention } from "chaffjs/plugin";
2
+ import { toHalfWidth } from "./numbers.ts";
3
+
4
+ // 算用数字で番号を振った文書の中の参照(「3.2節」「第3章」「3.2.1項」)。番地は木の通し番号(### 3.2 → 3.2)と同じにする。
5
+ // 漢数字の「第三章」「第二節」は法令の書き方で、法令の番地は章ごと・編ごとに振り直すので、ここでは読まない。
6
+
7
+ export type SectionVocabulary = {
8
+ /** 番号の直前にあると番地でなくなる語(全3章・バージョン3.2)。 */
9
+ readonly notBefore: readonly string[];
10
+ /** 単位の字で始まる別の語(3.2節約・3項目)。 */
11
+ readonly notAfter: readonly string[];
12
+ };
13
+
14
+ const patternsOf = (lexicon: Lexicon | undefined): string[] => (lexicon ?? []).map((entry) => entry.pattern);
15
+
16
+ export const sectionVocabulary = (lexicons: Readonly<Record<string, Lexicon>>): SectionVocabulary => ({
17
+ notBefore: patternsOf(lexicons["not-section-before"]),
18
+ notAfter: patternsOf(lexicons["not-section-after"]),
19
+ });
20
+
21
+ /** 部品は 3 桁まで・深さは 6 まで。木の通し番号と同じ上限。 */
22
+ const SECTION = /(?:第[ \u3000]?)?(?<n>[0-90-9]{1,3}(?:[..][0-90-9]{1,3}){0,5})[ \u3000]?(?<unit>[章節項])/gu;
23
+
24
+ /** 番号の一部になる字が前にあれば、長い番号(2024.3.2)や版(v3.2)の途中。 */
25
+ const NUMBER_CHAR = /[0-90-9..A-Za-zA-Za-z]/u;
26
+
27
+ /** 章は「3章」、節と項は「3.2節」「3.2.1項」。点の無い「2節」「第2項」は数か法令の番地で、点のある「3.2章」は書かない。 */
28
+ const hasDots = (unit: string): boolean => unit !== "章";
29
+
30
+ /** 行頭の「3.2節 データ」「3.2節(データ)」「### 3.2節」は、その行の見出しの番号。本文の「3.2節で述べた」は参照。 */
31
+ const isLineLabel = (text: string, start: number, end: number): boolean => /^[#\s]*$/u.test(text.slice(0, start)) && /^(?:[\s((::]|$)/u.test(text.slice(end));
32
+
33
+ /** 「全 3 章」のように数える語と番号のあいだに空白があっても、数える語。見る長さは語彙の語が収まる分だけ。 */
34
+ const BEFORE_WINDOW = 20;
35
+ const wordBefore = (text: string, start: number): string => text.slice(Math.max(0, start - BEFORE_WINDOW), start).trimEnd();
36
+
37
+ const blocked = (text: string, start: number, unitAt: number, vocabulary: SectionVocabulary): boolean =>
38
+ NUMBER_CHAR.test(text[start - 1] ?? "") ||
39
+ vocabulary.notBefore.some((word) => wordBefore(text, start).endsWith(word)) ||
40
+ vocabulary.notAfter.some((word) => text.startsWith(word, unitAt));
41
+
42
+ /**
43
+ * 「3.2節」→ 3.2、「第3章」「3章」→ ch3。見出し「## 第3章」は木に ch3 として入る。見出しを「## 3. 構成」と書く文書では 3 なので、番号だけの見出しの 3 を fallback にする(第3条には当てない)。
44
+ * 他の文書の名前(民法第3章)は、条の参照と一緒に structure.ts が付ける。
45
+ */
46
+ export const sectionReferences = (text: string, vocabulary: SectionVocabulary): Mention[] =>
47
+ [...text.matchAll(SECTION)].flatMap((match) => {
48
+ const groups = match.groups ?? {};
49
+ const [written, unit] = [groups["n"] ?? "", groups["unit"] ?? ""];
50
+ const number = toHalfWidth(written).replace(/./gu, ".");
51
+ const end = match.index + match[0].length;
52
+ if (number.includes(".") !== hasDots(unit)) return [];
53
+ if (blocked(text, match.index, end - unit.length, vocabulary) || isLineLabel(text, match.index, end)) return [];
54
+ const address = unit === "章" ? { target: `ch${number}`, fallback: number, fallbackLabel: number } : { target: number };
55
+ return [{ start: match.index, end, attrs: { ...address, label: match[0] } }];
56
+ });
@@ -0,0 +1,131 @@
1
+ import { DefaultAbbrMarkerOptions, split, SentenceSplitterSyntax } from "sentence-splitter";
2
+ import type { Span } from "chaffjs/plugin";
3
+
4
+ /**
5
+ * sentence-splitter に長い段落を一度に渡すと、文の数の 2 乗で遅くなる。
6
+ * 文を閉じるたびに、それまでに閉じた括弧を全部並べ直すため。
7
+ *
8
+ * そこで分割器の状態が空に戻る所(文が閉じ、括弧も開いていない所)で切り、切れ目ごとに渡す。
9
+ * 切ってよいかは分割器の規則を写して決める。写し方が狂うと文が変わるので、迷う所では切らない。
10
+ */
11
+
12
+ // PairMaker と同じ組。開き括弧を鍵にする。
13
+ const PAIRS: readonly (readonly [string, string])[] = [
14
+ ['"', '"'],
15
+ ["[", "]"],
16
+ ["(", ")"],
17
+ ["{", "}"],
18
+ ["「", "」"],
19
+ ["(", ")"],
20
+ ["『", "』"],
21
+ ["{", "}"],
22
+ ["[", "]"],
23
+ ["〚", "〛"],
24
+ ["【", "】"],
25
+ ["《", "》"],
26
+ ];
27
+ const KEY_OF = new Map<string, string>(
28
+ PAIRS.flatMap(([open, close]): [string, string][] => [
29
+ [close, open],
30
+ [open, open],
31
+ ]),
32
+ );
33
+ const CLOSE_OF = new Map<string, string>(PAIRS.map(([open, close]): [string, string] => [open, close]));
34
+
35
+ // AbbrMarker の語の区切り。分割器は UTF-16 の 1 単位ずつ読むので、こちらも 1 単位で判定する。
36
+ const CJK = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
37
+ const isCJK = (unit: string | undefined): boolean => unit !== undefined && CJK.test(unit);
38
+ const isSpace = (unit: string | undefined): boolean => unit !== undefined && /\s/.test(unit);
39
+
40
+ // 和文の句点の並び。直前が仮名・漢字なら、略語の判定がこの句点に掛かることはない。
41
+ const JAPANESE_STOPS = /[。.?!]+/g;
42
+ // 英語は「空白の後の英字だけの語 + ピリオド + 空白」。略語の一覧に無い語だけを切れ目にする。
43
+ const ENGLISH_STOP = /(?<=^|\s)[A-Za-z]{2,}\.(?=\s)/g;
44
+ const { language } = DefaultAbbrMarkerOptions;
45
+ const ABBREVIATIONS = new Set(
46
+ [...language.ABBREVIATIONS, ...language.PREPOSITIVE_ABBREVIATIONS, ...language.EXCLAMATION_WORDS].map((word) => word.toLowerCase()),
47
+ );
48
+ // 「J. Smith」のような語は前の語を見て略語か決まる。前の語が切れ目の向こうにあると判定が変わる。
49
+ const CAPITAL_DOT = /\p{Lu}\./gu;
50
+
51
+ /** 各位置の手前で、開いたままの括弧があるか。PairMaker と同じく種類ごとに 1 つまで開く。 */
52
+ const pairOpenBefore = (text: string): boolean[] => {
53
+ const open = new Set<string>();
54
+ const before = [false];
55
+ text.split("").forEach((unit) => {
56
+ const key = KEY_OF.get(unit);
57
+ if (key !== undefined && !open.has(key) && unit === key) open.add(key);
58
+ else if (key !== undefined && open.has(key) && unit === CLOSE_OF.get(key)) open.delete(key);
59
+ before.push(open.size > 0);
60
+ });
61
+ return before;
62
+ };
63
+
64
+ /** sorted の中で from 以上の最初の値。無ければ fallback。 */
65
+ const firstAtOrAfter = (sorted: readonly number[], from: number, fallback: number): number => {
66
+ const search = (low: number, high: number): number => {
67
+ if (low >= high) return sorted[low] ?? fallback;
68
+ const middle = Math.floor((low + high) / 2);
69
+ return (sorted[middle] ?? fallback) >= from ? search(low, middle) : search(middle + 1, high);
70
+ };
71
+ return search(0, sorted.length);
72
+ };
73
+
74
+ const indexesOf = (text: string, pattern: RegExp): number[] => [...text.matchAll(pattern)].map((match) => match.index);
75
+
76
+ /** 句点の並びの直後。和文は直前が仮名・漢字の句点、英文は略語でない語のピリオド。 */
77
+ const stopEnds = (text: string): number[] => {
78
+ const japanese = [...text.matchAll(JAPANESE_STOPS)].filter((match) => isCJK(text[match.index - 1]));
79
+ const english = [...text.matchAll(ENGLISH_STOP)].filter((match) => !ABBREVIATIONS.has(match[0].toLowerCase()));
80
+ return [...japanese, ...english].map((match) => match.index + match[0].length).sort((a, b) => a - b);
81
+ };
82
+
83
+ const skipSpaces = (text: string, from: number): number => {
84
+ const spaces = /\s*/y;
85
+ spaces.lastIndex = from;
86
+ return from + (spaces.exec(text)?.[0].length ?? 0);
87
+ };
88
+
89
+ /**
90
+ * 句点の直後から次の文の頭へ。空白を挟むか、仮名・漢字が続くときだけ切れる。
91
+ * それ以外の文字が続くと、分割器はその文字を前の語の続きとして読む。
92
+ */
93
+ const chunkStart = (text: string, stopEnd: number): number | undefined => {
94
+ const next = text[stopEnd];
95
+ if (isSpace(next)) return skipSpaces(text, stopEnd);
96
+ return isCJK(next) ? stopEnd : undefined;
97
+ };
98
+
99
+ type Landmarks = { readonly open: readonly boolean[]; readonly spaces: readonly number[]; readonly capitalDots: readonly number[] };
100
+
101
+ /**
102
+ * 切れ目の後ろ、最初の 2 つの語の塊に「J.」の形が無いこと。
103
+ * 分割器はその形の語だけ、空白を越えて前の語を読み返す。
104
+ */
105
+ const noLookBack = (text: string, start: number, marks: Landmarks): boolean => {
106
+ const secondRun = skipSpaces(text, firstAtOrAfter(marks.spaces, start, text.length));
107
+ return firstAtOrAfter(marks.capitalDots, start, Infinity) > secondRun;
108
+ };
109
+
110
+ const cutPoints = (text: string): number[] => {
111
+ const marks: Landmarks = { open: pairOpenBefore(text), spaces: indexesOf(text, /\s/g), capitalDots: indexesOf(text, CAPITAL_DOT) };
112
+ return stopEnds(text).flatMap((stopEnd) => {
113
+ if (marks.open[stopEnd] === true) return [];
114
+ const start = chunkStart(text, stopEnd);
115
+ return start !== undefined && start < text.length && noLookBack(text, start, marks) ? [start] : [];
116
+ });
117
+ };
118
+
119
+ const spansOf = (text: string, offset: number): Span[] =>
120
+ split(text)
121
+ .filter((node) => node.type === SentenceSplitterSyntax.Sentence)
122
+ .map((node) => ({ start: offset + node.range[0], end: offset + node.range[1] }));
123
+
124
+ /** 分割器に別々に渡してよい区間。つなぐと text 全体になる。 */
125
+ export const chunksOf = (text: string): Span[] => {
126
+ const starts = [0, ...cutPoints(text)];
127
+ return starts.map((start, index) => ({ start, end: starts[index + 1] ?? text.length }));
128
+ };
129
+
130
+ /** split(text) の文の span と同じものを返す。区間ごとに分けて渡すだけ。 */
131
+ export const sentenceSpans = (text: string): Span[] => chunksOf(text).flatMap((chunk) => spansOf(text.slice(chunk.start, chunk.end), chunk.start));