Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/chardet/hebrewprober.py: 96%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

85 statements  

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# Shy Shalom 

6# Portions created by the Initial Developer are Copyright (C) 2005 

7# the Initial Developer. All Rights Reserved. 

8# 

9# Contributor(s): 

10# Mark Pilgrim - port to Python 

11# 

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. 

16# 

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. 

21# 

22# You should have received a copy of the GNU Lesser General Public 

23# License along with this library; if not, see 

24# <https://www.gnu.org/licenses/>. 

25######################### END LICENSE BLOCK ######################### 

26 

27from typing import Optional, Union 

28 

29from .charsetprober import CharSetProber 

30from .enums import ProbingState 

31from .sbcharsetprober import SingleByteCharSetProber 

32 

33# This prober doesn't actually recognize a language or a charset. 

34# It is a helper prober for the use of the Hebrew model probers 

35 

36### General ideas of the Hebrew charset recognition ### 

37# 

38# Four main charsets exist in Hebrew: 

39# "ISO-8859-8" - Visual Hebrew 

40# "windows-1255" - Logical Hebrew 

41# "ISO-8859-8-I" - Logical Hebrew 

42# "x-mac-hebrew" - ?? Logical Hebrew ?? 

43# 

44# Both "ISO" charsets use a completely identical set of code points, whereas 

45# "windows-1255" and "x-mac-hebrew" are two different proper supersets of 

46# these code points. windows-1255 defines additional characters in the range 

47# 0x80-0x9F as some misc punctuation marks as well as some Hebrew-specific 

48# diacritics and additional 'Yiddish' ligature letters in the range 0xc0-0xd6. 

49# x-mac-hebrew defines similar additional code points but with a different 

50# mapping. 

51# 

52# As far as an average Hebrew text with no diacritics is concerned, all four 

53# charsets are identical with respect to code points. Meaning that for the 

54# main Hebrew alphabet, all four map the same values to all 27 Hebrew letters 

55# (including final letters). 

56# 

57# The dominant difference between these charsets is their directionality. 

58# "Visual" directionality means that the text is ordered as if the renderer is 

59# not aware of a BIDI rendering algorithm. The renderer sees the text and 

60# draws it from left to right. The text itself when ordered naturally is read 

61# backwards. A buffer of Visual Hebrew generally looks like so: 

62# "[last word of first line spelled backwards] [whole line ordered backwards 

63# and spelled backwards] [first word of first line spelled backwards] 

64# [end of line] [last word of second line] ... etc' " 

65# adding punctuation marks, numbers and English text to visual text is 

66# naturally also "visual" and from left to right. 

67# 

68# "Logical" directionality means the text is ordered "naturally" according to 

69# the order it is read. It is the responsibility of the renderer to display 

70# the text from right to left. A BIDI algorithm is used to place general 

71# punctuation marks, numbers and English text in the text. 

72# 

73# Texts in x-mac-hebrew are almost impossible to find on the Internet. From 

74# what little evidence I could find, it seems that its general directionality 

75# is Logical. 

76# 

77# To sum up all of the above, the Hebrew probing mechanism knows about two 

78# charsets: 

79# Visual Hebrew - "ISO-8859-8" - backwards text - Words and sentences are 

80# backwards while line order is natural. For charset recognition purposes 

81# the line order is unimportant (In fact, for this implementation, even 

82# word order is unimportant). 

83# Logical Hebrew - "windows-1255" - normal, naturally ordered text. 

84# 

85# "ISO-8859-8-I" is a subset of windows-1255 and doesn't need to be 

86# specifically identified. 

87# "x-mac-hebrew" is also identified as windows-1255. A text in x-mac-hebrew 

88# that contain special punctuation marks or diacritics is displayed with 

89# some unconverted characters showing as question marks. This problem might 

90# be corrected using another model prober for x-mac-hebrew. Due to the fact 

91# that x-mac-hebrew texts are so rare, writing another model prober isn't 

92# worth the effort and performance hit. 

93# 

94#### The Prober #### 

95# 

96# The prober is divided between two SBCharSetProbers and a HebrewProber, 

97# all of which are managed, created, fed data, inquired and deleted by the 

98# SBCSGroupProber. The two SBCharSetProbers identify that the text is in 

99# fact some kind of Hebrew, Logical or Visual. The final decision about which 

100# one is it is made by the HebrewProber by combining final-letter scores 

101# with the scores of the two SBCharSetProbers to produce a final answer. 

102# 

103# The SBCSGroupProber is responsible for stripping the original text of HTML 

104# tags, English characters, numbers, low-ASCII punctuation characters, spaces 

105# and new lines. It reduces any sequence of such characters to a single space. 

106# The buffer fed to each prober in the SBCS group prober is pure text in 

107# high-ASCII. 

108# The two SBCharSetProbers (model probers) share the same language model: 

109# Win1255Model. 

110# The first SBCharSetProber uses the model normally as any other 

111# SBCharSetProber does, to recognize windows-1255, upon which this model was 

112# built. The second SBCharSetProber is told to make the pair-of-letter 

113# lookup in the language model backwards. This in practice exactly simulates 

114# a visual Hebrew model using the windows-1255 logical Hebrew model. 

115# 

116# The HebrewProber is not using any language model. All it does is look for 

117# final-letter evidence suggesting the text is either logical Hebrew or visual 

118# Hebrew. Disjointed from the model probers, the results of the HebrewProber 

119# alone are meaningless. HebrewProber always returns 0.00 as confidence 

120# since it never identifies a charset by itself. Instead, the pointer to the 

121# HebrewProber is passed to the model probers as a helper "Name Prober". 

122# When the Group prober receives a positive identification from any prober, 

123# it asks for the name of the charset identified. If the prober queried is a 

124# Hebrew model prober, the model prober forwards the call to the 

125# HebrewProber to make the final decision. In the HebrewProber, the 

126# decision is made according to the final-letters scores maintained and Both 

127# model probers scores. The answer is returned in the form of the name of the 

128# charset identified, either "windows-1255" or "ISO-8859-8". 

129 

130 

131class HebrewProber(CharSetProber): 

132 SPACE = 0x20 

133 # windows-1255 / ISO-8859-8 code points of interest 

134 FINAL_KAF = 0xEA 

135 NORMAL_KAF = 0xEB 

136 FINAL_MEM = 0xED 

137 NORMAL_MEM = 0xEE 

138 FINAL_NUN = 0xEF 

139 NORMAL_NUN = 0xF0 

140 FINAL_PE = 0xF3 

141 NORMAL_PE = 0xF4 

142 FINAL_TSADI = 0xF5 

143 NORMAL_TSADI = 0xF6 

144 

145 # Minimum Visual vs Logical final letter score difference. 

146 # If the difference is below this, don't rely solely on the final letter score 

147 # distance. 

148 MIN_FINAL_CHAR_DISTANCE = 5 

149 

150 # Minimum Visual vs Logical model score difference. 

151 # If the difference is below this, don't rely at all on the model score 

152 # distance. 

153 MIN_MODEL_DISTANCE = 0.01 

154 

155 VISUAL_HEBREW_NAME = "ISO-8859-8" 

156 LOGICAL_HEBREW_NAME = "windows-1255" 

157 

158 def __init__(self) -> None: 

159 super().__init__() 

160 self._final_char_logical_score = 0 

161 self._final_char_visual_score = 0 

162 self._prev = self.SPACE 

163 self._before_prev = self.SPACE 

164 self._logical_prober: Optional[SingleByteCharSetProber] = None 

165 self._visual_prober: Optional[SingleByteCharSetProber] = None 

166 self.reset() 

167 

168 def reset(self) -> None: 

169 self._final_char_logical_score = 0 

170 self._final_char_visual_score = 0 

171 # The two last characters seen in the previous buffer, 

172 # mPrev and mBeforePrev are initialized to space in order to simulate 

173 # a word delimiter at the beginning of the data 

174 self._prev = self.SPACE 

175 self._before_prev = self.SPACE 

176 # These probers are owned by the group prober. 

177 

178 def set_model_probers( 

179 self, 

180 logical_prober: SingleByteCharSetProber, 

181 visual_prober: SingleByteCharSetProber, 

182 ) -> None: 

183 self._logical_prober = logical_prober 

184 self._visual_prober = visual_prober 

185 

186 def is_final(self, c: int) -> bool: 

187 return c in [ 

188 self.FINAL_KAF, 

189 self.FINAL_MEM, 

190 self.FINAL_NUN, 

191 self.FINAL_PE, 

192 self.FINAL_TSADI, 

193 ] 

194 

195 def is_non_final(self, c: int) -> bool: 

196 # The normal Tsadi is not a good Non-Final letter due to words like 

197 # 'lechotet' (to chat) containing an apostrophe after the tsadi. This 

198 # apostrophe is converted to a space in FilterWithoutEnglishLetters 

199 # causing the Non-Final tsadi to appear at an end of a word even 

200 # though this is not the case in the original text. 

201 # The letters Pe and Kaf rarely display a related behavior of not being 

202 # a good Non-Final letter. Words like 'Pop', 'Winamp' and 'Mubarak' 

203 # for example legally end with a Non-Final Pe or Kaf. However, the 

204 # benefit of these letters as Non-Final letters outweighs the damage 

205 # since these words are quite rare. 

206 return c in [self.NORMAL_KAF, self.NORMAL_MEM, self.NORMAL_NUN, self.NORMAL_PE] 

207 

208 def feed(self, byte_str: Union[bytes, bytearray]) -> ProbingState: 

209 # Final letter analysis for logical-visual decision. 

210 # Look for evidence that the received buffer is either logical Hebrew 

211 # or visual Hebrew. 

212 # The following cases are checked: 

213 # 1) A word longer than 1 letter, ending with a final letter. This is 

214 # an indication that the text is laid out "naturally" since the 

215 # final letter really appears at the end. +1 for logical score. 

216 # 2) A word longer than 1 letter, ending with a Non-Final letter. In 

217 # normal Hebrew, words ending with Kaf, Mem, Nun, Pe or Tsadi, 

218 # should not end with the Non-Final form of that letter. Exceptions 

219 # to this rule are mentioned above in isNonFinal(). This is an 

220 # indication that the text is laid out backwards. +1 for visual 

221 # score 

222 # 3) A word longer than 1 letter, starting with a final letter. Final 

223 # letters should not appear at the beginning of a word. This is an 

224 # indication that the text is laid out backwards. +1 for visual 

225 # score. 

226 # 

227 # The visual score and logical score are accumulated throughout the 

228 # text and are finally checked against each other in GetCharSetName(). 

229 # No checking for final letters in the middle of words is done since 

230 # that case is not an indication for either Logical or Visual text. 

231 # 

232 # We automatically filter out all 7-bit characters (replace them with 

233 # spaces) so the word boundary detection works properly. [MAP] 

234 

235 if self.state == ProbingState.NOT_ME: 

236 # Both model probers say it's not them. No reason to continue. 

237 return ProbingState.NOT_ME 

238 

239 byte_str = self.filter_high_byte_only(byte_str) 

240 

241 for cur in byte_str: 

242 if cur == self.SPACE: 

243 # We stand on a space - a word just ended 

244 if self._before_prev != self.SPACE: 

245 # next-to-last char was not a space so self._prev is not a 

246 # 1 letter word 

247 if self.is_final(self._prev): 

248 # case (1) [-2:not space][-1:final letter][cur:space] 

249 self._final_char_logical_score += 1 

250 elif self.is_non_final(self._prev): 

251 # case (2) [-2:not space][-1:Non-Final letter][ 

252 # cur:space] 

253 self._final_char_visual_score += 1 

254 else: 

255 # Not standing on a space 

256 if ( 

257 (self._before_prev == self.SPACE) 

258 and (self.is_final(self._prev)) 

259 and (cur != self.SPACE) 

260 ): 

261 # case (3) [-2:space][-1:final letter][cur:not space] 

262 self._final_char_visual_score += 1 

263 self._before_prev = self._prev 

264 self._prev = cur 

265 

266 # Forever detecting, till the end or until both model probers return 

267 # ProbingState.NOT_ME (handled above) 

268 return ProbingState.DETECTING 

269 

270 @property 

271 def charset_name(self) -> str: 

272 assert self._logical_prober is not None 

273 assert self._visual_prober is not None 

274 

275 # Make the decision: is it Logical or Visual? 

276 # If the final letter score distance is dominant enough, rely on it. 

277 finalsub = self._final_char_logical_score - self._final_char_visual_score 

278 if finalsub >= self.MIN_FINAL_CHAR_DISTANCE: 

279 return self.LOGICAL_HEBREW_NAME 

280 if finalsub <= -self.MIN_FINAL_CHAR_DISTANCE: 

281 return self.VISUAL_HEBREW_NAME 

282 

283 # It's not dominant enough, try to rely on the model scores instead. 

284 modelsub = ( 

285 self._logical_prober.get_confidence() - self._visual_prober.get_confidence() 

286 ) 

287 if modelsub > self.MIN_MODEL_DISTANCE: 

288 return self.LOGICAL_HEBREW_NAME 

289 if modelsub < -self.MIN_MODEL_DISTANCE: 

290 return self.VISUAL_HEBREW_NAME 

291 

292 # Still no good, back to final letter distance, maybe it'll save the 

293 # day. 

294 if finalsub < 0.0: 

295 return self.VISUAL_HEBREW_NAME 

296 

297 # (finalsub > 0 - Logical) or (don't know what to do) default to 

298 # Logical. 

299 return self.LOGICAL_HEBREW_NAME 

300 

301 @property 

302 def language(self) -> str: 

303 return "Hebrew" 

304 

305 @property 

306 def state(self) -> ProbingState: 

307 assert self._logical_prober is not None 

308 assert self._visual_prober is not None 

309 

310 # Remain active as long as any of the model probers are active. 

311 if (self._logical_prober.state == ProbingState.NOT_ME) and ( 

312 self._visual_prober.state == ProbingState.NOT_ME 

313 ): 

314 return ProbingState.NOT_ME 

315 return ProbingState.DETECTING