File size: 4,493 Bytes
e4b9a7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# -*- coding: utf-8 -*-
# SPDX-FileCopyrightText: 2016-2025 PyThaiNLP Project
# SPDX-FileCopyrightText: Copyright 2019 Ponrawee Prasertsom
# SPDX-License-Identifier: Apache-2.0
"""
🪿 Han-solo: Thai syllable segmenter

GitHub: https://github.com/PyThaiNLP/Han-solo
"""
from typing import List

from pythainlp.corpus import path_pythainlp_corpus

try:
    import pycrfsuite
except ImportError:
    raise ImportError(
        "ImportError; Install pycrfsuite by pip install python-crfsuite"
    )

tagger = pycrfsuite.Tagger()
tagger.open(path_pythainlp_corpus("han_solo.crfsuite"))


class Featurizer:
    #  This class from ssg at https://github.com/ponrawee/ssg.

    def __init__(self, N=2, sequence_size=1, delimiter=None):
        self.N = N
        self.delimiter = delimiter
        self.radius = N + sequence_size

    def pad(self, sentence, padder="#"):
        return padder * (self.radius) + sentence + padder * (self.radius)

    def featurize(
        self, sentence, padding=True, indiv_char=True, return_type="list"
    ):
        if padding:
            sentence = self.pad(sentence)
        all_features = []
        all_labels = []
        skip_next = False
        for current_position in range(
            self.radius, len(sentence) - self.radius + 1
        ):
            if skip_next:
                skip_next = False
                continue
            features = {}
            if return_type == "list":
                features = []
            cut = 0
            char = sentence[current_position]
            if char == self.delimiter:
                cut = 1
                skip_next = True
            counter = 0
            chars_left = ""
            chars_right = ""
            chars = ""
            abs_index_left = current_position  # left start at -1
            abs_index_right = current_position - 1  # right start at 0
            while counter < self.radius:
                abs_index_left -= (
                    1  # สมมุติตำแหน่งที่ 0 จะได้ -1, -2, -3, -4, -5 (radius = 5)
                )
                char_left = sentence[abs_index_left]
                while char_left == self.delimiter:
                    abs_index_left -= 1
                    char_left = sentence[abs_index_left]
                relative_index_left = -counter - 1
                # เก็บตัวหนังสือ
                chars_left = char_left + chars_left
                # ใส่ลง feature
                if indiv_char:
                    left_key = "|".join([str(relative_index_left), char_left])
                    if return_type == "dict":
                        features[left_key] = 1
                    else:
                        features.append(left_key)

                abs_index_right += (
                    1  # สมมุติคือตำแหน่งที่ 0 จะได้ 0, 1, 2, 3, 4 (radius = 5)
                )
                char_right = sentence[abs_index_right]
                while char_right == self.delimiter:
                    abs_index_right += 1
                    char_right = sentence[abs_index_right]
                relative_index_right = counter
                chars_right += char_right
                if indiv_char:
                    right_key = "|".join(
                        [str(relative_index_right), char_right]
                    )
                    if return_type == "dict":
                        features[right_key] = 1
                    else:
                        features.append(right_key)

                counter += 1

            chars = chars_left + chars_right
            for i in range(0, len(chars) - self.N + 1):
                ngram = chars[i : i + self.N]
                ngram_key = "|".join([str(i - self.radius), ngram])
                if return_type == "dict":
                    features[ngram_key] = 1
                else:
                    features.append(ngram_key)
            all_features.append(features)
            if return_type == "list":
                cut = str(cut)
            all_labels.append(cut)

        return {"X": all_features, "Y": all_labels}


_to_feature = Featurizer()


def segment(text: str) -> List[str]:
    x = _to_feature.featurize(text)["X"]
    y_pred = tagger.tag(x)
    list_cut = []
    for j, k in zip(list(text), y_pred):
        if k == "1":
            list_cut.append(j)
        else:
            list_cut[-1] += j
    return list_cut