summaryrefslogtreecommitdiffstats
path: root/prepare.py
blob: 914c10ba69da911614a2bba41b6e5cd88786edd6 (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
#!/usr/bin/python3
import os
import os.path
import sqlite3
from argparse import ArgumentParser
import utils
from myconfig import MyConfig
from dirwalk import walkIndex


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);
'''


config = MyConfig()

#maximum combine number
N = config.getMaximumCombineNumber()

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


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)

        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.path.exists(onedir) or os.makedirs(onedir)

    #create sqlite databases
    createSqliteDatabases(onedir)

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


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

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