summaryrefslogtreecommitdiffstats
path: root/partialword.py
blob: 61c8e7dbd82be979f4a21ae3cbac56f85b348306 (plain)
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
#!/usr/bin/python3
import os
import sqlite3
from argparse import ArgumentParser
from operator import itemgetter
import utils
from myconfig import MyConfig
from dirwalk import walkIndex

config = MyConfig()

#change cwd to the word recognizer directory
words_dir = config.getWordRecognizerDir()
os.chdir(words_dir)
#chdir done

############################################################
#                     Get Threshold                        #
############################################################

SELECT_WORD_DML = '''
SELECT freq from ngram where words = ?;
'''

def getWordFrequency(conn, word):
    sep = config.getWordSep()
    word_str = sep + word + sep

    cur = conn.cursor()
    row = cur.execute(SELECT_WORD_DML, (word_str, )).fetchone()

    if None == row:
        return 0
    else:
        freq = row[0]
        return freq


def computeThreshold(conn):
    wordswithfreq = []
    wordlistfile = open(config.getWordsListFileName(), "r")

    for oneline in wordlistfile.readlines():
        oneline = oneline.rstrip(os.linesep)

        if len(oneline) == 0:
            continue

        word = oneline

        freq = getWordFrequency(conn, word)

        if freq < config.getWordMinimumOccurrence():
            continue

        wordswithfreq.append((word, freq))

    wordlistfile.close()

    #ascending sort
    wordswithfreq.sort(key=itemgetter(1))
    pos = int(len(wordswithfreq) * config.getPartialWordThreshold())
    (word, threshold) = wordswithfreq[-pos]
    print(word, threshold)
    return threshold


def getThreshold(workdir):
    print(workdir, 'threshold')

    length = 1
    filename = config.getNgramFileName(length)
    filepath = workdir + os.sep + filename

    conn = sqlite3.connect(filepath)

    threshold = computeThreshold(conn)

    conn.commit()
    if conn:
        conn.close()

    return threshold


############################################################
#                   Get Partial Word                       #
############################################################

SELECT_PARTIAL_WORD_DML = '''
SELECT words, freq FROM ngram WHERE freq > ?;
'''

#try update first to get affected row count
UPDATE_LOW_NGRAM_DML = '''
UPDATE ngram SET freq = freq + ? WHERE words = ?;
'''

INSERT_LOW_NGRAM_DML = '''
INSERT INTO ngram (words, freq) VALUES (?, ?);
'''

#try delete last
DELETE_HIGH_NGRAM_DML = '''
DELETE FROM ngram WHERE words = ?;
'''


#sqlite full text search section
CREATE_NGRAM_FTS_DDL = '''
CREATE VIRTUAL TABLE ngram_fts USING fts3 (words TEXT NOT NULL, freq INTEGER NOT NULL);
'''

POPULATE_NGRAM_FTS_DML = '''
INSERT INTO ngram_fts (words, freq) SELECT words, freq FROM ngram WHERE freq > ?;
'''

DROP_NGRAM_FTS_DML = '''
DROP TABLE IF EXISTS ngram_fts;
'''

SELECT_MERGE_HIGH_NGRAM_DML = '''
SELECT words, freq FROM ngram_fts WHERE words MATCH ?;
'''

#maximum combine number
N = config.getMaximumCombineNumber()


#load existing words
words_set = set([])

def load_words(filename):
    wordlistfile = open(filename, "r")

    for oneline in wordlistfile.readlines():
        oneline = oneline.rstrip(os.linesep)

        if len(oneline) == 0:
            continue

        word = oneline

        words_set.add(word)

    wordlistfile.close()


def createNgramTableClone(conn):
    print("creating ngram fts table...")

    threshold = config.getNgramMinimumOccurrence()

    cur = conn.cursor()

    cur.execute(CREATE_NGRAM_FTS_DDL)
    cur.execute(POPULATE_NGRAM_FTS_DML, (threshold, ))

    conn.commit()


def dropNgramTableClone(conn):
    print("dropping ngram fts table...")
    cur = conn.cursor()

    cur.execute(DROP_NGRAM_FTS_DML)

    conn.commit()


#from 2-gram.db
def getPartialWordList(conn, threshold):
    #print(threshold)

    words_list = []
    sep = config.getWordSep()

    cur = conn.cursor()
    rows = cur.execute(SELECT_PARTIAL_WORD_DML, (threshold, )).fetchall()

    for row in rows:
        (words_str, freq) = row
        (prefix, postfix) = words_str.strip(sep).split(sep, 1)
        merged_word = prefix + postfix
        words_list.append((merged_word, prefix, postfix, freq))

    conn.commit()
    return words_list


def getMatchedItems(cur, words):
    #print(words)
    (prefix, postfix) = words

    matched_list = []
    sep = config.getWordSep()
    words_str = '"' + sep + prefix + sep + postfix + sep + '"'
    #print(words_str)

    rows = cur.execute(SELECT_MERGE_HIGH_NGRAM_DML, (words_str, )).fetchall()

    for row in rows:
        (words, freq) = row
        matched_list.append((words, freq))

    return matched_list


def doCombineWord(high_cur, low_cur, words):
    #print(words)
    (prefix, postfix) = words

    sep = config.getWordSep()

    matched_items = getMatchedItems(high_cur, words)
    words_str = sep + prefix + sep + postfix + sep
    #print(words_str)

    #if the to-be-merged sequence has several matched pairs,
    #  then several sequences will be added to lower-gram.
    #TODO: maybe consider equally divide the matched_freq.
    for item in matched_items:
        (matched_words_str, matched_freq) = item
        assert words_str in matched_words_str
        merged_str = sep + prefix + postfix + sep

        (left, middle, right) = matched_words_str.partition(words_str)
        while middle != '':
            merged_words_str = left + merged_str + right

            #print(matched_words_str), print(merged_words_str)
            assert len(matched_words_str) == len(merged_words_str) + 1

            #do combine
            rowcount = low_cur.execute(UPDATE_LOW_NGRAM_DML, \
                                           (matched_freq, merged_words_str)).rowcount
            #print(rowcount)
            assert rowcount <= 1

            if 0 == rowcount:
                low_cur.execute(INSERT_LOW_NGRAM_DML, \
                                    (merged_words_str, matched_freq))

                rowcount = high_cur.execute(DELETE_HIGH_NGRAM_DML, \
                                                (merged_words_str, )).rowcount
                assert rowcount <= 1

            (partial_left, middle, right) = right.partition(words_str)
            left = left + middle + partial_left


def recognizePartialWord(workdir, threshold):
    print(workdir, threshold)

    iternum = 0
    maxIter = config.getMaximumIteration()

    bigram_set = set([])

    filename = config.getPartialWordFileName()
    filepath = workdir + os.sep + filename
    partialwordfile = open(filepath, "w")

    while iternum < maxIter :
        print("pass ", iternum)

        length = 2
        filename = config.getNgramFileName(length)
        filepath = workdir + os.sep + filename

        conn = sqlite3.connect(filepath)
        partial_words_list = getPartialWordList(conn, threshold)
        conn.close()

        changed_num = 0
        for item in partial_words_list:
            (merged_word, prefix, postfix, freq) = item
            if merged_word in words_set :
                continue
            if (prefix, postfix) in bigram_set:
                continue
            changed_num = changed_num + 1

        if 0 == changed_num:
            break;

        for item in partial_words_list:
            (merged_word, prefix, postfix, freq) = item
            if merged_word in words_set:
                continue
            if (prefix, postfix) in bigram_set:
                continue
            oneline = "\t".join((merged_word, prefix, postfix, str(freq)))
            partialwordfile.writelines([oneline, os.linesep])

        for i in range(N, 1, -1):
            #high n-gram
            filename = config.getNgramFileName(i)
            filepath = workdir + os.sep + filename
            high_conn = sqlite3.connect(filepath)
            high_cur = high_conn.cursor()

            #low n-gram
            filename = config.getNgramFileName(i - 1)
            filepath = workdir + os.sep + filename
            low_conn = sqlite3.connect(filepath)
            low_cur = low_conn.cursor()

            dropNgramTableClone(high_conn)
            createNgramTableClone(high_conn)

            for item in partial_words_list:
                (merged_word, prefix, postfix, freq) = item

                if merged_word in words_set :
                    continue

                if (prefix, postfix) in bigram_set:
                    continue

                print(merged_word, prefix, postfix, freq, i)
                doCombineWord(high_cur, low_cur, (prefix, postfix))

            high_conn.commit(), low_conn.commit()
            dropNgramTableClone(high_conn)
            high_conn.close(), low_conn.close()

        for item in partial_words_list:
            (merged_word, prefix, postfix, freq) = item
            bigram_set.add((prefix, postfix))

        iternum = iternum + 1

    partialwordfile.close()
    print(workdir, 'done')


def handleOneIndex(indexpath, subdir, indexname):
    print(indexpath, subdir, indexname)

    indexstatuspath = indexpath + config.getStatusPostfix()
    indexstatus = utils.load_status(indexstatuspath)
    if not utils.check_epoch(indexstatus, 'Populate'):
        raise utils.EpochError('Please populate first.\n')
    if utils.check_epoch(indexstatus, 'PartialWord'):
        return

    workdir = config.getWordRecognizerDir() + os.sep + \
        subdir + os.sep + indexname
    print(workdir)

    threshold = getThreshold(workdir)
    indexstatus['PartialWordThreshold'] = threshold
    utils.store_status(indexstatuspath, indexstatus)

    recognizePartialWord(workdir, threshold)

    #sign epoch
    utils.sign_epoch(indexstatus, 'PartialWord')
    utils.store_status(indexstatuspath, indexstatus)


print("loading words.txt...")
load_words(config.getWordsListFileName())
#print(words_set)


if __name__ == '__main__':
    parser = ArgumentParser(description='Recognize partial words.')
    parser.add_argument('--indexdir', action='store', \
                            help='index directory', \
                            default=config.getTextIndexDir())


    args = parser.parse_args()
    print(args)
    walkIndex(handleOneIndex, args.indexdir)
    print('done')