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
|
#! /usr/bin/env python
# -*- coding: utf8 -*-
#===============================================================================
# Author: Walapa Muangjeen
#===============================================================================
#version:
#5.0.424 - new CorpusFiltergraph 5.0 interface
import os
import sys
import logging
import re
logger = logging.getLogger('.'.join([os.path.splitext(os.path.basename(sys.argv[0]))[0],'manager','filtergraph',__name__]))
class filter(object):
def __init__(self):
self.cfg = {
'encoding': 'utf8',
'inputfile': '',
'outputfile': '',
'version': '5.0.424',
}
self.encoding = 'utf8'
self.inputfile = ''
self.outputfile = ''
self.isopen = False
self.was_run = False
self.p = object
self.errors = []
def open(self,cfg):
self.encoding = 'utf8' if 'utf8' in cfg['encoding'].lower().replace('-','') else cfg['encoding']
self.inputfile = cfg['inputfile'].replace('%(rootfolder)s',self.p.rootfolder) if cfg['inputfile'] else self.inputfile
self.outputfile = cfg['outputfile'].replace('%(rootfolder)s',self.p.rootfolder) if cfg['outputfile'] else self.outputfile
if (self.inputfile and not self.outputfile) or (not self.inputfile and self.outputfile):
self.errors.append([__name__,'invalid','[%s] inputfile=%s without outputfile= value'%(__name__,cfg['inputfile'])])
logger.warn('%s\t%s',*self.errors[-1][1:])
def run(self,k):
if self.inputfile:
return
self.p.cfoutput[k]['tempbuff'] = [re.sub( r' +' , r'', line ) for line in self.p.cfoutput[k]['tempbuff']]
def flush(self):
if not self.inputfile:
return
import codecs
from FilterGraph.progress_bar import ProgressBar
if not os.path.exists(self.inputfile):
self.errors.append([__name__,'missing','[%s] %s'%(__name__,self.inputfile)])
logger.error('%s\t%s',*self.errors[-1][1:])
return
# make output folder
try:
os.makedirs(os.path.dirname(self.outputfile))
except OSError,e:
if not e.errno == 17:
logger.exception('%s\t%s, %s, %s',*['failed',e.errno,e.strerror,e.filename,])
raise OSError(e)
# open input and output files
out = self.outputfile
if out == self.inputfile:
import tempfile
dirname = os.sep.join([self.p.tempdir,__name__])
cf.makedirs(dirname)
fd,out = tempfile.mkstemp(suffix='.tmp', prefix='~', dir=dirname)
os.close(fd)
ttl_lines = cf.file_length(self.inputfile)
try:
o = codecs.open(out,'w',self.encoding)
except Exception as e:
self.errors.append([__name__,'failed','[%s] output: %s'%(__name__,out)])
logger.error('%s\t%s',*self.errors[-1][1:])
raise
try:
i = codecs.open(self.inputfile,'r',self.encoding)
except Exception as e:
self.errors.append([__name__,'failed','[%s] input: %s'%(__name__,self.inputfile)])
logger.error('%s\t%s',*self.errors[-1][1:])
raise
progress = ProgressBar()
progress.reset(0,ttl_lines,72,mode='fixed',char='#')
sys.stderr.write('[%s] %s\n'%(__name__,self.outputfile.encode('utf8')))
try:
# loop writes output line-by-line
for line in i:
o.write('%s\x0a' % re.sub( r' +' , r'', line.rstrip('\r\n')))
progress.increment_amount()
sys.stderr.write(progress.bar)
sys.stderr.flush()
sys.stderr.write('\n')
progress.update_amount(ttl_lines)
sys.stderr.write(progress.bar)
sys.stderr.write('\n')
sys.stderr.flush()
# close input and output files
i.close()
o.close()
if not out == self.outputfile:
import shutil
shutil.move(out,self.outputfile)
except KeyboardInterrupt:
os.unlink(out)
raise KeyboardInterrupt()
if not os.path.exists(self.outputfile):
self.errors.append([__name__,'missing','[%s] %s'%(__name__,self.outputfile)])
logger.error('%s\t%s',*self.errors[-1][1:])
def close(self):
return
def usage():
'''Command prompt help.'''
return "\n%s\n\tUsage:\n\tfrom %s import filter\n"%(
os.path.basename(sys.argv[0]),
os.path.splitext(os.path.basename(sys.argv[0]))[0]
)
licensetxt=u'''CorpusFiltergraphâ„¢ v5.0
Copyright © 2010-2014 Precision Translation Tools Co., Ltd.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see http://www.gnu.org/licenses/.
For more information, please contact Precision Translation Tools Co., Ltd.
at: http://www.precisiontranslationtools.com'''
if __name__ == "__main__":
import os
import sys
sys.stdout.write(usage().encode('utf8')+'\n')
else:
from FilterGraph import common as cf
|