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
|
#!/usr/bin/python3
import os
import os.path
import sqlite3
from argparse import ArgumentParser
import utils
from myconfig import MyConfig
CREATE_NGRAM_DDL = '''
CREATE TABLE ngram (
words TEXT NOT NULL,
freq INTEGER NOT NULL
);
'''
CREATE_NGRAM_INDEX_DDL = '''
CREATE UNIQUE INDEX ngram_index on ngram(words);
'''
CREATE_BIGRAM_DDL = '''
CREATE TABLE bigram (
prefix TEXT NOT NULL,
postfix TEXT NOT NULL,
freq INTEGER NOT NULL
);
'''
config = MyConfig()
#maximum combine number
N = config.getMaximumCombineNumber()
#change cwd to the word recognizer directory
words_dir = config.getWordRecognizerDir()
os.makedirs(words_dir, exist_ok=True)
os.chdir(words_dir)
#chdir done
def handleError(error):
sys.exit(error)
def createSqliteDatabases(onedir):
print(onedir)
#create databases
for i in range(1, N + 1):
filename = config.getNgramFileName(i)
filepath = onedir + os.sep + filename
print(filepath)
#create database
if os.access(filepath, os.F_OK):
os.unlink(filepath)
conn = sqlite3.connect(filepath)
cur = conn.cursor()
cur.execute(CREATE_NGRAM_DDL)
cur.execute(CREATE_NGRAM_INDEX_DDL)
#special case for bi-gram
if 2 == i:
cur.execute(CREATE_BIGRAM_DDL)
conn.commit()
if conn:
conn.close()
def handleOneIndex(indexpath, subdir, indexname):
print(indexpath, subdir, indexname)
indexstatuspath = indexpath + config.getStatusPostfix()
indexstatus = utils.load_status(indexstatuspath)
if not utils.check_epoch(indexstatus, 'Segment'):
raise utils.EpochError('Please segment first.\n')
if utils.check_epoch(indexstatus, 'Prepare'):
return
#create directory
onedir = config.getWordRecognizerDir() + os.sep + \
subdir + os.sep + indexname
os.makedirs(onedir, exist_ok=True)
#create sqlite databases
createSqliteDatabases(onedir)
#sign epoch
utils.sign_epoch(indexstatus, 'Prepare')
utils.store_status(indexstatuspath, indexstatus)
def walkThroughIndex(path):
for root, dirs, files in os.walk(path, topdown=True, onerror=handleError):
for onefile in files:
filepath = os.path.join(root, onefile)
indexpostfix = config.getIndexPostfix()
if onefile.endswith(indexpostfix):
subdir = os.path.relpath(root, path)
indexname = onefile[:-len(indexpostfix)]
handleOneIndex(filepath, subdir, indexname)
elif onefile.endswith(config.getStatusPostfix()):
pass
else:
print('Unexpected file:' + filepath)
if __name__ == '__main__':
parser = ArgumentParser(description='Prepare word recognizer.')
parser.add_argument('--indexdir', action='store', \
help='index directory', \
default=os.path.join(config.getTextDir(), 'index'))
args = parser.parse_args()
print(args)
walkThroughIndex(args.indexdir)
print('done')
|