~jtv/corpusfiltergraph/cross-python

« back to all changes in this revision

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