~jtv/corpusfiltergraph/cross-python

« back to all changes in this revision

Viewing changes to trunk/lib/corpusfg/plugins/remove-irrelevant.py

  • Committer: tahoar
  • Date: 2012-05-02 15:46:23 UTC
  • Revision ID: svn-v4:bc069b21-dff4-4e29-a776-06a4e04bad4e::266
new layout. need to update code to use the new layout

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#! /usr/bin/env python
 
2
# -*- coding: utf8 -*-
 
3
 
 
4
#===============================================================================
 
5
# Author: Walapa Muangjeen
 
6
#===============================================================================
 
7
 
 
8
#version:
 
9
#4.0.264 - version update
 
10
 
 
11
import os
 
12
import sys
 
13
import string
 
14
import re
 
15
import common as cf
 
16
import logging
 
17
 
 
18
logger = logging.getLogger('.'.join([os.path.splitext(os.path.basename(sys.argv[0]))[0],'manager','filtergraph',__name__]))
 
19
skipclose = True
 
20
 
 
21
class filter(object):
 
22
 
 
23
        cfg = {
 
24
                'deleteline': False,
 
25
                'irrelevant': string.punctuation+string.whitespace+string.digits,
 
26
                'encoding': 'utf8',
 
27
                'inputfile': '',
 
28
                'outputfile': '',
 
29
                'version': '4.0.264',
 
30
                }
 
31
        deleteline = False
 
32
        irrelevant = string.punctuation+string.whitespace+string.digits
 
33
        encoding = 'utf8'
 
34
        inputfile = ''
 
35
        outputfile = ''
 
36
        isopen = False
 
37
        p = object
 
38
        errors = []
 
39
 
 
40
        def open(self,parent,cfg):
 
41
                self.encoding = 'utf8' if 'utf8' in cfg['encoding'].lower().replace('-','') else cfg['encoding']
 
42
                self.inputfile = cfg['inputfile'].replace('%(rootfolder)s',parent.rootfolder) if cfg['inputfile'] else self.inputfile
 
43
                self.outputfile = cfg['outputfile'].replace('%(rootfolder)s',parent.rootfolder) if cfg['outputfile'] else self.outputfile
 
44
                if (self.inputfile and not self.outputfile) or (not self.inputfile and self.outputfile):
 
45
                        self.errors.append([__name__,'invalid','[%s] inputfile=%s without outputfile= value'%(__name__,cfg['inputfile'])])
 
46
                        logger.warn('%s\t%s',*self.errors[-1][1:])
 
47
 
 
48
                self.deleteline = cfg['deleteline']
 
49
                self.irrelevant = string.punctuation+string.whitespace+string.digits+''.join([ char for char in cf.dedupelist(cfg['irrelevant']) if not char in string.punctuation+string.whitespace+string.digits ])
 
50
                self.regex = re.compile('[%s]'%re.escape(self.irrelevant))
 
51
        def run(self,k):
 
52
                global skipclose
 
53
                skipclose = not self.inputfile
 
54
                if self.inputfile: return
 
55
 
 
56
                if self.deleteline:
 
57
                        self.p.cfoutput[k]['tempbuff'] = [line for line in self.p.cfoutput[k]['tempbuff'] if len(self.regex.sub('', line))]
 
58
                else:
 
59
                        self.p.cfoutput[k]['tempbuff'] = [self.__filter(line) for line in self.p.cfoutput[k]['tempbuff']]
 
60
 
 
61
        def __filter(self,line):
 
62
                if not self.regex.sub('', line): line = ''
 
63
                return line
 
64
 
 
65
        def flush(self,k):
 
66
                return
 
67
 
 
68
        def close(self):
 
69
                if skipclose: return
 
70
 
 
71
                import codecs
 
72
 
 
73
                if not os.path.exists(self.inputfile):
 
74
                        self.errors.append([__name__,'missing','[%s] %s'%(__name__,self.inputfile)])
 
75
                        logger.error('%s\t%s',*self.errors[-1][1:])
 
76
                        return
 
77
 
 
78
                # make output folder
 
79
                try:
 
80
                        os.makedirs(os.path.dirname(self.outputfile))
 
81
                except OSError,e:
 
82
                        if not e.errno == 17:
 
83
                                logger.exception('%s\t%s, %s, %s',*['failed',e.errno,e.strerror,e.filename,])
 
84
                                raise OSError(e)
 
85
 
 
86
                # open input and output files
 
87
                out = self.outputfile
 
88
                if out == self.inputfile:
 
89
                        import tempfile
 
90
                        fd,out = tempfile.mkstemp(suffix='.tmp', prefix='~', dir=self.p.tempdir)
 
91
                        os.close(fd)
 
92
                try:
 
93
                        o = codecs.open(out,'w',self.encoding)
 
94
                        i = codecs.open(self.inputfile,'r',self.encoding)
 
95
                except:
 
96
                        raise RuntimeError('Failed to open [%s] input/output files'%(__name__))
 
97
 
 
98
                sys.stderr.write('[%s] %s\n   Please wait'%(__name__,self.outputfile))
 
99
                cnt = 0
 
100
                try:
 
101
                        # loop writes output line-by-line
 
102
                        for line in i:
 
103
                                o.write('%s\n'%(self.__filter(line.rstrip('\r\n'))))
 
104
                                cnt += 1
 
105
                                if not cnt%5000: sys.stderr.write('.')
 
106
                        sys.stderr.write('\n')
 
107
                        # close input and output files
 
108
                        i.close()
 
109
                        o.close()
 
110
 
 
111
                        if not out == self.outputfile:
 
112
                                import shutil
 
113
                                shutil.move(out,self.outputfile)
 
114
 
 
115
                except KeyboardInterrupt:
 
116
                        os.unlink(out)
 
117
                        raise KeyboardInterrupt()
 
118
 
 
119
                if not os.path.exists(self.outputfile):
 
120
                        self.errors.append([__name__,'missing','[%s] %s'%(__name__,self.outputfile)])
 
121
                        logger.error('%s\t%s',*self.errors[-1][1:])
 
122
 
 
123
def usage():
 
124
        '''Command prompt help.'''
 
125
        return "\n%s\n\tUsage:\n\tfrom %s import filter\n"%(
 
126
        os.path.basename(sys.argv[0]),
 
127
        os.path.splitext(os.path.basename(sys.argv[0]))[0]
 
128
        )
 
129
 
 
130
licensetxt=u'''CorpusFiltergraph™ v4.0
 
131
Copyright © 2010-2012 Precision Translation Tools Co., Ltd.
 
132
 
 
133
This program is free software: you can redistribute it and/or modify
 
134
it under the terms of the GNU Lesser General Public License as published by
 
135
the Free Software Foundation, either version 3 of the License, or
 
136
(at your option) any later version.
 
137
 
 
138
This program is distributed in the hope that it will be useful,
 
139
but WITHOUT ANY WARRANTY; without even the implied warranty of
 
140
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
141
GNU Lesser General Public License for more details.
 
142
 
 
143
You should have received a copy of the GNU Lesser General Public License
 
144
along with this program.  If not, see http://www.gnu.org/licenses/.
 
145
 
 
146
For more information, please contact Precision Translation Tools Co., Ltd.
 
147
at: http://www.precisiontranslationtools.com'''
 
148
 
 
149
if __name__ == "__main__":
 
150
        import os
 
151
        import sys
 
152
        sys.stdout.write(usage().encode('utf8')+'\n')