~jtv/corpusfiltergraph/cross-python

« back to all changes in this revision

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