summaryrefslogtreecommitdiffstats
path: root/segment.py
blob: 7992eb0b2690d63e66d7afaef197765b93ec87ad (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
#!/usr/bin/python3
import os
import os.path
import sys
from argparse import ArgumentParser
from subprocess import Popen, PIPE
import utils
from myconfig import MyConfig


config = MyConfig()

#change cwd to the libpinyin utils/segment directory
libpinyin_dir = config.getToolsDir()
libpinyin_sub_dir = os.path.join(libpinyin_dir, 'data')
os.chdir(libpinyin_sub_dir)
#chdir done


def handleError(error):
    sys.exit(error)


def segmentOneText(infile, outfile, reportfile, fast):
    infilestatuspath = infile + config.getStatusPostfix()
    infilestatus = utils.load_status(infilestatuspath)
    if utils.check_epoch(infilestatus, 'Segment'):
        return

    #begin processing
    if fast:
        cmdline = '../utils/segment/spseg >"' + outfile + '"'
    else:
        cmdline = '../utils/segment/ngseg >"' + outfile + '"'

    subprocess = Popen(cmdline, shell=True, stdin=PIPE, stderr=PIPE, \
                           close_fds=True)

    with open(infile, 'rb') as f:
        subprocess.stdin.writelines(f.readlines())
    subprocess.stdin.close()
    f.close()

    lines = subprocess.stderr.readlines()
    if lines:
        print('found error report')
        with open(reportfile, 'wb') as f:
            f.writelines(lines)
        f.close()

    os.waitpid(subprocess.pid, 0)
    #end processing

    utils.sign_epoch(infilestatus, 'Segment')
    utils.store_status(infilestatuspath, infilestatus)


def handleOneIndex(indexpath, fast):
    indexstatuspath = indexpath + config.getStatusPostfix()
    indexstatus = utils.load_status(indexstatuspath)
    if utils.check_epoch(indexstatus, 'Segment'):
        return

    #begin processing
    indexfile = open(indexpath, 'r')
    for oneline in indexfile.readlines():
        #remove tailing '\n'
        oneline = oneline.rstrip(os.linesep)
        (title, textpath) = oneline.split('#')
        infile = config.getTextDir() + textpath
        outfile = config.getTextDir() + textpath + config.getSegmentPostfix()
        reportfile = config.getTextDir() + textpath + \
            config.getSegmentReportPostfix()
        print("Processing " + title + '#' + textpath)
        segmentOneText(infile, outfile, reportfile, fast)
        print("Processed " + title + '#' + textpath)
    indexfile.close()
    #end processing

    utils.sign_epoch(indexstatus, 'Segment')
    utils.store_status(indexstatuspath, indexstatus)


def walkThroughIndex(path, fast):
    for root, dirs, files in os.walk(path, topdown=True, onerror=handleError):
        for onefile in files:
            filepath = os.path.join(root, onefile)
            if onefile.endswith(config.getIndexPostfix()):
                handleOneIndex(filepath, fast)
            elif onefile.endswith(config.getStatusPostfix()):
                pass
            else:
                print('Unexpected file:' + filepath)


if __name__ == '__main__':
    parser = ArgumentParser(description='Segment all raw corpus documents.')
    parser.add_argument('--indexdir', action='store', \
                            help='index directory', \
                            default=config.getTextIndexDir())

    parser.add_argument('--fast', action='store_const', \
                            help='Use spseg to speed up segment', \
                            const=True, default=False)

    args = parser.parse_args()
    print(args)
    walkThroughIndex(args.indexdir, args.fast)
    print('done')