You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

292 lines
14 KiB

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