@chaffjs/lang-ja 0.14.0 → 0.16.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 (58) hide show
  1. package/dist/citation.d.ts +3 -1
  2. package/dist/citation.d.ts.map +1 -1
  3. package/dist/citation.js +8 -3
  4. package/dist/citation.js.map +1 -1
  5. package/dist/counter-tsu.d.ts +4 -0
  6. package/dist/counter-tsu.d.ts.map +1 -1
  7. package/dist/counter-tsu.js.map +1 -1
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +11 -8
  10. package/dist/index.js.map +1 -1
  11. package/dist/lexicons.d.ts.map +1 -1
  12. package/dist/lexicons.js +5 -6
  13. package/dist/lexicons.js.map +1 -1
  14. package/dist/passive-reading.d.ts +6 -1
  15. package/dist/passive-reading.d.ts.map +1 -1
  16. package/dist/passive-reading.js +62 -9
  17. package/dist/passive-reading.js.map +1 -1
  18. package/dist/pos.d.ts +2 -0
  19. package/dist/pos.d.ts.map +1 -1
  20. package/dist/pos.js +41 -6
  21. package/dist/pos.js.map +1 -1
  22. package/dist/reduplication.d.ts +31 -1
  23. package/dist/reduplication.d.ts.map +1 -1
  24. package/dist/reduplication.js +104 -8
  25. package/dist/reduplication.js.map +1 -1
  26. package/dist/sentence-split.js +1 -1
  27. package/dist/sentence-split.js.map +1 -1
  28. package/dist/spaced-counter.d.ts.map +1 -1
  29. package/dist/spaced-counter.js +2 -1
  30. package/dist/spaced-counter.js.map +1 -1
  31. package/dist/structure.d.ts.map +1 -1
  32. package/dist/structure.js +26 -13
  33. package/dist/structure.js.map +1 -1
  34. package/lexicons/calendar-unit.yaml +8 -0
  35. package/lexicons/calendar-year-unit.yaml +7 -0
  36. package/lexicons/date-time-unit.yaml +1 -0
  37. package/lexicons/document-kind.yaml +1 -0
  38. package/lexicons/doubled-word.yaml +1 -0
  39. package/lexicons/emphasis-word.yaml +2 -1
  40. package/lexicons/excessive-hedging.yaml +9 -5
  41. package/lexicons/hedge-frame.yaml +14 -0
  42. package/lexicons/hedge-scope.yaml +7 -0
  43. package/lexicons/iteration-kanji.yaml +18 -0
  44. package/lexicons/name-joiner.yaml +5 -0
  45. package/lexicons/name-title.yaml +20 -0
  46. package/lexicons/self-prefix.yaml +2 -1
  47. package/lexicons/stative-passive-verb.yaml +38 -2
  48. package/package.json +1 -1
  49. package/src/citation.ts +11 -3
  50. package/src/counter-tsu.ts +4 -0
  51. package/src/index.ts +9 -8
  52. package/src/lexicons.ts +9 -8
  53. package/src/passive-reading.ts +80 -10
  54. package/src/pos.ts +60 -6
  55. package/src/reduplication.ts +163 -10
  56. package/src/sentence-split.ts +1 -1
  57. package/src/spaced-counter.ts +2 -1
  58. package/src/structure.ts +26 -14
@@ -1,8 +1,44 @@
1
- # 「れる/られる」を付けると、誰かの動作ではなく物と物との関係を表す動詞。「外国人も含まれる」「対症療法に限られる」には
2
- # 名指すべき動作主がいない(誰かが含める動作は「含める」の受動「含められる」で、こちらは残る)。agentless-passive はこれを受動に数えない。
1
+ # 「れる/られる」を付けると、誰かの動作ではなく状態・決まり・文書の中身を言う動詞。agentless-passive はこれを受動に数えない。
2
+ # - 物と物との関係: 「外国人も含まれる」「対症療法に限られる」(誰かが含める動作は「含める」の受動「含められる」で、こちらは残る)
3
+ # - 決まりの中身: 「次の各号が適用される」「3 つに分類されている」「法令上定められていない」
4
+ # - 文書の中身: 「ガイドラインに記載されている」「図に示されている」
5
+ # 「た」で終わる出来事(「適用された」「定められた」「限定されました」)は誰かのした動作なので、ここにあっても受動に数える。
6
+ # 「ている」の過去(「記載されていた」)は状態のまま。サ変名詞(適用・分類)は「する」の直前にあるときだけ見る。
7
+ # 動作を報告する動詞は入れない: 確認する・検討する・決定する・見直す(「確認されていません」は誰が確認したのかを隠す)。
8
+ # 認めるも入れない。「不正アクセスは認められていません」は誰が調べたのかを隠す。
9
+ # 求める・望むも入れない。「一定の協力が求められます」は、求めているのが書き手の組織であることを隠す。
3
10
  # 形態素解析の原形(基本形)で照らす。
4
11
  id: stative-passive-verb
5
12
  language: ja
6
13
  entries:
7
14
  - pattern: 含む
8
15
  - pattern: 限る
16
+ - pattern: 覆う
17
+ - pattern: 囲む
18
+ - pattern: 適用
19
+ - pattern: 準用
20
+ - pattern: 規定
21
+ - pattern: 定める
22
+ - pattern: 定義
23
+ - pattern: 分類
24
+ - pattern: 区分
25
+ - pattern: 構成
26
+ - pattern: 位置付ける
27
+ - pattern: 位置づける
28
+ - pattern: 限定
29
+ - pattern: 除外
30
+ - pattern: 優先
31
+ - pattern: 妨げる
32
+ - pattern: 記載
33
+ - pattern: 記述
34
+ - pattern: 明記
35
+ - pattern: 列記
36
+ - pattern: 列挙
37
+ - pattern: 網羅
38
+ - pattern: 言及
39
+ - pattern: 例示
40
+ - pattern: 示す
41
+ - pattern: 述べる
42
+ - pattern: 挙げる
43
+ - pattern: 触れる
44
+ - pattern: まとめる
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chaffjs/lang-ja",
3
- "version": "0.14.0",
3
+ "version": "0.16.0",
4
4
  "description": "Japanese language adapter for chaff",
5
5
  "license": "MIT",
6
6
  "author": "isamu",
package/src/citation.ts CHANGED
@@ -9,6 +9,8 @@ export type CitationVocabulary = {
9
9
  readonly kanaTitleKinds: readonly string[];
10
10
  /** 名前と番地のあいだに挟まる括弧書き。 */
11
11
  readonly notes: readonly RegExp[];
12
+ /** 名前と番地を繋ぐ助詞(「前契約の第9条」の「の」)。 */
13
+ readonly joiners: readonly string[];
12
14
  /** この文書自身を指す名前の頭。 */
13
15
  readonly selfPrefixes: readonly string[];
14
16
  };
@@ -16,9 +18,10 @@ export type CitationVocabulary = {
16
18
  const patternsOf = (lexicon: Lexicon | undefined): string[] => (lexicon ?? []).map((entry) => entry.pattern);
17
19
 
18
20
  export const citationVocabulary = (lexicons: Readonly<Record<string, Lexicon>>): CitationVocabulary => ({
19
- kinds: patternsOf(lexicons["document-kind"]).sort((left, right) => right.length - left.length),
21
+ kinds: patternsOf(lexicons["document-kind"]).toSorted((left, right) => right.length - left.length),
20
22
  kanaTitleKinds: patternsOf(lexicons["kana-title-kind"]),
21
23
  notes: patternsOf(lexicons["name-note"]).map((pattern) => new RegExp(`(?:${pattern})$`, "u")),
24
+ joiners: patternsOf(lexicons["name-joiner"]),
22
25
  selfPrefixes: patternsOf(lexicons["self-prefix"]),
23
26
  });
24
27
 
@@ -43,12 +46,17 @@ const beforeNote = (text: string, at: number, notes: readonly RegExp[]): number
43
46
  return note === undefined ? at : at - note.length;
44
47
  };
45
48
 
49
+ const beforeJoiner = (text: string, at: number, joiners: readonly string[]): number => {
50
+ const joiner = joiners.find((candidate) => text.endsWith(candidate, at));
51
+ return joiner === undefined ? at : at - joiner.length;
52
+ };
53
+
46
54
  /**
47
- * reference の直前に書かれた文書名。「民法第709条」なら「民法」。この文書の条を指すなら undefined。
55
+ * reference の直前に書かれた文書名。「民法第709条」「民法の第709条」なら「民法」。この文書の条を指すなら undefined。
48
56
  * 名前が種類の語だけ(「契約第3条」)のときも、どの文書か決まらないので undefined にする。
49
57
  */
50
58
  export const citedDocument = (text: string, reference: number, vocabulary: CitationVocabulary): string | undefined => {
51
- const at = beforeNote(text, reference, vocabulary.notes);
59
+ const at = beforeNote(text, beforeJoiner(text, reference, vocabulary.joiners), vocabulary.notes);
52
60
  const plain = nameBefore(text, at, NAME_CHAR);
53
61
  const name = vocabulary.kanaTitleKinds.includes(plain) ? nameBefore(text, at, TITLE_CHAR) : plain;
54
62
  const kind = vocabulary.kinds.find((candidate) => name.endsWith(candidate));
@@ -12,6 +12,10 @@ export type Morpheme = {
12
12
  readonly pos_detail_3?: string;
13
13
  readonly basic_form: string;
14
14
  readonly reading?: string;
15
+ /** 活用形(連用形・命令e)。活用しない語は持たない。 */
16
+ readonly conjugated_form?: string;
17
+ /** 活用の型(一段、五段・ラ行、サ変・スル など)。活用しない語には無い。 */
18
+ readonly conjugated_type?: string;
15
19
  };
16
20
 
17
21
  const TSU = "つ";
package/src/index.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  import { loadLexicons } from "./lexicons.ts";
2
2
  import { sentenceSpans } from "./sentence-split.ts";
3
3
  import { structure } from "./structure.ts";
4
- import { isReady, predicateOnly, prepare, readsAsCounter, readsAsOneAdverb, tokenize } from "./pos.ts";
4
+ import { isReady, predicateOnly, prepare, readsAsCounter, readsAsOneAdverb, readsAsOneWord, tokenize } from "./pos.ts";
5
5
  import { markSpacedCounters } from "./spaced-counter.ts";
6
6
  import { tokensWithin } from "./tokens-within.ts";
7
- import { distributiveVocabulary, markReduplication } from "./reduplication.ts";
7
+ import { distributiveVocabulary, iterationMarkReading, markReduplication } from "./reduplication.ts";
8
8
  import type { AdapterNeeds, LanguageAdapter, Segmentation, Sentence, Span } from "chaffjs/plugin";
9
9
 
10
10
  // chaff からは型だけを取る。実行時の値依存を作らない。アダプタは単体で動く。
@@ -38,10 +38,9 @@ const merge = (source: string, spans: readonly Span[]): Sentence[] =>
38
38
  // 誤分割を閉じるためのもので、行またぎは要らない。またぐと、引用ブロックの
39
39
  // 英文と訳文のように別の行のものまで 1 文に繋がる。
40
40
  const acrossLines = last !== undefined && source.slice(last.end, span.start).includes("\n");
41
- if (last !== undefined && !acrossLines && isOpen(source.slice(last.start, last.end))) {
42
- return [...acc.slice(0, -1), { start: last.start, end: span.end }];
43
- }
44
- return [...acc, span];
41
+ if (last !== undefined && !acrossLines && isOpen(source.slice(last.start, last.end))) acc[acc.length - 1] = { start: last.start, end: span.end };
42
+ else acc.push(span);
43
+ return acc;
45
44
  }, [])
46
45
  .map((span) => ({ span, text: source.slice(span.start, span.end) }));
47
46
 
@@ -49,7 +48,9 @@ const merge = (source: string, spans: readonly Span[]): Sentence[] =>
49
48
  * token の span は文ではなく、segment に渡した文字列を基準にする。文の span と同じ座標系。
50
49
  * 文ごとに解析して足し戻すのではなく、一度解析して文へ配る。同じ文字列を二度読まない。
51
50
  */
52
- const DISTRIBUTIVE = distributiveVocabulary(loadLexicons());
51
+ const LEXICONS = loadLexicons();
52
+ const DISTRIBUTIVE = distributiveVocabulary(LEXICONS);
53
+ const TAKES_ITERATION_MARK = iterationMarkReading(LEXICONS, readsAsOneWord);
53
54
 
54
55
  const withTokens = (source: string, sentences: readonly Sentence[]): Sentence[] => {
55
56
  const read = tokenize(source);
@@ -58,7 +59,7 @@ const withTokens = (source: string, sentences: readonly Sentence[]): Sentence[]
58
59
  return sentences.map((sentence) => ({
59
60
  ...sentence,
60
61
  // 述語かどうかは文の中でしか決まらないので、文へ配ってから印を落とす。
61
- tokens: markReduplication(predicateOnly(tokensWithin(tokens, sentence.span)), DISTRIBUTIVE, readsAsOneAdverb),
62
+ tokens: markReduplication(predicateOnly(tokensWithin(tokens, sentence.span)), DISTRIBUTIVE, readsAsOneAdverb, TAKES_ITERATION_MARK),
62
63
  }));
63
64
  };
64
65
 
package/src/lexicons.ts CHANGED
@@ -27,11 +27,12 @@ const toEntry = (raw: unknown): LexiconEntry | undefined => {
27
27
  * 新しい言語のサポートは、ここを書くところから始まる。
28
28
  */
29
29
  export const loadLexicons = (dir: string = DIR): Record<string, Lexicon> =>
30
- readdirSync(dir)
31
- .filter((file) => file.endsWith(".yaml"))
32
- .reduce<Record<string, Lexicon>>((acc, file) => {
33
- const raw: unknown = parse(readFileSync(join(dir, file), "utf8"));
34
- if (!isRecord(raw) || typeof raw["id"] !== "string" || !Array.isArray(raw["entries"])) return acc;
35
- const entries = raw["entries"].map(toEntry).filter((entry) => entry !== undefined);
36
- return { ...acc, [raw["id"]]: entries };
37
- }, {});
30
+ Object.fromEntries(
31
+ readdirSync(dir)
32
+ .filter((file) => file.endsWith(".yaml"))
33
+ .flatMap((file): [string, Lexicon][] => {
34
+ const raw: unknown = parse(readFileSync(join(dir, file), "utf8"));
35
+ if (!isRecord(raw) || typeof raw["id"] !== "string" || !Array.isArray(raw["entries"])) return [];
36
+ return [[raw["id"], raw["entries"].map(toEntry).filter((entry) => entry !== undefined)]];
37
+ }),
38
+ );
@@ -8,7 +8,7 @@ import type { Morpheme } from "./counter-tsu.ts";
8
8
  export type PassiveVocabulary = {
9
9
  /** 自発に読む動詞の原形(考える・思う)。 */
10
10
  readonly spontaneous: ReadonlySet<string>;
11
- /** 関係を表す動詞の原形(含む・限る)。 */
11
+ /** 状態・決まり・文書の中身を言う動詞の原形とサ変名詞(含む・定める・適用・記載)。 */
12
12
  readonly stative: ReadonlySet<string>;
13
13
  /** 尊敬の決まり文句(におかれましては)。 */
14
14
  readonly formulas: readonly string[];
@@ -51,10 +51,21 @@ const continuesPredicate = (morpheme: Morpheme): boolean =>
51
51
 
52
52
  const isPast = (morpheme: Morpheme): boolean => morpheme.pos === "助動詞" && morpheme.basic_form === "た";
53
53
 
54
- const pastFollows = (morphemes: readonly Morpheme[], at: number): boolean => {
54
+ /** at の「れる/られる」に続く述語の語(ます・ている・た)。述語の外の最初の語は含まない。 */
55
+ const predicateAfter = (morphemes: readonly Morpheme[], at: number): readonly Morpheme[] => {
55
56
  const rest = morphemes.slice(at + 1, at + 1 + PREDICATE_REACH);
56
57
  const end = rest.findIndex((morpheme) => !continuesPredicate(morpheme));
57
- return rest.slice(0, end === -1 ? rest.length : end).some(isPast);
58
+ return rest.slice(0, end === -1 ? rest.length : end);
59
+ };
60
+
61
+ const pastFollows = (morphemes: readonly Morpheme[], at: number): boolean => predicateAfter(morphemes, at).some(isPast);
62
+
63
+ const isAspect = (morpheme: Morpheme): boolean => morpheme.pos === "動詞" && ASPECT_VERB.has(morpheme.basic_form);
64
+
65
+ /** 「た」で終わる出来事の述語。「適用された」は誰かが適用した動作、「記載されていた」は過去の状態。 */
66
+ const eventPastFollows = (morphemes: readonly Morpheme[], at: number): boolean => {
67
+ const predicate = predicateAfter(morphemes, at);
68
+ return predicate.some(isPast) && !predicate.some(isAspect);
58
69
  };
59
70
 
60
71
  /**
@@ -63,8 +74,43 @@ const pastFollows = (morphemes: readonly Morpheme[], at: number): boolean => {
63
74
  */
64
75
  const verbReadsOtherwise = (morphemes: readonly Morpheme[], at: number, verb: Morpheme, vocabulary: PassiveVocabulary): boolean =>
65
76
  (vocabulary.spontaneous.has(verb.basic_form) && !pastFollows(morphemes, at)) ||
66
- vocabulary.stative.has(verb.basic_form) ||
67
- namesSomething(morphemes, at, verb, vocabulary);
77
+ statesSomething(morphemes, at, vocabulary) ||
78
+ namesSomething(morphemes, at, verb, vocabulary) ||
79
+ withoutRa(verb, morphemes[at]) ||
80
+ cannotBeDone(morphemes, at, verb);
81
+
82
+ /**
83
+ * 状態・決まり・文書の中身を言う受動(「適用される」「定められている」「記載されている」)。サ変名詞は「する」の前で見る。
84
+ * 「た」で終わる出来事(「適用された」「定められた」)は、誰かがした動作の受動として残す。
85
+ */
86
+ const statesSomething = (morphemes: readonly Morpheme[], at: number, vocabulary: PassiveVocabulary): boolean =>
87
+ lemmasBefore(morphemes, at).some((lemma) => vocabulary.stative.has(lemma)) && !eventPastFollows(morphemes, at);
88
+
89
+ const isSuru = (morpheme: Morpheme | undefined): boolean => morpheme?.pos === "動詞" && morpheme.basic_form === "する";
90
+
91
+ /** 「れる/られる」の直前の動詞の原形と、それが「する」ならその前のサ変名詞(「適用される」の適用)。 */
92
+ const lemmasBefore = (morphemes: readonly Morpheme[], at: number): string[] => {
93
+ const verb = morphemes[at - 1];
94
+ const noun = morphemes[at - 2];
95
+ if (verb === undefined) return [];
96
+ return isSuru(verb) && noun?.pos_detail_1 === "サ変接続" ? [verb.basic_form, noun.basic_form] : [verb.basic_form];
97
+ };
98
+
99
+ /**
100
+ * 一段動詞の受動は「られる」で作る(「変えられる」)。一段動詞に直に付いた「れる」は、ら抜きの可能(「見れる」)か、
101
+ * 「とらえれいただければ」のような誤字を解析器が受動と読んだもの。
102
+ */
103
+ const withoutRa = (verb: Morpheme, passive: Morpheme | undefined): boolean => verb.conjugated_type === "一段" && passive?.basic_form === "れる";
104
+
105
+ const NEGATION = new Set(["ない", "ぬ"]);
106
+
107
+ const isNegation = (morpheme: Morpheme | undefined): boolean => morpheme?.pos === "助動詞" && NEGATION.has(morpheme.basic_form);
108
+
109
+ /**
110
+ * 一段動詞の「られる」は受動と可能が同じ形。打ち消しが直に続くと可能に読む(「他人は変えられない」「質問に答えられず」)。
111
+ * 「ている」を挟んだ「変えられていない」は、まだ変えていない状態の受動として残す。
112
+ */
113
+ const cannotBeDone = (morphemes: readonly Morpheme[], at: number, verb: Morpheme): boolean => verb.conjugated_type === "一段" && isNegation(morphemes[at + 1]);
68
114
 
69
115
  /** 「〜と呼ばれる」「〜とも呼ばれています」は名前を言うもので、呼んだ誰かを隠していない。「と」の無い「会議に呼ばれた」は受動。 */
70
116
  const namesSomething = (morphemes: readonly Morpheme[], at: number, verb: Morpheme, vocabulary: PassiveVocabulary): boolean => {
@@ -73,8 +119,6 @@ const namesSomething = (morphemes: readonly Morpheme[], at: number, verb: Morphe
73
119
  return before?.pos === "助詞" && before.surface_form === "と";
74
120
  };
75
121
 
76
- const isSuru = (morpheme: Morpheme | undefined): boolean => morpheme?.pos === "動詞" && morpheme.basic_form === "する";
77
-
78
122
  /**
79
123
  * 自動詞には、動作を受ける側を主語にする受動が無い。「来られ」「取り組まれ」「辞任され」は尊敬か可能。
80
124
  * 本動詞(動詞,自立)だけを見る。補助動詞の「連れてこられた」は「連れてくる」全体の受動。
@@ -82,9 +126,7 @@ const isSuru = (morpheme: Morpheme | undefined): boolean => morpheme?.pos === "
82
126
  const intransitiveVerb = (morphemes: readonly Morpheme[], at: number, vocabulary: PassiveVocabulary): boolean => {
83
127
  const verb = morphemes[at - 1];
84
128
  if (verb?.pos !== "動詞" || verb.pos_detail_1 !== "自立") return false;
85
- if (vocabulary.intransitive.has(verb.basic_form)) return true;
86
- const noun = morphemes[at - 2];
87
- return isSuru(verb) && noun?.pos_detail_1 === "サ変接続" && vocabulary.intransitive.has(noun.basic_form);
129
+ return lemmasBefore(morphemes, at).some((lemma) => vocabulary.intransitive.has(lemma));
88
130
  };
89
131
 
90
132
  /** 「おる」は受動を作らないので、「しておられる」の「れる」は尊敬。 */
@@ -123,3 +165,31 @@ export const readsAsPassive = (morphemes: readonly Morpheme[], at: number, vocab
123
165
  if (honoursTheDoer(morphemes, at, vocabulary)) return false;
124
166
  return !insideFormula(morphemes, at, vocabulary.formulas);
125
167
  };
168
+
169
+ /**
170
+ * 述語を従える接続助詞のうち、仮定の節を作るもの。逆接の「が」「けど」は入れない。「確認されていないが、」は起きたことを言い切っている。
171
+ */
172
+ const CONDITIONAL = new Set(["ば", "と"]);
173
+
174
+ /** 「見直されなければならない」「図られなければなりません」の「ば」は仮定ではなく義務の言い方の一部。 */
175
+ const OBLIGATION = new Set(["なる", "いける"]);
176
+
177
+ const isObligation = (morpheme: Morpheme | undefined): boolean => morpheme?.pos === "動詞" && OBLIGATION.has(morpheme.basic_form);
178
+
179
+ /** 受動が仮定の節の述語か。「立証されれば」「整理されていると」は起きたことではなく、その前提。 */
180
+ const inConditionalClause = (morphemes: readonly Morpheme[], at: number): boolean => {
181
+ const end = at + 1 + predicateAfter(morphemes, at).length;
182
+ const next = morphemes[end];
183
+ return next?.pos_detail_1 === "接続助詞" && CONDITIONAL.has(next.basic_form) && !isObligation(morphemes[end + 1]);
184
+ };
185
+
186
+ /** 受動の連用形に付いて、起きやすさ・起こりうることを言う語(「理解されやすい」「開催されづらい」「解釈され得る」「放置されがち」)。 */
187
+ const TENDENCY = new Set(["やすい", "にくい", "づらい", "得る", "うる", "がち"]);
188
+
189
+ const isTendency = (morpheme: Morpheme | undefined): boolean => morpheme !== undefined && TENDENCY.has(morpheme.basic_form);
190
+
191
+ /**
192
+ * 受動の「れる/られる」が、文の報告する動作の外にあるか。仮定の節と、起きやすさを言う形は、誰かが実際にした動作を言っていない。
193
+ * 隠れた動作主を問うのは、文末や「〜され、」で続く述語の受動のほう。
194
+ */
195
+ export const outsideTheReport = (morphemes: readonly Morpheme[], at: number): boolean => isTendency(morphemes[at + 1]) || inConditionalClause(morphemes, at);
package/src/pos.ts CHANGED
@@ -2,8 +2,9 @@ import { surfaceStarts } from "./surface-starts.ts";
2
2
  import { wellFormed } from "./well-formed.ts";
3
3
  import { analyserPieces } from "./analyser-pieces.ts";
4
4
  import { readCounterTsu, type Morpheme } from "./counter-tsu.ts";
5
- import { isPassiveForm, passiveVocabulary, readsAsPassive } from "./passive-reading.ts";
5
+ import { outsideTheReport, isPassiveForm, passiveVocabulary, readsAsPassive } from "./passive-reading.ts";
6
6
  import { loadLexicons } from "./lexicons.ts";
7
+ import { isEchoAt, type Inflection } from "./reduplication.ts";
7
8
  import { createRequire } from "node:module";
8
9
  import { dirname, join } from "node:path";
9
10
  import type { Token } from "chaffjs/plugin";
@@ -29,7 +30,7 @@ const isTokenizer = (value: unknown): value is Tokenizer => isRecord(value) && i
29
30
  /** kuromoji の形態素。形の違うものは落とす。二段目の細分類(助数詞・地域)は無ければ *。三段目(人名の姓・名)は無ければ持たない。 */
30
31
  const toMorpheme = (value: unknown): Morpheme[] => {
31
32
  if (!isRecord(value)) return [];
32
- const [surface, pos, detail1, detail2, detail3, basic, reading] = [
33
+ const [surface, pos, detail1, detail2, detail3, basic, reading, form, conjugation] = [
33
34
  value["surface_form"],
34
35
  value["pos"],
35
36
  value["pos_detail_1"],
@@ -37,6 +38,8 @@ const toMorpheme = (value: unknown): Morpheme[] => {
37
38
  value["pos_detail_3"],
38
39
  value["basic_form"],
39
40
  value["reading"],
41
+ value["conjugated_form"],
42
+ value["conjugated_type"],
40
43
  ];
41
44
  if (typeof surface !== "string" || typeof pos !== "string" || typeof detail1 !== "string" || typeof basic !== "string") return [];
42
45
  const detail = typeof detail2 === "string" ? detail2 : "*";
@@ -49,6 +52,8 @@ const toMorpheme = (value: unknown): Morpheme[] => {
49
52
  ...(typeof detail3 === "string" ? { pos_detail_3: detail3 } : {}),
50
53
  basic_form: basic,
51
54
  ...(typeof reading === "string" ? { reading } : {}),
55
+ ...(typeof form === "string" && form !== "*" ? { conjugated_form: form } : {}),
56
+ ...(typeof conjugation === "string" && conjugation !== "*" ? { conjugated_type: conjugation } : {}),
52
57
  },
53
58
  ];
54
59
  };
@@ -105,7 +110,8 @@ export const upos = (pos: string, detail: string): string => BY_DETAIL[detail] ?
105
110
 
106
111
  /**
107
112
  * 受動の「れる/られる」。この語は可能・尊敬・自発も表す。形のうえで受動でないと言えるもの
108
- * (自発や関係を表す動詞、名付けの「と呼ばれる」、尊敬の形と決まり文句)は passive-reading.ts が外す。残りは「受動の形」として印を付ける。
113
+ * (自発や状態を言う動詞、名付けの「と呼ばれる」、尊敬の形と決まり文句、ら抜きと可能)と、文が報告する動作の外にあるもの
114
+ * (仮定の節、「〜されやすい」)は passive-reading.ts が外す。残りは「受動の形」として印を付ける。
109
115
  */
110
116
  const PASSIVE_VOCABULARY = passiveVocabulary(loadLexicons());
111
117
 
@@ -140,16 +146,43 @@ export const isReady = (): boolean => state.ready !== undefined;
140
146
  * span は渡した文字列の先頭を 0 とする。位置は kuromoji の word_position ではなく、語の文字を本文と照らして決める(surface-starts.ts)。
141
147
  * 形の違うものが混ざったら、その 1 つを落とす。位置が NaN の token を下流に流さない。
142
148
  */
143
- const toToken = (morpheme: Morpheme, start: number, passive: boolean): Token => ({
149
+ const toToken = (morpheme: Morpheme, start: number, passive: boolean, echo: boolean, light: boolean): Token => ({
144
150
  span: { start, end: start + morpheme.surface_form.length },
145
151
  surface: morpheme.surface_form,
146
152
  // UD の日本語では「れる/られる」は AUX。IPADIC の「動詞,接尾」をそこへ寄せる。
147
153
  pos: isPassiveForm(morpheme) ? "AUX" : upos(morpheme.pos, morpheme.pos_detail_1),
148
154
  ...(morpheme.basic_form === "*" ? {} : { lemma: morpheme.basic_form }),
149
155
  ...(typeof morpheme.reading !== "string" || morpheme.reading === "*" ? {} : { reading: morpheme.reading }),
150
- ...featuresOf(morpheme, passive),
156
+ ...withEcho(withWordStatus(featuresOf(morpheme, passive), isBound(morpheme), light), echo),
151
157
  });
152
158
 
159
+ /**
160
+ * 単独では語にならない形態素(IPADIC の接頭詞・接尾・非自立: ご案内の「ご」、こころさんの「さん」、勤めているの「いる」)は Bound=Yes。
161
+ * 語の中身を数える rule が、付いた先の語だけを数えるため。UD の FEATS の言語別拡張。
162
+ */
163
+ const isBound = (morpheme: Morpheme): boolean => morpheme.pos === "接頭詞" || morpheme.pos_detail_1 === "非自立" || morpheme.pos_detail_1 === "接尾";
164
+
165
+ /** サ変名詞を動詞にするだけの「する」「いたす」(説明します)。意味は名詞が持つ。UD の VerbType=Light。 */
166
+ const LIGHT_VERBS = new Set(["する", "いたす"]);
167
+
168
+ const isLightVerbAt = (sequence: readonly Morpheme[], index: number): boolean => {
169
+ const [previous, morpheme] = [sequence[index - 1], sequence[index]];
170
+ return morpheme?.pos === "動詞" && LIGHT_VERBS.has(morpheme.basic_form) && previous?.pos === "名詞" && previous.pos_detail_1 === "サ変接続";
171
+ };
172
+
173
+ const withWordStatus = (
174
+ found: { features?: Readonly<Record<string, string>> },
175
+ bound: boolean,
176
+ light: boolean,
177
+ ): { features?: Readonly<Record<string, string>> } => {
178
+ if (!bound && !light) return found;
179
+ return { features: { ...found.features, ...(bound ? { Bound: "Yes" } : {}), ...(light ? { VerbType: "Light" } : {}) } };
180
+ };
181
+
182
+ /** 重ね言葉の二つ目(UD の Echo=Rdp)。ほかの印は残す。 */
183
+ const withEcho = (found: { features?: Readonly<Record<string, string>> }, echo: boolean): { features?: Readonly<Record<string, string>> } =>
184
+ echo ? { features: { ...found.features, Echo: "Rdp" } } : found;
185
+
153
186
  /**
154
187
  * 数(名詞,数)。UPOS では名詞に寄せるので、数であることは UD の NumType=Card で渡す。
155
188
  * 決まった言い回し(二人三脚、三日坊主、一人ひとり、十分)は辞書が一語として持つので、数にはならない。
@@ -220,12 +253,30 @@ export const predicateOnly = (tokens: readonly Token[]): Token[] =>
220
253
  return { span: token.span, surface: token.surface, pos: token.pos, ...(token.lemma === undefined ? {} : { lemma: token.lemma }) };
221
254
  });
222
255
 
256
+ const inflectionOf = (morpheme: Morpheme, start: number): Inflection => ({
257
+ surface: morpheme.surface_form,
258
+ pos: morpheme.pos,
259
+ detail: morpheme.pos_detail_1,
260
+ form: morpheme.conjugated_form ?? "*",
261
+ conjugation: morpheme.conjugated_type ?? "*",
262
+ start,
263
+ });
264
+
223
265
  export const tokenize = (text: string): Token[] | undefined => {
224
266
  const tokenizer = state.ready;
225
267
  if (tokenizer === undefined) return undefined;
226
268
  const read = readAll(tokenizer, text);
227
269
  const sequence = read.map(({ morpheme }) => morpheme);
228
- return read.map(({ morpheme, start }, index) => toToken(morpheme, start, readsAsPassive(sequence, index, PASSIVE_VOCABULARY)));
270
+ const inflections = read.map(({ morpheme, start }) => inflectionOf(morpheme, start));
271
+ return read.map(({ morpheme, start }, index) =>
272
+ toToken(
273
+ morpheme,
274
+ start,
275
+ readsAsPassive(sequence, index, PASSIVE_VOCABULARY) && !outsideTheReport(sequence, index),
276
+ isEchoAt(inflections, index),
277
+ isLightVerbAt(sequence, index),
278
+ ),
279
+ );
229
280
  };
230
281
 
231
282
  /** 句読点の無い並びをこれより長く渡さない。解析器は並びの長さの二乗で遅くなり、20 万字の 1 行では何分も返らない。 */
@@ -290,6 +341,9 @@ export const readsAsOneAdverb = (text: string): boolean => {
290
341
  return read?.length === 1 && read[0]?.pos === "ADV";
291
342
  };
292
343
 
344
+ /** 一語と読むか(家々・時々)。品詞は問わない。 */
345
+ export const readsAsOneWord = (text: string): boolean => tokenize(text)?.length === 1;
346
+
293
347
  /**
294
348
  * 数のすぐ後ろに詰めて書いたとき、word が数につく語として読まれるか(spaced-counter.ts が使う)。
295
349
  * word がそのまま一語の助数詞になるか、桁の語で始まるとき。「件名」は詰めると 件 と 名 に割れるので、助数詞とは読まない。
@@ -34,19 +34,172 @@ const isDistributive = (tokens: readonly Token[], index: number, vocabulary: Dis
34
34
  /** 文字列を解析器が一語の副詞と読むか。解析器を持つ index.ts が渡す。 */
35
35
  export type ReadsAsAdverb = (text: string) => boolean;
36
36
 
37
+ /** 一字の漢字に 々 を付けて畳語になるか(家 → 家々)。解析器の辞書と語彙表を持つ index.ts が渡す。 */
38
+ export type TakesIterationMark = (kanji: string) => boolean;
39
+
40
+ /**
41
+ * 解析器の辞書が 々 付きの一語として持つ漢字(家々・国々)と、辞書に無い畳語の漢字(朝々・神々)の語彙表。
42
+ * readsAsOneWord は解析器を持つ index.ts が渡す。
43
+ */
44
+ export const iterationMarkReading = (lexicons: Readonly<Record<string, Lexicon>>, readsAsOneWord: (text: string) => boolean): TakesIterationMark => {
45
+ const listed = patternsOf(lexicons["iteration-kanji"]);
46
+ return (kanji) => listed.has(kanji) || readsAsOneWord(`${kanji}々`);
47
+ };
48
+
37
49
  const CONTENT_WORD = new Set(["NOUN", "VERB", "ADJ"]);
38
50
 
51
+ /** 助動詞が付く語。 */
52
+ const PREDICATE = new Set(["VERB", "ADJ", "AUX"]);
53
+
54
+ /**
55
+ * 助動詞の重なりは、前に付く述語が無ければ解析器が仮名の擬音を切った片割れ(たんたらたら → たん・たら・たら)。
56
+ * 述語に付いた重なり(行ったたので・着いたらたら)は書き損じ。
57
+ */
58
+ const isStrandedAuxiliary = (before: Token | undefined, first: Token): boolean => first.pos === "AUX" && (before === undefined || !PREDICATE.has(before.pos));
59
+
39
60
  /**
40
61
  * 重ね言葉の副詞(がんがん)は、前の語に引かれると同じ名詞二つに切られる(労働者ががんがん → が・がん・がん)。
41
- * 二語を続けて読み直して一語の副詞なら、重ね言葉。機能語の重なりは読み直さない。書き損じの「行ったたので」の「たた」も一語の副詞に読める。
62
+ * 二語を続けて読み直して一語の副詞なら、重ね言葉。機能語の重なりは、付く先の無い助動詞のほかは読み直さない。
63
+ * 書き損じの「行ったたので」の「たた」も一語の副詞に読める。
42
64
  */
43
- const isSplitAdverb = (first: Token | undefined, second: Token, readsAsAdverb: ReadsAsAdverb): boolean =>
44
- first !== undefined &&
45
- first.surface === second.surface &&
46
- first.pos === second.pos &&
47
- CONTENT_WORD.has(second.pos) &&
48
- first.span.end === second.span.start &&
49
- readsAsAdverb(`${first.surface}${second.surface}`);
65
+ const isSplitAdverb = (tokens: readonly Token[], index: number, readsAsAdverb: ReadsAsAdverb): boolean => {
66
+ const [before, first, second] = [tokens[index - 2], tokens[index - 1], tokens[index]];
67
+ return (
68
+ first !== undefined &&
69
+ second !== undefined &&
70
+ first.surface === second.surface &&
71
+ first.pos === second.pos &&
72
+ (CONTENT_WORD.has(second.pos) || isStrandedAuxiliary(before, first)) &&
73
+ first.span.end === second.span.start &&
74
+ readsAsAdverb(`${first.surface}${second.surface}`)
75
+ );
76
+ };
77
+
78
+ const ONE_KANJI = /^\p{Script=Han}$/u;
79
+
80
+ const isKanjiNoun = (token: Token | undefined): token is Token =>
81
+ token !== undefined && token.pos === "NOUN" && ONE_KANJI.test(token.surface) && token.features?.["NumType"] !== "Card";
82
+
83
+ /**
84
+ * 一字の漢字の名詞を 々 を使わずに重ねた畳語(家家・朝朝)。々 を付けて畳語になる漢字だけ。
85
+ * 略称を重ねた「法法」は 法々 と書けないので、書き損じのまま。
86
+ */
87
+ const isIteratedKanji = (tokens: readonly Token[], index: number, takesIterationMark: TakesIterationMark): boolean => {
88
+ const [first, second] = [tokens[index - 1], tokens[index]];
89
+ return (
90
+ isKanjiNoun(first) && isKanjiNoun(second) && first.surface === second.surface && first.span.end === second.span.start && takesIterationMark(second.surface)
91
+ );
92
+ };
93
+
94
+ export const markReduplication = (
95
+ tokens: readonly Token[],
96
+ vocabulary: Distributive,
97
+ readsAsAdverb: ReadsAsAdverb,
98
+ takesIterationMark: TakesIterationMark,
99
+ ): Token[] =>
100
+ tokens.map((token, index) =>
101
+ isDistributive(tokens, index, vocabulary) || isSplitAdverb(tokens, index, readsAsAdverb) || isIteratedKanji(tokens, index, takesIterationMark)
102
+ ? echoed(token)
103
+ : token,
104
+ );
105
+
106
+ /** 解析器が読んだ一語。pos は IPADIC の品詞、detail はその細分類、form は活用形、conjugation は活用型(活用しない語はどちらも *)。 */
107
+ export type Inflection = {
108
+ readonly surface: string;
109
+ readonly pos: string;
110
+ readonly detail: string;
111
+ readonly form: string;
112
+ readonly conjugation: string;
113
+ readonly start: number;
114
+ };
115
+
116
+ /** 文を終えずに後ろへ続く形。連用形(連用テ接続・連用タ接続を含む)と命令形。 */
117
+ const CONTINUING_FORM = /^(?:連用|命令)/u;
118
+
119
+ /** 一文字の語(し・い)は重ねて強める形にならない。「確認ししました」は書き損じ。 */
120
+ const MIN_ECHO_LENGTH = 2;
121
+
122
+ /** IPADIC で細分類が「自立」なのは動詞と形容詞だけで、活用形を持つ。 */
123
+ const continuesAsWord = (word: Inflection | undefined): word is Inflection =>
124
+ word !== undefined && word.detail === "自立" && word.surface.length >= MIN_ECHO_LENGTH && CONTINUING_FORM.test(word.form);
125
+
126
+ const GODAN = /^五段/u;
127
+
128
+ /**
129
+ * 語尾として続く語。助動詞が続く重なり(できできます)は語幹の書き損じ。接続助詞も同じだが、五段動詞の連用形(売り・行き)は
130
+ * 語幹に音を足した形なので、「て」を続けた重ね言葉(売り売りて・行き行きて)になる。一段動詞の連用形(でき)は語幹そのもの。
131
+ */
132
+ const isEnding = (next: Inflection | undefined, echo: Inflection): boolean =>
133
+ next !== undefined && (next.pos === "助動詞" || (next.detail === "接続助詞" && !GODAN.test(echo.conjugation)));
134
+
135
+ const touches = (first: Inflection, second: Inflection): boolean => first.start + first.surface.length === second.start;
136
+
137
+ /**
138
+ * 自立の動詞・形容詞を、連用形か命令形のまま重ねた形(泣き泣き・売り売り・長く長く・待て待て)は重ね言葉。二つ目に Echo=Rdp。
139
+ * 解析器は一つ目を別の活用に読むことがある(待て待て の一つ目は「待てる」の連用形)ので、形は二つとも続く形であればよい。
140
+ * 終止形の重なり(行く行く)、非自立の語(くださいください)、語尾が続く重なり(できできます)は書き損じのまま。
141
+ */
142
+ export const isInflectedEcho = (words: readonly Inflection[], index: number): boolean => {
143
+ const [first, second] = [words[index - 1], words[index]];
144
+ return continuesAsWord(first) && continuesAsWord(second) && first.surface === second.surface && touches(first, second) && !isEnding(words[index + 1], second);
145
+ };
146
+
147
+ /** 片仮名の語はたいてい外来語(ユーザー・データ)で、重ねれば書き損じ。 */
148
+ const HIRAGANA = /^[\p{Script=Hiragana}ー]+$/u;
149
+
150
+ /** 解析器が擬音・擬態語の切れ端に当てる品詞。助詞・助動詞の重なり(のの・ですです)は書き損じ。 */
151
+ const FREE_WORD = new Set(["名詞", "動詞", "形容詞"]);
152
+
153
+ /** 接尾語が付く語。 */
154
+ const HOST = new Set(["名詞", "動詞", "形容詞", "助動詞"]);
155
+
156
+ /** 拍に数えない小さい仮名(ちょ・しゃ)。 */
157
+ const SMALL_KANA = /[ぁぃぅぇぉゃゅょゎ]/gu;
158
+
159
+ /** 擬音・擬態語の根は二拍(すう・きし・ちょん)。動詞に読まれた重なりは二拍までが擬音で、長い動詞の重なり(できるできる)は書き損じ。 */
160
+ const MIMETIC_ROOT_MORAE = 2;
161
+
162
+ const moraeOf = (text: string): number => text.length - (text.match(SMALL_KANA)?.length ?? 0);
163
+
164
+ const fitsMimeticRoot = (word: Inflection): boolean => word.pos !== "動詞" || moraeOf(word.surface) <= MIMETIC_ROOT_MORAE;
165
+
166
+ const isKanaWord = (word: Inflection | undefined): word is Inflection =>
167
+ word !== undefined &&
168
+ word.surface.length >= MIN_ECHO_LENGTH &&
169
+ HIRAGANA.test(word.surface) &&
170
+ FREE_WORD.has(word.pos) &&
171
+ word.detail !== "非自立" &&
172
+ fitsMimeticRoot(word);
173
+
174
+ /** 前の語に付いた接尾語(田中さん・見られ)。読点の後ろの「しだい」は付く先が無く、解析器が擬態語を切った片割れ。 */
175
+ const isAttachedSuffix = (before: Inflection | undefined, word: Inflection): boolean =>
176
+ word.detail === "接尾" && before !== undefined && HOST.has(before.pos) && touches(before, word);
177
+
178
+ /**
179
+ * 擬音・擬態語は副詞として立つ。後ろに「と」「に」が続くか、行が終わる(歌の行末。解析器は改行を「記号,空白」と読む)。
180
+ * 句読点の前は、名詞の書き損じ(まとめまとめ、)と見分けられない。
181
+ */
182
+ const ADVERB_MARK = new Set(["と", "に"]);
183
+
184
+ const endsAsAdverb = (second: Inflection, next: Inflection | undefined): boolean =>
185
+ next === undefined || !touches(second, next) || next.detail === "空白" || (next.pos === "助詞" && ADVERB_MARK.has(next.surface));
186
+
187
+ /**
188
+ * 平仮名だけの語を丸ごと重ねた形(きしきし・ちょんちょん・すうすう・しだいしだい・あはれあはれ)は擬音・擬態語か感動詞。
189
+ * 解析器は辞書に無い擬音を、表層の合う名詞や動詞に切って読む(すう = 吸う)ので、品詞ではなく平仮名であることと、副詞の位置に立つことで見分ける。
190
+ * 前の語に付いた接尾語(田中さんさん)と、副詞の位置に立たない重なり(まとめまとめを・できるできるように)は書き損じのまま。
191
+ */
192
+ export const isKanaEcho = (words: readonly Inflection[], index: number): boolean => {
193
+ const [before, first, second] = [words[index - 2], words[index - 1], words[index]];
194
+ return (
195
+ isKanaWord(first) &&
196
+ isKanaWord(second) &&
197
+ first.surface === second.surface &&
198
+ touches(first, second) &&
199
+ !isAttachedSuffix(before, first) &&
200
+ endsAsAdverb(second, words[index + 1])
201
+ );
202
+ };
50
203
 
51
- export const markReduplication = (tokens: readonly Token[], vocabulary: Distributive, readsAsAdverb: ReadsAsAdverb): Token[] =>
52
- tokens.map((token, index) => (isDistributive(tokens, index, vocabulary) || isSplitAdverb(tokens[index - 1], token, readsAsAdverb) ? echoed(token) : token));
204
+ /** 活用した語の重なりか、仮名の語の重なり。pos.ts が二つ目に Echo=Rdp を付ける。 */
205
+ export const isEchoAt = (words: readonly Inflection[], index: number): boolean => isInflectedEcho(words, index) || isKanaEcho(words, index);
@@ -77,7 +77,7 @@ const indexesOf = (text: string, pattern: RegExp): number[] => [...text.matchAll
77
77
  const stopEnds = (text: string): number[] => {
78
78
  const japanese = [...text.matchAll(JAPANESE_STOPS)].filter((match) => isCJK(text[match.index - 1]));
79
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);
80
+ return [...japanese, ...english].map((match) => match.index + match[0].length).toSorted((a, b) => a - b);
81
81
  };
82
82
 
83
83
  const skipSpaces = (text: string, from: number): number => {