~ubuntu-branches/ubuntu/jaunty/calibre/jaunty-backports

« back to all changes in this revision

Viewing changes to src/calibre/ebooks/chardet/universaldetector.py

  • Committer: Bazaar Package Importer
  • Author(s): Martin Pitt
  • Date: 2009-01-20 17:14:02 UTC
  • Revision ID: james.westby@ubuntu.com-20090120171402-8y3znf6nokwqe80k
Tags: upstream-0.4.125+dfsg
ImportĀ upstreamĀ versionĀ 0.4.125+dfsg

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
import constants, sys
 
30
from latin1prober import Latin1Prober # windows-1252
 
31
from mbcsgroupprober import MBCSGroupProber # multi-byte character sets
 
32
from sbcsgroupprober import SBCSGroupProber # single-byte character sets
 
33
from escprober import EscCharSetProber # ISO-2122, etc.
 
34
import re
 
35
 
 
36
MINIMUM_THRESHOLD = 0.20
 
37
ePureAscii = 0
 
38
eEscAscii = 1
 
39
eHighbyte = 2
 
40
 
 
41
class UniversalDetector:
 
42
    def __init__(self):
 
43
        self._highBitDetector = re.compile(r'[\x80-\xFF]')
 
44
        self._escDetector = re.compile(r'(\033|~{)')
 
45
        self._mEscCharSetProber = None
 
46
        self._mCharSetProbers = []
 
47
        self.reset()
 
48
 
 
49
    def reset(self):
 
50
        self.result = {'encoding': None, 'confidence': 0.0}
 
51
        self.done = constants.False
 
52
        self._mStart = constants.True
 
53
        self._mGotData = constants.False
 
54
        self._mInputState = ePureAscii
 
55
        self._mLastChar = ''
 
56
        if self._mEscCharSetProber:
 
57
            self._mEscCharSetProber.reset()
 
58
        for prober in self._mCharSetProbers:
 
59
            prober.reset()
 
60
 
 
61
    def feed(self, aBuf):
 
62
        if self.done: return
 
63
 
 
64
        aLen = len(aBuf)
 
65
        if not aLen: return
 
66
        
 
67
        if not self._mGotData:
 
68
            # If the data starts with BOM, we know it is UTF
 
69
            if aBuf[:3] == '\xEF\xBB\xBF':
 
70
                # EF BB BF  UTF-8 with BOM
 
71
                self.result = {'encoding': "UTF-8", 'confidence': 1.0}
 
72
            elif aBuf[:4] == '\xFF\xFE\x00\x00':
 
73
                # FF FE 00 00  UTF-32, little-endian BOM
 
74
                self.result = {'encoding': "UTF-32LE", 'confidence': 1.0}
 
75
            elif aBuf[:4] == '\x00\x00\xFE\xFF': 
 
76
                # 00 00 FE FF  UTF-32, big-endian BOM
 
77
                self.result = {'encoding': "UTF-32BE", 'confidence': 1.0}
 
78
            elif aBuf[:4] == '\xFE\xFF\x00\x00':
 
79
                # FE FF 00 00  UCS-4, unusual octet order BOM (3412)
 
80
                self.result = {'encoding': "X-ISO-10646-UCS-4-3412", 'confidence': 1.0}
 
81
            elif aBuf[:4] == '\x00\x00\xFF\xFE':
 
82
                # 00 00 FF FE  UCS-4, unusual octet order BOM (2143)
 
83
                self.result = {'encoding': "X-ISO-10646-UCS-4-2143", 'confidence': 1.0}
 
84
            elif aBuf[:4] == '\xFF\xFE':
 
85
                # FF FE  UTF-16, little endian BOM
 
86
                self.result = {'encoding': "UTF-16LE", 'confidence': 1.0}
 
87
            elif aBuf[:2] == '\xFE\xFF':
 
88
                # FE FF  UTF-16, big endian BOM
 
89
                self.result = {'encoding': "UTF-16BE", 'confidence': 1.0}
 
90
 
 
91
        self._mGotData = constants.True
 
92
        if self.result['encoding'] and (self.result['confidence'] > 0.0):
 
93
            self.done = constants.True
 
94
            return
 
95
 
 
96
        if self._mInputState == ePureAscii:
 
97
            if self._highBitDetector.search(aBuf):
 
98
                self._mInputState = eHighbyte
 
99
            elif (self._mInputState == ePureAscii) and self._escDetector.search(self._mLastChar + aBuf):
 
100
                self._mInputState = eEscAscii
 
101
 
 
102
        self._mLastChar = aBuf[-1]
 
103
 
 
104
        if self._mInputState == eEscAscii:
 
105
            if not self._mEscCharSetProber:
 
106
                self._mEscCharSetProber = EscCharSetProber()
 
107
            if self._mEscCharSetProber.feed(aBuf) == constants.eFoundIt:
 
108
                self.result = {'encoding': self._mEscCharSetProber.get_charset_name(),
 
109
                               'confidence': self._mEscCharSetProber.get_confidence()}
 
110
                self.done = constants.True
 
111
        elif self._mInputState == eHighbyte:
 
112
            if not self._mCharSetProbers:
 
113
                self._mCharSetProbers = [MBCSGroupProber(), SBCSGroupProber(), Latin1Prober()]
 
114
            for prober in self._mCharSetProbers:
 
115
                if prober.feed(aBuf) == constants.eFoundIt:
 
116
                    self.result = {'encoding': prober.get_charset_name(),
 
117
                                   'confidence': prober.get_confidence()}
 
118
                    self.done = constants.True
 
119
                    break
 
120
 
 
121
    def close(self):
 
122
        if self.done: return
 
123
        if not self._mGotData:
 
124
            if constants._debug:
 
125
                sys.stderr.write('no data received!\n')
 
126
            return
 
127
        self.done = constants.True
 
128
        
 
129
        if self._mInputState == ePureAscii:
 
130
            self.result = {'encoding': 'ascii', 'confidence': 1.0}
 
131
            return self.result
 
132
 
 
133
        if self._mInputState == eHighbyte:
 
134
            proberConfidence = None
 
135
            maxProberConfidence = 0.0
 
136
            maxProber = None
 
137
            for prober in self._mCharSetProbers:
 
138
                if not prober: continue
 
139
                proberConfidence = prober.get_confidence()
 
140
                if proberConfidence > maxProberConfidence:
 
141
                    maxProberConfidence = proberConfidence
 
142
                    maxProber = prober
 
143
            if maxProber and (maxProberConfidence > MINIMUM_THRESHOLD):
 
144
                self.result = {'encoding': maxProber.get_charset_name(),
 
145
                               'confidence': maxProber.get_confidence()}
 
146
                return self.result
 
147
 
 
148
        if constants._debug:
 
149
            sys.stderr.write('no probers hit minimum threshhold\n')
 
150
            for prober in self._mCharSetProbers[0].mProbers:
 
151
                if not prober: continue
 
152
                sys.stderr.write('%s confidence = %s\n' % \
 
153
                                 (prober.get_charset_name(), \
 
154
                                  prober.get_confidence()))