7ccea84faab9dfb2b5106a01c7409d066e704c9c
[sdc/sdc-distribution-client.git] /
1 ######################## BEGIN LICENSE BLOCK ########################
2 # The Original Code is Mozilla Universal charset detector code.
3 #
4 # The Initial Developer of the Original Code is
5 # Netscape Communications Corporation.
6 # Portions created by the Initial Developer are Copyright (C) 2001
7 # the Initial Developer. All Rights Reserved.
8 #
9 # Contributor(s):
10 #   Mark Pilgrim - port to Python
11 #   Shy Shalom - original C code
12 #
13 # This library is free software; you can redistribute it and/or
14 # modify it under the terms of the GNU Lesser General Public
15 # License as published by the Free Software Foundation; either
16 # version 2.1 of the License, or (at your option) any later version.
17 #
18 # This library is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21 # Lesser General Public License for more details.
22 #
23 # You should have received a copy of the GNU Lesser General Public
24 # License along with this library; if not, write to the Free Software
25 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
26 # 02110-1301  USA
27 ######################### END LICENSE BLOCK #########################
28
29 from . import constants
30 import sys
31 import codecs
32 from .latin1prober import Latin1Prober  # windows-1252
33 from .mbcsgroupprober import MBCSGroupProber  # multi-byte character sets
34 from .sbcsgroupprober import SBCSGroupProber  # single-byte character sets
35 from .escprober import EscCharSetProber  # ISO-2122, etc.
36 import re
37
38 MINIMUM_THRESHOLD = 0.20
39 ePureAscii = 0
40 eEscAscii = 1
41 eHighbyte = 2
42
43
44 class UniversalDetector:
45     def __init__(self):
46         self._highBitDetector = re.compile(b'[\x80-\xFF]')
47         self._escDetector = re.compile(b'(\033|~{)')
48         self._mEscCharSetProber = None
49         self._mCharSetProbers = []
50         self.reset()
51
52     def reset(self):
53         self.result = {'encoding': None, 'confidence': 0.0}
54         self.done = False
55         self._mStart = True
56         self._mGotData = False
57         self._mInputState = ePureAscii
58         self._mLastChar = b''
59         if self._mEscCharSetProber:
60             self._mEscCharSetProber.reset()
61         for prober in self._mCharSetProbers:
62             prober.reset()
63
64     def feed(self, aBuf):
65         if self.done:
66             return
67
68         aLen = len(aBuf)
69         if not aLen:
70             return
71
72         if not self._mGotData:
73             # If the data starts with BOM, we know it is UTF
74             if aBuf[:3] == codecs.BOM:
75                 # EF BB BF  UTF-8 with BOM
76                 self.result = {'encoding': "UTF-8", 'confidence': 1.0}
77             elif aBuf[:4] in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):
78                 # FF FE 00 00  UTF-32, little-endian BOM
79                 # 00 00 FE FF  UTF-32, big-endian BOM
80                 self.result = {'encoding': "UTF-32", 'confidence': 1.0}
81             elif aBuf[:4] == b'\xFE\xFF\x00\x00':
82                 # FE FF 00 00  UCS-4, unusual octet order BOM (3412)
83                 self.result = {
84                     'encoding': "X-ISO-10646-UCS-4-3412",
85                     'confidence': 1.0
86                 }
87             elif aBuf[:4] == b'\x00\x00\xFF\xFE':
88                 # 00 00 FF FE  UCS-4, unusual octet order BOM (2143)
89                 self.result = {
90                     'encoding': "X-ISO-10646-UCS-4-2143",
91                     'confidence': 1.0
92                 }
93             elif aBuf[:2] == codecs.BOM_LE or aBuf[:2] == codecs.BOM_BE:
94                 # FF FE  UTF-16, little endian BOM
95                 # FE FF  UTF-16, big endian BOM
96                 self.result = {'encoding': "UTF-16", 'confidence': 1.0}
97
98         self._mGotData = True
99         if self.result['encoding'] and (self.result['confidence'] > 0.0):
100             self.done = True
101             return
102
103         if self._mInputState == ePureAscii:
104             if self._highBitDetector.search(aBuf):
105                 self._mInputState = eHighbyte
106             elif ((self._mInputState == ePureAscii) and
107                     self._escDetector.search(self._mLastChar + aBuf)):
108                 self._mInputState = eEscAscii
109
110         self._mLastChar = aBuf[-1:]
111
112         if self._mInputState == eEscAscii:
113             if not self._mEscCharSetProber:
114                 self._mEscCharSetProber = EscCharSetProber()
115             if self._mEscCharSetProber.feed(aBuf) == constants.eFoundIt:
116                 self.result = {
117                     'encoding': self._mEscCharSetProber.get_charset_name(),
118                     'confidence': self._mEscCharSetProber.get_confidence()
119                 }
120                 self.done = True
121         elif self._mInputState == eHighbyte:
122             if not self._mCharSetProbers:
123                 self._mCharSetProbers = [MBCSGroupProber(), SBCSGroupProber(),
124                                          Latin1Prober()]
125             for prober in self._mCharSetProbers:
126                 if prober.feed(aBuf) == constants.eFoundIt:
127                     self.result = {'encoding': prober.get_charset_name(),
128                                    'confidence': prober.get_confidence()}
129                     self.done = True
130                     break
131
132     def close(self):
133         if self.done:
134             return
135         if not self._mGotData:
136             if constants._debug:
137                 sys.stderr.write('no data received!\n')
138             return
139         self.done = True
140
141         if self._mInputState == ePureAscii:
142             self.result = {'encoding': 'ascii', 'confidence': 1.0}
143             return self.result
144
145         if self._mInputState == eHighbyte:
146             proberConfidence = None
147             maxProberConfidence = 0.0
148             maxProber = None
149             for prober in self._mCharSetProbers:
150                 if not prober:
151                     continue
152                 proberConfidence = prober.get_confidence()
153                 if proberConfidence > maxProberConfidence:
154                     maxProberConfidence = proberConfidence
155                     maxProber = prober
156             if maxProber and (maxProberConfidence > MINIMUM_THRESHOLD):
157                 self.result = {'encoding': maxProber.get_charset_name(),
158                                'confidence': maxProber.get_confidence()}
159                 return self.result
160
161         if constants._debug:
162             sys.stderr.write('no probers hit minimum threshhold\n')
163             for prober in self._mCharSetProbers[0].mProbers:
164                 if not prober:
165                     continue
166                 sys.stderr.write('%s confidence = %s\n' %
167                                  (prober.get_charset_name(),
168                                   prober.get_confidence()))