2
0

HebrewProber.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. /* ***** BEGIN LICENSE BLOCK *****
  2. * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3. *
  4. * The contents of this file are subject to the Mozilla Public License Version
  5. * 1.1 (the "License"); you may not use this file except in compliance with
  6. * the License. You may obtain a copy of the License at
  7. * http://www.mozilla.org/MPL/
  8. *
  9. * Software distributed under the License is distributed on an "AS IS" basis,
  10. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11. * for the specific language governing rights and limitations under the
  12. * License.
  13. *
  14. * The Original Code is Mozilla Universal charset detector code.
  15. *
  16. * The Initial Developer of the Original Code is
  17. * Netscape Communications Corporation.
  18. * Portions created by the Initial Developer are Copyright (C) 2001
  19. * the Initial Developer. All Rights Reserved.
  20. *
  21. * Contributor(s):
  22. * Shy Shalom <shooshX@gmail.com>
  23. * Rudi Pettazzi <rudi.pettazzi@gmail.com> (C# port)
  24. *
  25. * Alternatively, the contents of this file may be used under the terms of
  26. * either the GNU General Public License Version 2 or later (the "GPL"), or
  27. * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  28. * in which case the provisions of the GPL or the LGPL are applicable instead
  29. * of those above. If you wish to allow use of your version of this file only
  30. * under the terms of either the GPL or the LGPL, and not to allow others to
  31. * use your version of this file under the terms of the MPL, indicate your
  32. * decision by deleting the provisions above and replace them with the notice
  33. * and other provisions required by the GPL or the LGPL. If you do not delete
  34. * the provisions above, a recipient may use your version of this file under
  35. * the terms of any one of the MPL, the GPL or the LGPL.
  36. *
  37. * ***** END LICENSE BLOCK ***** */
  38. using System;
  39. /**
  40. * General ideas of the Hebrew charset recognition
  41. *
  42. * Four main charsets exist in Hebrew:
  43. * "ISO-8859-8" - Visual Hebrew
  44. * "windows-1255" - Logical Hebrew
  45. * "ISO-8859-8-I" - Logical Hebrew
  46. * "x-mac-hebrew" - ?? Logical Hebrew ??
  47. *
  48. * Both "ISO" charsets use a completely identical set of code points, whereas
  49. * "windows-1255" and "x-mac-hebrew" are two different proper supersets of
  50. * these code points. windows-1255 defines additional characters in the range
  51. * 0x80-0x9F as some misc punctuation marks as well as some Hebrew-specific
  52. * diacritics and additional 'Yiddish' ligature letters in the range 0xc0-0xd6.
  53. * x-mac-hebrew defines similar additional code points but with a different
  54. * mapping.
  55. *
  56. * As far as an average Hebrew text with no diacritics is concerned, all four
  57. * charsets are identical with respect to code points. Meaning that for the
  58. * main Hebrew alphabet, all four map the same values to all 27 Hebrew letters
  59. * (including final letters).
  60. *
  61. * The dominant difference between these charsets is their directionality.
  62. * "Visual" directionality means that the text is ordered as if the renderer is
  63. * not aware of a BIDI rendering algorithm. The renderer sees the text and
  64. * draws it from left to right. The text itself when ordered naturally is read
  65. * backwards. A buffer of Visual Hebrew generally looks like so:
  66. * "[last word of first line spelled backwards] [whole line ordered backwards
  67. * and spelled backwards] [first word of first line spelled backwards]
  68. * [end of line] [last word of second line] ... etc' "
  69. * adding punctuation marks, numbers and English text to visual text is
  70. * naturally also "visual" and from left to right.
  71. *
  72. * "Logical" directionality means the text is ordered "naturally" according to
  73. * the order it is read. It is the responsibility of the renderer to display
  74. * the text from right to left. A BIDI algorithm is used to place general
  75. * punctuation marks, numbers and English text in the text.
  76. *
  77. * Texts in x-mac-hebrew are almost impossible to find on the Internet. From
  78. * what little evidence I could find, it seems that its general directionality
  79. * is Logical.
  80. *
  81. * To sum up all of the above, the Hebrew probing mechanism knows about two
  82. * charsets:
  83. * Visual Hebrew - "ISO-8859-8" - backwards text - Words and sentences are
  84. * backwards while line order is natural. For charset recognition purposes
  85. * the line order is unimportant (In fact, for this implementation, even
  86. * word order is unimportant).
  87. * Logical Hebrew - "windows-1255" - normal, naturally ordered text.
  88. *
  89. * "ISO-8859-8-I" is a subset of windows-1255 and doesn't need to be
  90. * specifically identified.
  91. * "x-mac-hebrew" is also identified as windows-1255. A text in x-mac-hebrew
  92. * that contain special punctuation marks or diacritics is displayed with
  93. * some unconverted characters showing as question marks. This problem might
  94. * be corrected using another model prober for x-mac-hebrew. Due to the fact
  95. * that x-mac-hebrew texts are so rare, writing another model prober isn't
  96. * worth the effort and performance hit.
  97. *
  98. * *** The Prober ***
  99. *
  100. * The prober is divided between two nsSBCharSetProbers and an nsHebrewProber,
  101. * all of which are managed, created, fed data, inquired and deleted by the
  102. * nsSBCSGroupProber. The two nsSBCharSetProbers identify that the text is in
  103. * fact some kind of Hebrew, Logical or Visual. The final decision about which
  104. * one is it is made by the nsHebrewProber by combining final-letter scores
  105. * with the scores of the two nsSBCharSetProbers to produce a final answer.
  106. *
  107. * The nsSBCSGroupProber is responsible for stripping the original text of HTML
  108. * tags, English characters, numbers, low-ASCII punctuation characters, spaces
  109. * and new lines. It reduces any sequence of such characters to a single space.
  110. * The buffer fed to each prober in the SBCS group prober is pure text in
  111. * high-ASCII.
  112. * The two nsSBCharSetProbers (model probers) share the same language model:
  113. * Win1255Model.
  114. * The first nsSBCharSetProber uses the model normally as any other
  115. * nsSBCharSetProber does, to recognize windows-1255, upon which this model was
  116. * built. The second nsSBCharSetProber is told to make the pair-of-letter
  117. * lookup in the language model backwards. This in practice exactly simulates
  118. * a visual Hebrew model using the windows-1255 logical Hebrew model.
  119. *
  120. * The nsHebrewProber is not using any language model. All it does is look for
  121. * final-letter evidence suggesting the text is either logical Hebrew or visual
  122. * Hebrew. Disjointed from the model probers, the results of the nsHebrewProber
  123. * alone are meaningless. nsHebrewProber always returns 0.00 as confidence
  124. * since it never identifies a charset by itself. Instead, the pointer to the
  125. * nsHebrewProber is passed to the model probers as a helper "Name Prober".
  126. * When the Group prober receives a positive identification from any prober,
  127. * it asks for the name of the charset identified. If the prober queried is a
  128. * Hebrew model prober, the model prober forwards the call to the
  129. * nsHebrewProber to make the final decision. In the nsHebrewProber, the
  130. * decision is made according to the final-letters scores maintained and Both
  131. * model probers scores. The answer is returned in the form of the name of the
  132. * charset identified, either "windows-1255" or "ISO-8859-8".
  133. *
  134. */
  135. namespace UniversalDetector.Core
  136. {
  137. /// <summary>
  138. /// This prober doesn't actually recognize a language or a charset.
  139. /// It is a helper prober for the use of the Hebrew model probers
  140. /// </summary>
  141. public class HebrewProber : CharsetProber
  142. {
  143. // windows-1255 / ISO-8859-8 code points of interest
  144. private const byte FINAL_KAF = 0xEA;
  145. private const byte NORMAL_KAF = 0xEB;
  146. private const byte FINAL_MEM = 0xED;
  147. private const byte NORMAL_MEM = 0xEE;
  148. private const byte FINAL_NUN = 0xEF;
  149. private const byte NORMAL_NUN = 0xF0;
  150. private const byte FINAL_PE = 0xF3;
  151. private const byte NORMAL_PE = 0xF4;
  152. private const byte FINAL_TSADI = 0xF5;
  153. private const byte NORMAL_TSADI = 0xF6;
  154. // Minimum Visual vs Logical final letter score difference.
  155. // If the difference is below this, don't rely solely on the final letter score distance.
  156. private const int MIN_FINAL_CHAR_DISTANCE = 5;
  157. // Minimum Visual vs Logical model score difference.
  158. // If the difference is below this, don't rely at all on the model score distance.
  159. private const float MIN_MODEL_DISTANCE = 0.01f;
  160. protected const string VISUAL_HEBREW_NAME = "ISO-8859-8";
  161. protected const string LOGICAL_HEBREW_NAME = "windows-1255";
  162. // owned by the group prober.
  163. protected CharsetProber logicalProber, visualProber;
  164. protected int finalCharLogicalScore, finalCharVisualScore;
  165. // The two last bytes seen in the previous buffer.
  166. protected byte prev, beforePrev;
  167. public HebrewProber()
  168. {
  169. Reset();
  170. }
  171. public void SetModelProbers(CharsetProber logical, CharsetProber visual)
  172. {
  173. logicalProber = logical;
  174. visualProber = visual;
  175. }
  176. /**
  177. * Final letter analysis for logical-visual decision.
  178. * Look for evidence that the received buffer is either logical Hebrew or
  179. * visual Hebrew.
  180. * The following cases are checked:
  181. * 1) A word longer than 1 letter, ending with a final letter. This is an
  182. * indication that the text is laid out "naturally" since the final letter
  183. * really appears at the end. +1 for logical score.
  184. * 2) A word longer than 1 letter, ending with a Non-Final letter. In normal
  185. * Hebrew, words ending with Kaf, Mem, Nun, Pe or Tsadi, should not end with
  186. * the Non-Final form of that letter. Exceptions to this rule are mentioned
  187. * above in isNonFinal(). This is an indication that the text is laid out
  188. * backwards. +1 for visual score
  189. * 3) A word longer than 1 letter, starting with a final letter. Final letters
  190. * should not appear at the beginning of a word. This is an indication that
  191. * the text is laid out backwards. +1 for visual score.
  192. *
  193. * The visual score and logical score are accumulated throughout the text and
  194. * are finally checked against each other in GetCharSetName().
  195. * No checking for final letters in the middle of words is done since that case
  196. * is not an indication for either Logical or Visual text.
  197. *
  198. * The input buffer should not contain any white spaces that are not (' ')
  199. * or any low-ascii punctuation marks.
  200. */
  201. public override ProbingState HandleData(byte[] buf, int offset, int len)
  202. {
  203. // Both model probers say it's not them. No reason to continue.
  204. if (GetState() == ProbingState.NotMe)
  205. return ProbingState.NotMe;
  206. int max = offset + len;
  207. for (int i = offset; i < max; i++) {
  208. byte b = buf[i];
  209. // a word just ended
  210. if (b == 0x20) {
  211. // *(curPtr-2) was not a space so prev is not a 1 letter word
  212. if (beforePrev != 0x20) {
  213. // case (1) [-2:not space][-1:final letter][cur:space]
  214. if (IsFinal(prev))
  215. finalCharLogicalScore++;
  216. // case (2) [-2:not space][-1:Non-Final letter][cur:space]
  217. else if (IsNonFinal(prev))
  218. finalCharVisualScore++;
  219. }
  220. } else {
  221. // case (3) [-2:space][-1:final letter][cur:not space]
  222. if ((beforePrev == 0x20) && (IsFinal(prev)) && (b != ' '))
  223. ++finalCharVisualScore;
  224. }
  225. beforePrev = prev;
  226. prev = b;
  227. }
  228. // Forever detecting, till the end or until both model probers
  229. // return NotMe (handled above).
  230. return ProbingState.Detecting;
  231. }
  232. // Make the decision: is it Logical or Visual?
  233. public override string GetCharsetName()
  234. {
  235. // If the final letter score distance is dominant enough, rely on it.
  236. int finalsub = finalCharLogicalScore - finalCharVisualScore;
  237. if (finalsub >= MIN_FINAL_CHAR_DISTANCE)
  238. return LOGICAL_HEBREW_NAME;
  239. if (finalsub <= -(MIN_FINAL_CHAR_DISTANCE))
  240. return VISUAL_HEBREW_NAME;
  241. // It's not dominant enough, try to rely on the model scores instead.
  242. float modelsub = logicalProber.GetConfidence() - visualProber.GetConfidence();
  243. if (modelsub > MIN_MODEL_DISTANCE)
  244. return LOGICAL_HEBREW_NAME;
  245. if (modelsub < -(MIN_MODEL_DISTANCE))
  246. return VISUAL_HEBREW_NAME;
  247. // Still no good, back to final letter distance, maybe it'll save the day.
  248. if (finalsub < 0)
  249. return VISUAL_HEBREW_NAME;
  250. // (finalsub > 0 - Logical) or (don't know what to do) default to Logical.
  251. return LOGICAL_HEBREW_NAME;
  252. }
  253. public override void Reset()
  254. {
  255. finalCharLogicalScore = 0;
  256. finalCharVisualScore = 0;
  257. prev = 0x20;
  258. beforePrev = 0x20;
  259. }
  260. public override ProbingState GetState()
  261. {
  262. // Remain active as long as any of the model probers are active.
  263. if (logicalProber.GetState() == ProbingState.NotMe &&
  264. visualProber.GetState() == ProbingState.NotMe)
  265. return ProbingState.NotMe;
  266. return ProbingState.Detecting;
  267. }
  268. public override void DumpStatus()
  269. {
  270. //Console.WriteLine(" HEB: {0} - {1} [Logical-Visual score]", finalCharLogicalScore, finalCharVisualScore);
  271. }
  272. public override float GetConfidence()
  273. {
  274. return 0.0f;
  275. }
  276. protected static bool IsFinal(byte b)
  277. {
  278. return (b == FINAL_KAF || b == FINAL_MEM || b == FINAL_NUN
  279. || b == FINAL_PE || b == FINAL_TSADI);
  280. }
  281. protected static bool IsNonFinal(byte b)
  282. {
  283. // The normal Tsadi is not a good Non-Final letter due to words like
  284. // 'lechotet' (to chat) containing an apostrophe after the tsadi. This
  285. // apostrophe is converted to a space in FilterWithoutEnglishLetters causing
  286. // the Non-Final tsadi to appear at an end of a word even though this is not
  287. // the case in the original text.
  288. // The letters Pe and Kaf rarely display a related behavior of not being a
  289. // good Non-Final letter. Words like 'Pop', 'Winamp' and 'Mubarak' for
  290. // example legally end with a Non-Final Pe or Kaf. However, the benefit of
  291. // these letters as Non-Final letters outweighs the damage since these words
  292. // are quite rare.
  293. return (b == NORMAL_KAF || b == NORMAL_MEM || b == NORMAL_NUN
  294. || b == NORMAL_PE);
  295. }
  296. }
  297. }