hebrewprober.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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, write to the Free Software
  24. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  25. # 02110-1301 USA
  26. ######################### END LICENSE BLOCK #########################
  27. from typing import Optional, Union
  28. from .charsetprober import CharSetProber
  29. from .enums import ProbingState
  30. from .sbcharsetprober import SingleByteCharSetProber
  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
  33. ### General ideas of the Hebrew charset recognition ###
  34. #
  35. # Four main charsets exist in Hebrew:
  36. # "ISO-8859-8" - Visual Hebrew
  37. # "windows-1255" - Logical Hebrew
  38. # "ISO-8859-8-I" - Logical Hebrew
  39. # "x-mac-hebrew" - ?? Logical Hebrew ??
  40. #
  41. # Both "ISO" charsets use a completely identical set of code points, whereas
  42. # "windows-1255" and "x-mac-hebrew" are two different proper supersets of
  43. # these code points. windows-1255 defines additional characters in the range
  44. # 0x80-0x9F as some misc punctuation marks as well as some Hebrew-specific
  45. # diacritics and additional 'Yiddish' ligature letters in the range 0xc0-0xd6.
  46. # x-mac-hebrew defines similar additional code points but with a different
  47. # mapping.
  48. #
  49. # As far as an average Hebrew text with no diacritics is concerned, all four
  50. # charsets are identical with respect to code points. Meaning that for the
  51. # main Hebrew alphabet, all four map the same values to all 27 Hebrew letters
  52. # (including final letters).
  53. #
  54. # The dominant difference between these charsets is their directionality.
  55. # "Visual" directionality means that the text is ordered as if the renderer is
  56. # not aware of a BIDI rendering algorithm. The renderer sees the text and
  57. # draws it from left to right. The text itself when ordered naturally is read
  58. # backwards. A buffer of Visual Hebrew generally looks like so:
  59. # "[last word of first line spelled backwards] [whole line ordered backwards
  60. # and spelled backwards] [first word of first line spelled backwards]
  61. # [end of line] [last word of second line] ... etc' "
  62. # adding punctuation marks, numbers and English text to visual text is
  63. # naturally also "visual" and from left to right.
  64. #
  65. # "Logical" directionality means the text is ordered "naturally" according to
  66. # the order it is read. It is the responsibility of the renderer to display
  67. # the text from right to left. A BIDI algorithm is used to place general
  68. # punctuation marks, numbers and English text in the text.
  69. #
  70. # Texts in x-mac-hebrew are almost impossible to find on the Internet. From
  71. # what little evidence I could find, it seems that its general directionality
  72. # is Logical.
  73. #
  74. # To sum up all of the above, the Hebrew probing mechanism knows about two
  75. # charsets:
  76. # Visual Hebrew - "ISO-8859-8" - backwards text - Words and sentences are
  77. # backwards while line order is natural. For charset recognition purposes
  78. # the line order is unimportant (In fact, for this implementation, even
  79. # word order is unimportant).
  80. # Logical Hebrew - "windows-1255" - normal, naturally ordered text.
  81. #
  82. # "ISO-8859-8-I" is a subset of windows-1255 and doesn't need to be
  83. # specifically identified.
  84. # "x-mac-hebrew" is also identified as windows-1255. A text in x-mac-hebrew
  85. # that contain special punctuation marks or diacritics is displayed with
  86. # some unconverted characters showing as question marks. This problem might
  87. # be corrected using another model prober for x-mac-hebrew. Due to the fact
  88. # that x-mac-hebrew texts are so rare, writing another model prober isn't
  89. # worth the effort and performance hit.
  90. #
  91. #### The Prober ####
  92. #
  93. # The prober is divided between two SBCharSetProbers and a HebrewProber,
  94. # all of which are managed, created, fed data, inquired and deleted by the
  95. # SBCSGroupProber. The two SBCharSetProbers identify that the text is in
  96. # fact some kind of Hebrew, Logical or Visual. The final decision about which
  97. # one is it is made by the HebrewProber by combining final-letter scores
  98. # with the scores of the two SBCharSetProbers to produce a final answer.
  99. #
  100. # The SBCSGroupProber is responsible for stripping the original text of HTML
  101. # tags, English characters, numbers, low-ASCII punctuation characters, spaces
  102. # and new lines. It reduces any sequence of such characters to a single space.
  103. # The buffer fed to each prober in the SBCS group prober is pure text in
  104. # high-ASCII.
  105. # The two SBCharSetProbers (model probers) share the same language model:
  106. # Win1255Model.
  107. # The first SBCharSetProber uses the model normally as any other
  108. # SBCharSetProber does, to recognize windows-1255, upon which this model was
  109. # built. The second SBCharSetProber is told to make the pair-of-letter
  110. # lookup in the language model backwards. This in practice exactly simulates
  111. # a visual Hebrew model using the windows-1255 logical Hebrew model.
  112. #
  113. # The HebrewProber is not using any language model. All it does is look for
  114. # final-letter evidence suggesting the text is either logical Hebrew or visual
  115. # Hebrew. Disjointed from the model probers, the results of the HebrewProber
  116. # alone are meaningless. HebrewProber always returns 0.00 as confidence
  117. # since it never identifies a charset by itself. Instead, the pointer to the
  118. # HebrewProber is passed to the model probers as a helper "Name Prober".
  119. # When the Group prober receives a positive identification from any prober,
  120. # it asks for the name of the charset identified. If the prober queried is a
  121. # Hebrew model prober, the model prober forwards the call to the
  122. # HebrewProber to make the final decision. In the HebrewProber, the
  123. # decision is made according to the final-letters scores maintained and Both
  124. # model probers scores. The answer is returned in the form of the name of the
  125. # charset identified, either "windows-1255" or "ISO-8859-8".
  126. class HebrewProber(CharSetProber):
  127. SPACE = 0x20
  128. # windows-1255 / ISO-8859-8 code points of interest
  129. FINAL_KAF = 0xEA
  130. NORMAL_KAF = 0xEB
  131. FINAL_MEM = 0xED
  132. NORMAL_MEM = 0xEE
  133. FINAL_NUN = 0xEF
  134. NORMAL_NUN = 0xF0
  135. FINAL_PE = 0xF3
  136. NORMAL_PE = 0xF4
  137. FINAL_TSADI = 0xF5
  138. NORMAL_TSADI = 0xF6
  139. # Minimum Visual vs Logical final letter score difference.
  140. # If the difference is below this, don't rely solely on the final letter score
  141. # distance.
  142. MIN_FINAL_CHAR_DISTANCE = 5
  143. # Minimum Visual vs Logical model score difference.
  144. # If the difference is below this, don't rely at all on the model score
  145. # distance.
  146. MIN_MODEL_DISTANCE = 0.01
  147. VISUAL_HEBREW_NAME = "ISO-8859-8"
  148. LOGICAL_HEBREW_NAME = "windows-1255"
  149. def __init__(self) -> None:
  150. super().__init__()
  151. self._final_char_logical_score = 0
  152. self._final_char_visual_score = 0
  153. self._prev = self.SPACE
  154. self._before_prev = self.SPACE
  155. self._logical_prober: Optional[SingleByteCharSetProber] = None
  156. self._visual_prober: Optional[SingleByteCharSetProber] = None
  157. self.reset()
  158. def reset(self) -> None:
  159. self._final_char_logical_score = 0
  160. self._final_char_visual_score = 0
  161. # The two last characters seen in the previous buffer,
  162. # mPrev and mBeforePrev are initialized to space in order to simulate
  163. # a word delimiter at the beginning of the data
  164. self._prev = self.SPACE
  165. self._before_prev = self.SPACE
  166. # These probers are owned by the group prober.
  167. def set_model_probers(
  168. self,
  169. logical_prober: SingleByteCharSetProber,
  170. visual_prober: SingleByteCharSetProber,
  171. ) -> None:
  172. self._logical_prober = logical_prober
  173. self._visual_prober = visual_prober
  174. def is_final(self, c: int) -> bool:
  175. return c in [
  176. self.FINAL_KAF,
  177. self.FINAL_MEM,
  178. self.FINAL_NUN,
  179. self.FINAL_PE,
  180. self.FINAL_TSADI,
  181. ]
  182. def is_non_final(self, c: int) -> bool:
  183. # The normal Tsadi is not a good Non-Final letter due to words like
  184. # 'lechotet' (to chat) containing an apostrophe after the tsadi. This
  185. # apostrophe is converted to a space in FilterWithoutEnglishLetters
  186. # causing the Non-Final tsadi to appear at an end of a word even
  187. # though this is not the case in the original text.
  188. # The letters Pe and Kaf rarely display a related behavior of not being
  189. # a good Non-Final letter. Words like 'Pop', 'Winamp' and 'Mubarak'
  190. # for example legally end with a Non-Final Pe or Kaf. However, the
  191. # benefit of these letters as Non-Final letters outweighs the damage
  192. # since these words are quite rare.
  193. return c in [self.NORMAL_KAF, self.NORMAL_MEM, self.NORMAL_NUN, self.NORMAL_PE]
  194. def feed(self, byte_str: Union[bytes, bytearray]) -> ProbingState:
  195. # Final letter analysis for logical-visual decision.
  196. # Look for evidence that the received buffer is either logical Hebrew
  197. # or visual Hebrew.
  198. # The following cases are checked:
  199. # 1) A word longer than 1 letter, ending with a final letter. This is
  200. # an indication that the text is laid out "naturally" since the
  201. # final letter really appears at the end. +1 for logical score.
  202. # 2) A word longer than 1 letter, ending with a Non-Final letter. In
  203. # normal Hebrew, words ending with Kaf, Mem, Nun, Pe or Tsadi,
  204. # should not end with the Non-Final form of that letter. Exceptions
  205. # to this rule are mentioned above in isNonFinal(). This is an
  206. # indication that the text is laid out backwards. +1 for visual
  207. # score
  208. # 3) A word longer than 1 letter, starting with a final letter. Final
  209. # letters should not appear at the beginning of a word. This is an
  210. # indication that the text is laid out backwards. +1 for visual
  211. # score.
  212. #
  213. # The visual score and logical score are accumulated throughout the
  214. # text and are finally checked against each other in GetCharSetName().
  215. # No checking for final letters in the middle of words is done since
  216. # that case is not an indication for either Logical or Visual text.
  217. #
  218. # We automatically filter out all 7-bit characters (replace them with
  219. # spaces) so the word boundary detection works properly. [MAP]
  220. if self.state == ProbingState.NOT_ME:
  221. # Both model probers say it's not them. No reason to continue.
  222. return ProbingState.NOT_ME
  223. byte_str = self.filter_high_byte_only(byte_str)
  224. for cur in byte_str:
  225. if cur == self.SPACE:
  226. # We stand on a space - a word just ended
  227. if self._before_prev != self.SPACE:
  228. # next-to-last char was not a space so self._prev is not a
  229. # 1 letter word
  230. if self.is_final(self._prev):
  231. # case (1) [-2:not space][-1:final letter][cur:space]
  232. self._final_char_logical_score += 1
  233. elif self.is_non_final(self._prev):
  234. # case (2) [-2:not space][-1:Non-Final letter][
  235. # cur:space]
  236. self._final_char_visual_score += 1
  237. else:
  238. # Not standing on a space
  239. if (
  240. (self._before_prev == self.SPACE)
  241. and (self.is_final(self._prev))
  242. and (cur != self.SPACE)
  243. ):
  244. # case (3) [-2:space][-1:final letter][cur:not space]
  245. self._final_char_visual_score += 1
  246. self._before_prev = self._prev
  247. self._prev = cur
  248. # Forever detecting, till the end or until both model probers return
  249. # ProbingState.NOT_ME (handled above)
  250. return ProbingState.DETECTING
  251. @property
  252. def charset_name(self) -> str:
  253. assert self._logical_prober is not None
  254. assert self._visual_prober is not None
  255. # Make the decision: is it Logical or Visual?
  256. # If the final letter score distance is dominant enough, rely on it.
  257. finalsub = self._final_char_logical_score - self._final_char_visual_score
  258. if finalsub >= self.MIN_FINAL_CHAR_DISTANCE:
  259. return self.LOGICAL_HEBREW_NAME
  260. if finalsub <= -self.MIN_FINAL_CHAR_DISTANCE:
  261. return self.VISUAL_HEBREW_NAME
  262. # It's not dominant enough, try to rely on the model scores instead.
  263. modelsub = (
  264. self._logical_prober.get_confidence() - self._visual_prober.get_confidence()
  265. )
  266. if modelsub > self.MIN_MODEL_DISTANCE:
  267. return self.LOGICAL_HEBREW_NAME
  268. if modelsub < -self.MIN_MODEL_DISTANCE:
  269. return self.VISUAL_HEBREW_NAME
  270. # Still no good, back to final letter distance, maybe it'll save the
  271. # day.
  272. if finalsub < 0.0:
  273. return self.VISUAL_HEBREW_NAME
  274. # (finalsub > 0 - Logical) or (don't know what to do) default to
  275. # Logical.
  276. return self.LOGICAL_HEBREW_NAME
  277. @property
  278. def language(self) -> str:
  279. return "Hebrew"
  280. @property
  281. def state(self) -> ProbingState:
  282. assert self._logical_prober is not None
  283. assert self._visual_prober is not None
  284. # Remain active as long as any of the model probers are active.
  285. if (self._logical_prober.state == ProbingState.NOT_ME) and (
  286. self._visual_prober.state == ProbingState.NOT_ME
  287. ):
  288. return ProbingState.NOT_ME
  289. return ProbingState.DETECTING