tokenize_nl.go raw

   1  package iskra
   2  
   3  import (
   4  	"strings"
   5  )
   6  
   7  // Punctuation classes from the language tokenizers.
   8  const (
   9  	punctNone uint8 = 0
  10  	punctHard uint8 = 1 // sentence terminator: . ! ? 。 ! ?
  11  	punctSoft uint8 = 2 // clause boundary: , ; 、 : — …
  12  	punctSkip uint8 = 3 // quotes, brackets, decorative
  13  )
  14  
  15  // ClauseSplitToken is the synthetic boundary both tokenizers emit for soft and
  16  // hard punctuation: the JA comma 、.
  17  const ClauseSplitToken = "、"
  18  
  19  // ClassifyPunct classifies the punctuation run starting at b[i].
  20  func ClassifyPunct(b []byte, i int) (int, uint8) {
  21  	if i >= len(b) {
  22  		return 0, punctNone
  23  	}
  24  	c := b[i]
  25  	if c < 0x80 {
  26  		switch c {
  27  		case '.', '!', '?':
  28  			return 1, punctHard
  29  		case ',', ';', ':':
  30  			return 1, punctSoft
  31  		case '"', '(', ')', '[', ']', '{', '}':
  32  			return 1, punctSkip
  33  		}
  34  		return 0, punctNone
  35  	}
  36  	if i+2 >= len(b) {
  37  		return 0, punctNone
  38  	}
  39  	b1, b2 := b[i+1], b[i+2]
  40  	if c == 0xe3 && b1 == 0x80 {
  41  		switch b2 {
  42  		case 0x80, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91:
  43  			return 3, punctSkip
  44  		case 0x81:
  45  			return 3, punctSoft
  46  		case 0x82:
  47  			return 3, punctHard
  48  		}
  49  	}
  50  	if c == 0xef && b1 == 0xbc {
  51  		switch b2 {
  52  		case 0x81, 0x9f, 0x8e:
  53  			return 3, punctHard
  54  		case 0x8c, 0x9b, 0x9a:
  55  			return 3, punctSoft
  56  		case 0x88, 0x89:
  57  			return 3, punctSkip
  58  		}
  59  	}
  60  	if c == 0xe2 && b1 == 0x80 {
  61  		switch b2 {
  62  		case 0x94, 0x95, 0xa6:
  63  			return 3, punctSoft
  64  		case 0x9c, 0x9d, 0x98, 0x99:
  65  			return 3, punctSkip
  66  		}
  67  	}
  68  	if c == 0xe2 && b1 == 0x99 {
  69  		switch b2 {
  70  		case 0xaa, 0xab, 0xac, 0xad:
  71  			return 3, punctSoft
  72  		}
  73  	}
  74  	return 0, punctNone
  75  }
  76  
  77  // ClassifyPunctRun returns the byte length and the strongest class of the run
  78  // of punctuation starting at b[i].
  79  func ClassifyPunctRun(b []byte, i int) (int, uint8) {
  80  	total := 0
  81  	kind := punctNone
  82  	for {
  83  		n, k := ClassifyPunct(b, i+total)
  84  		if n == 0 {
  85  			break
  86  		}
  87  		total += n
  88  		if k > kind {
  89  			kind = k
  90  		}
  91  	}
  92  	return total, kind
  93  }
  94  
  95  // TokenizeEN splits an English sentence, splitting n't contractions and
  96  // emitting ClauseSplitToken for soft and hard punctuation. A skip-class run
  97  // alone emits nothing: the moxie tokenizer emits the split token for the whole
  98  // run whenever any member of it is soft or hard, so "book." splits the clause.
  99  func TokenizeEN(s string) []string {
 100  	b := []byte(s)
 101  	var tokens []string
 102  	for i := 0; i < len(b); {
 103  		if b[i] == ' ' || b[i] == '\t' || b[i] == '\n' || b[i] == '\r' {
 104  			i++
 105  			continue
 106  		}
 107  		if b[i] == '[' && i+9 <= len(b) && string(b[i:i+9]) == UntranslatedMarker {
 108  			tokens = append(tokens, UntranslatedMarker)
 109  			i += 9
 110  			continue
 111  		}
 112  		if n, kind := ClassifyPunctRun(b, i); n > 0 {
 113  			if kind == punctSoft || kind == punctHard {
 114  				tokens = append(tokens, ClauseSplitToken)
 115  			}
 116  			i += n
 117  			continue
 118  		}
 119  		if b[i] == '\'' {
 120  			tokens = append(tokens, "'")
 121  			i++
 122  			continue
 123  		}
 124  		start := i
 125  		for i < len(b) && b[i] != ' ' && b[i] != '\t' && b[i] != '\n' && b[i] != '\r' {
 126  			if b[i] == '\'' {
 127  				if i+1 < len(b) && isLetter(b[i+1]) {
 128  					i++
 129  					continue
 130  				}
 131  				break
 132  			}
 133  			if n, _ := ClassifyPunct(b, i); n > 0 {
 134  				break
 135  			}
 136  			i++
 137  		}
 138  		if i > start {
 139  			tok := string(b[start:i])
 140  			tl := len(tok)
 141  			if tl > 3 && (tok[tl-3] == 'n' || tok[tl-3] == 'N') && tok[tl-2] == '\'' && (tok[tl-1] == 't' || tok[tl-1] == 'T') {
 142  				base := tok[:tl-3]
 143  				switch strings.ToLower(base) {
 144  				case "wo":
 145  					base = "will"
 146  				case "ca":
 147  					base = "can"
 148  				case "sha":
 149  					base = "shall"
 150  				}
 151  				tokens = append(tokens, base, "n't")
 152  			} else {
 153  				tokens = append(tokens, tok)
 154  			}
 155  		}
 156  	}
 157  	return tokens
 158  }
 159  
 160  // jaParticles lists every JA particle the tokenizer splits on, longest first at
 161  // each length so から wins over か and まで over ま.
 162  func jaParticles() []string {
 163  	return []string{
 164  		"から", "まで", "より", "けど",
 165  		"は", "が", "を", "に", "で", "へ", "も", "の", "と", "か", "よ", "ね",
 166  		"★", "☆", "〇", "◯",
 167  	}
 168  }
 169  
 170  // TokenizeJA splits a Japanese sentence: particles come out as their own
 171  // tokens, the content between them accumulates, temporal nouns and kanji
 172  // adjective prefixes split off the front of a content run, and soft and hard
 173  // punctuation both emit ClauseSplitToken.
 174  func TokenizeJA(s string) []string {
 175  	b := []byte(s)
 176  	var tokens []string
 177  	for i := 0; i < len(b); {
 178  		if b[i] == ' ' || b[i] == '\t' || b[i] == '\n' || b[i] == '\r' {
 179  			i++
 180  			continue
 181  		}
 182  		if b[i] == '[' && i+9 <= len(b) && string(b[i:i+9]) == UntranslatedMarker {
 183  			tokens = append(tokens, UntranslatedMarker)
 184  			i += 9
 185  			continue
 186  		}
 187  		if n, kind := ClassifyPunctRun(b, i); n > 0 {
 188  			if kind == punctSoft || kind == punctHard {
 189  				tokens = append(tokens, ClauseSplitToken)
 190  			}
 191  			i += n
 192  			continue
 193  		}
 194  		if isPartOfMoshiPrefix(b, i) {
 195  			tokens = append(tokens, "もし")
 196  			i += 6
 197  			continue
 198  		}
 199  		matched := false
 200  		for _, p := range jaParticles() {
 201  			if strings.HasPrefix(string(b[i:]), p) && jaParticleFits(b, i, p) {
 202  				tokens = append(tokens, p)
 203  				i += len(p)
 204  				matched = true
 205  				break
 206  			}
 207  		}
 208  		if matched {
 209  			continue
 210  		}
 211  		if tlen := tryMatchJATemporalPrefix(b, i); tlen > 0 {
 212  			tokens = append(tokens, string(b[i:i+tlen]))
 213  			i += tlen
 214  			continue
 215  		}
 216  		if isJAKanjiAdjPrefix(b, i) {
 217  			tokens = append(tokens, string(b[i:i+3]))
 218  			i += 3
 219  			continue
 220  		}
 221  		start := i
 222  		for i < len(b) && !isJASkippable(b, i) {
 223  			if i+3 <= len(b) && b[i] == 0xe3 && b[i+1] == 0x80 && b[i+2] == 0x81 {
 224  				break
 225  			}
 226  			hit := false
 227  			for _, p := range jaParticles() {
 228  				if strings.HasPrefix(string(b[i:]), p) && jaParticleFits(b, i, p) {
 229  					hit = true
 230  					break
 231  				}
 232  			}
 233  			if hit {
 234  				break
 235  			}
 236  			if i+6 <= len(b) {
 237  				curHira := b[i] == 0xe3 && (b[i+1] == 0x81 || b[i+1] == 0x82)
 238  				nextKanji := b[i+3] >= 0xe4 && b[i+3] <= 0xe9
 239  				if curHira && nextKanji {
 240  					i += 3
 241  					break
 242  				}
 243  			}
 244  			i += utf8Len(b, i)
 245  		}
 246  		if i > start {
 247  			tokens = append(tokens, string(b[start:i]))
 248  		} else {
 249  			i += utf8Len(b, i)
 250  		}
 251  	}
 252  	return tokens
 253  }
 254  
 255  // jaParticleFits applies the compound suppressors: です/でした for で, volitional
 256  // stems for よ/こ/そ/と/の/ぼ/も/ろ/お, the conditional prefix for もし, and the
 257  // conjugation compounds for から/か/で/も.
 258  func jaParticleFits(b []byte, i int, p string) bool {
 259  	switch p {
 260  	case "で":
 261  		if isPartOfDesuCompound(b, i) {
 262  			return false
 263  		}
 264  	}
 265  	if isPartOfVolitionalCompound(b, i) {
 266  		return false
 267  	}
 268  	if isPartOfMoshiPrefix(b, i) {
 269  		return false
 270  	}
 271  	return !isPartOfConjugation(b, i, -1)
 272  }
 273  
 274  func isLetter(c byte) bool { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') }
 275  
 276  func utf8Len(b []byte, i int) int {
 277  	switch {
 278  	case b[i] < 0x80:
 279  		return 1
 280  	case b[i] < 0xE0:
 281  		return 2
 282  	case b[i] < 0xF0:
 283  		return 3
 284  	default:
 285  		return 4
 286  	}
 287  }
 288  
 289  // isPartOfVolitionalCompound reports a volitional stem followed by う.
 290  func isPartOfVolitionalCompound(b []byte, i int) bool {
 291  	if i+6 > len(b) || b[i+3] != 0xe3 || b[i+4] != 0x81 || b[i+5] != 0x86 || b[i] != 0xe3 {
 292  		return false
 293  	}
 294  	if b[i+1] == 0x82 && (b[i+2] == 0x88 || b[i+2] == 0x82 || b[i+2] == 0x8d) {
 295  		return true
 296  	}
 297  	if b[i+1] == 0x81 {
 298  		switch b[i+2] {
 299  		case 0x93, 0x94, 0x9d, 0xa8, 0xae, 0xbc, 0x8a:
 300  			return true
 301  		}
 302  	}
 303  	return false
 304  }
 305  
 306  // isPartOfMoshiPrefix reports もし at the start of the sentence.
 307  func isPartOfMoshiPrefix(b []byte, i int) bool {
 308  	if i != 0 || i+6 > len(b) {
 309  		return false
 310  	}
 311  	return b[0] == 0xe3 && b[1] == 0x82 && b[2] == 0x82 && b[3] == 0xe3 && b[4] == 0x81 && b[5] == 0x97
 312  }
 313  
 314  // isPartOfDesuCompound reports です or でした, where で is not a particle.
 315  func isPartOfDesuCompound(b []byte, i int) bool {
 316  	if i+3 > len(b) || !(b[i] == 0xe3 && b[i+1] == 0x81 && b[i+2] == 0xa7) {
 317  		return false
 318  	}
 319  	if i+6 <= len(b) && b[i+3] == 0xe3 && b[i+4] == 0x81 && b[i+5] == 0x99 {
 320  		return true
 321  	}
 322  	return i+9 <= len(b) && b[i+3] == 0xe3 && b[i+4] == 0x81 && b[i+5] == 0x97 &&
 323  		b[i+6] == 0xe3 && b[i+7] == 0x81 && b[i+8] == 0x9f
 324  }
 325  
 326  // temporalNouns split off the front of a content run.
 327  var temporalNouns = []string{
 328  	"昨日", "今日", "明日", "昨夜", "今朝", "今晩", "今夜",
 329  	"来週", "先週", "来月", "先月", "来年", "去年", "毎日", "毎週", "毎月", "毎年",
 330  }
 331  
 332  // tryMatchJATemporalPrefix returns the byte length of a temporal noun at i when
 333  // it is followed by more content.
 334  func tryMatchJATemporalPrefix(b []byte, i int) int {
 335  	for _, t := range temporalNouns {
 336  		if !strings.HasPrefix(string(b[i:]), t) {
 337  			continue
 338  		}
 339  		next := i + len(t)
 340  		if next >= len(b) {
 341  			return 0
 342  		}
 343  		if b[next] >= 0xe0 && b[next] < 0xf0 {
 344  			return len(t)
 345  		}
 346  		return 0
 347  	}
 348  	return 0
 349  }
 350  
 351  // kanjiAdjPrefixes are colour and size kanji that split off before a noun.
 352  var kanjiAdjPrefixes = []string{"赤", "白", "黒", "大", "小", "新", "古", "長", "高", "低"}
 353  
 354  // isJAKanjiAdjPrefix reports one of the adjective kanji followed by a kanji.
 355  func isJAKanjiAdjPrefix(b []byte, i int) bool {
 356  	if i+6 > len(b) || b[i+3] < 0xe4 || b[i+3] > 0xe9 {
 357  		return false
 358  	}
 359  	for _, k := range kanjiAdjPrefixes {
 360  		if strings.HasPrefix(string(b[i:]), k) {
 361  			return true
 362  		}
 363  	}
 364  	return false
 365  }
 366  
 367  // isJASkippable reports bytes that end a content run: whitespace and
 368  // punctuation other than the clause comma.
 369  func isJASkippable(b []byte, i int) bool {
 370  	if i >= len(b) {
 371  		return false
 372  	}
 373  	switch b[i] {
 374  	case ' ', '\t', '\n', '\r':
 375  		return true
 376  	case '.', ',', '!', '?', ';', ':', '"', '\'', '(', ')', '[', ']', '{', '}':
 377  		return true
 378  	}
 379  	if i+2 < len(b) && b[i] == 0xe3 && b[i+1] == 0x80 {
 380  		return b[i+2] != 0x81
 381  	}
 382  	return false
 383  }
 384  
 385  // isPartOfConjugation reports particles that are really verb morphology.
 386  func isPartOfConjugation(b []byte, i, contentStart int) bool {
 387  	if i+3 > len(b) || b[i] != 0xe3 {
 388  		return false
 389  	}
 390  	p1, p2 := b[i+1], b[i+2]
 391  	if p1 == 0x81 && p2 == 0x8b {
 392  		if i+6 <= len(b) && b[i+3] == 0xe3 && b[i+4] == 0x82 && b[i+5] == 0x89 {
 393  			if i+9 <= len(b) && b[i+6] == 0xe3 && b[i+7] == 0x81 && b[i+8] == 0xaa {
 394  				return true
 395  			}
 396  		}
 397  		if i >= 3 && b[i-3] == 0xe3 && b[i-2] == 0x81 && b[i-1] == 0xaa && i+6 <= len(b) {
 398  			if b[i+3] == 0xe3 && b[i+4] == 0x81 && b[i+5] == 0xa3 {
 399  				return true
 400  			}
 401  			if b[i+3] == 0xe3 && b[i+4] == 0x82 && b[i+5] == 0x8d {
 402  				return true
 403  			}
 404  		}
 405  		return i+6 <= len(b) && b[i+3] == 0xe3 && b[i+4] == 0x81 && b[i+5] == 0xaa
 406  	}
 407  	if p1 == 0x81 && p2 == 0xa7 {
 408  		if i+6 <= len(b) && b[i+3] == 0xe3 && b[i+4] == 0x81 && b[i+5] == 0x8d {
 409  			return true
 410  		}
 411  		if i >= 6 && b[i-6] == 0xe3 && b[i-5] == 0x81 && b[i-4] == 0xaa &&
 412  			b[i-3] == 0xe3 && b[i-2] == 0x81 && b[i-1] == 0x84 {
 413  			return true
 414  		}
 415  		return i >= 3 && (contentStart < 0 || contentStart <= i-3) &&
 416  			b[i-3] == 0xe3 && b[i-2] == 0x82 && b[i-1] == 0x93
 417  	}
 418  	if p1 == 0x82 && p2 == 0x82 {
 419  		if i+6 <= len(b) && b[i+3] == 0xe3 && b[i+4] == 0x82 && b[i+5] == 0x89 {
 420  			return true
 421  		}
 422  		return i >= 3 && b[i-3] == 0xe3 && b[i-2] == 0x81 && b[i-1] == 0xa6
 423  	}
 424  	return false
 425  }
 426