Catch the exception if decoding failed.
[pymailheaders.git] / chardet / hebrewprober.py
bloba2b1eaa992310b1eda5263b77d1d091b3e915511
1 ######################## BEGIN LICENSE BLOCK ########################
2 # The Original Code is Mozilla Universal charset detector code.
4 # The Initial Developer of the Original Code is
5 # Shy Shalom
6 # Portions created by the Initial Developer are Copyright (C) 2005
7 # the Initial Developer. All Rights Reserved.
9 # Contributor(s):
10 # Mark Pilgrim - port to Python
12 # This library is free software; you can redistribute it and/or
13 # modify it under the terms of the GNU Lesser General Public
14 # License as published by the Free Software Foundation; either
15 # version 2.1 of the License, or (at your option) any later version.
17 # This library is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 # Lesser General Public License for more details.
22 # You should have received a copy of the GNU Lesser General Public
23 # License along with this library; if not, write to the Free Software
24 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
25 # 02110-1301 USA
26 ######################### END LICENSE BLOCK #########################
28 from charsetprober import CharSetProber
29 import constants
31 # This prober doesn't actually recognize a language or a charset.
32 # It is a helper prober for the use of the Hebrew model probers
34 ### General ideas of the Hebrew charset recognition ###
36 # Four main charsets exist in Hebrew:
37 # "ISO-8859-8" - Visual Hebrew
38 # "windows-1255" - Logical Hebrew
39 # "ISO-8859-8-I" - Logical Hebrew
40 # "x-mac-hebrew" - ?? Logical Hebrew ??
42 # Both "ISO" charsets use a completely identical set of code points, whereas
43 # "windows-1255" and "x-mac-hebrew" are two different proper supersets of
44 # these code points. windows-1255 defines additional characters in the range
45 # 0x80-0x9F as some misc punctuation marks as well as some Hebrew-specific
46 # diacritics and additional 'Yiddish' ligature letters in the range 0xc0-0xd6.
47 # x-mac-hebrew defines similar additional code points but with a different
48 # mapping.
50 # As far as an average Hebrew text with no diacritics is concerned, all four
51 # charsets are identical with respect to code points. Meaning that for the
52 # main Hebrew alphabet, all four map the same values to all 27 Hebrew letters
53 # (including final letters).
55 # The dominant difference between these charsets is their directionality.
56 # "Visual" directionality means that the text is ordered as if the renderer is
57 # not aware of a BIDI rendering algorithm. The renderer sees the text and
58 # draws it from left to right. The text itself when ordered naturally is read
59 # backwards. A buffer of Visual Hebrew generally looks like so:
60 # "[last word of first line spelled backwards] [whole line ordered backwards
61 # and spelled backwards] [first word of first line spelled backwards]
62 # [end of line] [last word of second line] ... etc' "
63 # adding punctuation marks, numbers and English text to visual text is
64 # naturally also "visual" and from left to right.
66 # "Logical" directionality means the text is ordered "naturally" according to
67 # the order it is read. It is the responsibility of the renderer to display
68 # the text from right to left. A BIDI algorithm is used to place general
69 # punctuation marks, numbers and English text in the text.
71 # Texts in x-mac-hebrew are almost impossible to find on the Internet. From
72 # what little evidence I could find, it seems that its general directionality
73 # is Logical.
75 # To sum up all of the above, the Hebrew probing mechanism knows about two
76 # charsets:
77 # Visual Hebrew - "ISO-8859-8" - backwards text - Words and sentences are
78 # backwards while line order is natural. For charset recognition purposes
79 # the line order is unimportant (In fact, for this implementation, even
80 # word order is unimportant).
81 # Logical Hebrew - "windows-1255" - normal, naturally ordered text.
83 # "ISO-8859-8-I" is a subset of windows-1255 and doesn't need to be
84 # specifically identified.
85 # "x-mac-hebrew" is also identified as windows-1255. A text in x-mac-hebrew
86 # that contain special punctuation marks or diacritics is displayed with
87 # some unconverted characters showing as question marks. This problem might
88 # be corrected using another model prober for x-mac-hebrew. Due to the fact
89 # that x-mac-hebrew texts are so rare, writing another model prober isn't
90 # worth the effort and performance hit.
92 #### The Prober ####
94 # The prober is divided between two SBCharSetProbers and a HebrewProber,
95 # all of which are managed, created, fed data, inquired and deleted by the
96 # SBCSGroupProber. The two SBCharSetProbers identify that the text is in
97 # fact some kind of Hebrew, Logical or Visual. The final decision about which
98 # one is it is made by the HebrewProber by combining final-letter scores
99 # with the scores of the two SBCharSetProbers to produce a final answer.
101 # The SBCSGroupProber is responsible for stripping the original text of HTML
102 # tags, English characters, numbers, low-ASCII punctuation characters, spaces
103 # and new lines. It reduces any sequence of such characters to a single space.
104 # The buffer fed to each prober in the SBCS group prober is pure text in
105 # high-ASCII.
106 # The two SBCharSetProbers (model probers) share the same language model:
107 # Win1255Model.
108 # The first SBCharSetProber uses the model normally as any other
109 # SBCharSetProber does, to recognize windows-1255, upon which this model was
110 # built. The second SBCharSetProber is told to make the pair-of-letter
111 # lookup in the language model backwards. This in practice exactly simulates
112 # a visual Hebrew model using the windows-1255 logical Hebrew model.
114 # The HebrewProber is not using any language model. All it does is look for
115 # final-letter evidence suggesting the text is either logical Hebrew or visual
116 # Hebrew. Disjointed from the model probers, the results of the HebrewProber
117 # alone are meaningless. HebrewProber always returns 0.00 as confidence
118 # since it never identifies a charset by itself. Instead, the pointer to the
119 # HebrewProber is passed to the model probers as a helper "Name Prober".
120 # When the Group prober receives a positive identification from any prober,
121 # it asks for the name of the charset identified. If the prober queried is a
122 # Hebrew model prober, the model prober forwards the call to the
123 # HebrewProber to make the final decision. In the HebrewProber, the
124 # decision is made according to the final-letters scores maintained and Both
125 # model probers scores. The answer is returned in the form of the name of the
126 # charset identified, either "windows-1255" or "ISO-8859-8".
128 # windows-1255 / ISO-8859-8 code points of interest
129 FINAL_KAF = '\xea'
130 NORMAL_KAF = '\xeb'
131 FINAL_MEM = '\xed'
132 NORMAL_MEM = '\xee'
133 FINAL_NUN = '\xef'
134 NORMAL_NUN = '\xf0'
135 FINAL_PE = '\xf3'
136 NORMAL_PE = '\xf4'
137 FINAL_TSADI = '\xf5'
138 NORMAL_TSADI = '\xf6'
140 # Minimum Visual vs Logical final letter score difference.
141 # If the difference is below this, don't rely solely on the final letter score distance.
142 MIN_FINAL_CHAR_DISTANCE = 5
144 # Minimum Visual vs Logical model score difference.
145 # If the difference is below this, don't rely at all on the model score distance.
146 MIN_MODEL_DISTANCE = 0.01
148 VISUAL_HEBREW_NAME = "ISO-8859-8"
149 LOGICAL_HEBREW_NAME = "windows-1255"
151 class HebrewProber(CharSetProber):
152 def __init__(self):
153 CharSetProber.__init__(self)
154 self._mLogicalProber = None
155 self._mVisualProber = None
156 self.reset()
158 def reset(self):
159 self._mFinalCharLogicalScore = 0
160 self._mFinalCharVisualScore = 0
161 # The two last characters seen in the previous buffer,
162 # mPrev and mBeforePrev are initialized to space in order to simulate a word
163 # delimiter at the beginning of the data
164 self._mPrev = ' '
165 self._mBeforePrev = ' '
166 # These probers are owned by the group prober.
168 def set_model_probers(self, logicalProber, visualProber):
169 self._mLogicalProber = logicalProber
170 self._mVisualProber = visualProber
172 def is_final(self, c):
173 return c in [FINAL_KAF, FINAL_MEM, FINAL_NUN, FINAL_PE, FINAL_TSADI]
175 def is_non_final(self, c):
176 # The normal Tsadi is not a good Non-Final letter due to words like
177 # 'lechotet' (to chat) containing an apostrophe after the tsadi. This
178 # apostrophe is converted to a space in FilterWithoutEnglishLetters causing
179 # the Non-Final tsadi to appear at an end of a word even though this is not
180 # the case in the original text.
181 # The letters Pe and Kaf rarely display a related behavior of not being a
182 # good Non-Final letter. Words like 'Pop', 'Winamp' and 'Mubarak' for
183 # example legally end with a Non-Final Pe or Kaf. However, the benefit of
184 # these letters as Non-Final letters outweighs the damage since these words
185 # are quite rare.
186 return c in [NORMAL_KAF, NORMAL_MEM, NORMAL_NUN, NORMAL_PE]
188 def feed(self, aBuf):
189 # Final letter analysis for logical-visual decision.
190 # Look for evidence that the received buffer is either logical Hebrew or
191 # visual Hebrew.
192 # The following cases are checked:
193 # 1) A word longer than 1 letter, ending with a final letter. This is an
194 # indication that the text is laid out "naturally" since the final letter
195 # really appears at the end. +1 for logical score.
196 # 2) A word longer than 1 letter, ending with a Non-Final letter. In normal
197 # Hebrew, words ending with Kaf, Mem, Nun, Pe or Tsadi, should not end with
198 # the Non-Final form of that letter. Exceptions to this rule are mentioned
199 # above in isNonFinal(). This is an indication that the text is laid out
200 # backwards. +1 for visual score
201 # 3) A word longer than 1 letter, starting with a final letter. Final letters
202 # should not appear at the beginning of a word. This is an indication that
203 # the text is laid out backwards. +1 for visual score.
205 # The visual score and logical score are accumulated throughout the text and
206 # are finally checked against each other in GetCharSetName().
207 # No checking for final letters in the middle of words is done since that case
208 # is not an indication for either Logical or Visual text.
210 # We automatically filter out all 7-bit characters (replace them with spaces)
211 # so the word boundary detection works properly. [MAP]
213 if self.get_state() == constants.eNotMe:
214 # Both model probers say it's not them. No reason to continue.
215 return constants.eNotMe
217 aBuf = self.filter_high_bit_only(aBuf)
219 for cur in aBuf:
220 if cur == ' ':
221 # We stand on a space - a word just ended
222 if self._mBeforePrev != ' ':
223 # next-to-last char was not a space so self._mPrev is not a 1 letter word
224 if self.is_final(self._mPrev):
225 # case (1) [-2:not space][-1:final letter][cur:space]
226 self._mFinalCharLogicalScore += 1
227 elif self.is_non_final(self._mPrev):
228 # case (2) [-2:not space][-1:Non-Final letter][cur:space]
229 self._mFinalCharVisualScore += 1
230 else:
231 # Not standing on a space
232 if (self._mBeforePrev == ' ') and (self.is_final(self._mPrev)) and (cur != ' '):
233 # case (3) [-2:space][-1:final letter][cur:not space]
234 self._mFinalCharVisualScore += 1
235 self._mBeforePrev = self._mPrev
236 self._mPrev = cur
238 # Forever detecting, till the end or until both model probers return eNotMe (handled above)
239 return constants.eDetecting
241 def get_charset_name(self):
242 # Make the decision: is it Logical or Visual?
243 # If the final letter score distance is dominant enough, rely on it.
244 finalsub = self._mFinalCharLogicalScore - self._mFinalCharVisualScore
245 if finalsub >= MIN_FINAL_CHAR_DISTANCE:
246 return LOGICAL_HEBREW_NAME
247 if finalsub <= -MIN_FINAL_CHAR_DISTANCE:
248 return VISUAL_HEBREW_NAME
250 # It's not dominant enough, try to rely on the model scores instead.
251 modelsub = self._mLogicalProber.get_confidence() - self._mVisualProber.get_confidence()
252 if modelsub > MIN_MODEL_DISTANCE:
253 return LOGICAL_HEBREW_NAME
254 if modelsub < -MIN_MODEL_DISTANCE:
255 return VISUAL_HEBREW_NAME
257 # Still no good, back to final letter distance, maybe it'll save the day.
258 if finalsub < 0.0:
259 return VISUAL_HEBREW_NAME
261 # (finalsub > 0 - Logical) or (don't know what to do) default to Logical.
262 return LOGICAL_HEBREW_NAME
264 def get_state(self):
265 # Remain active as long as any of the model probers are active.
266 if (self._mLogicalProber.get_state() == constants.eNotMe) and \
267 (self._mVisualProber.get_state() == constants.eNotMe):
268 return constants.eNotMe
269 return constants.eDetecting