chardistribution.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. ######################## BEGIN LICENSE BLOCK ########################
  2. # The Original Code is Mozilla Communicator client code.
  3. #
  4. # The Initial Developer of the Original Code is
  5. # Netscape Communications Corporation.
  6. # Portions created by the Initial Developer are Copyright (C) 1998
  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 Tuple, Union
  28. from .big5freq import (
  29. BIG5_CHAR_TO_FREQ_ORDER,
  30. BIG5_TABLE_SIZE,
  31. BIG5_TYPICAL_DISTRIBUTION_RATIO,
  32. )
  33. from .euckrfreq import (
  34. EUCKR_CHAR_TO_FREQ_ORDER,
  35. EUCKR_TABLE_SIZE,
  36. EUCKR_TYPICAL_DISTRIBUTION_RATIO,
  37. )
  38. from .euctwfreq import (
  39. EUCTW_CHAR_TO_FREQ_ORDER,
  40. EUCTW_TABLE_SIZE,
  41. EUCTW_TYPICAL_DISTRIBUTION_RATIO,
  42. )
  43. from .gb2312freq import (
  44. GB2312_CHAR_TO_FREQ_ORDER,
  45. GB2312_TABLE_SIZE,
  46. GB2312_TYPICAL_DISTRIBUTION_RATIO,
  47. )
  48. from .jisfreq import (
  49. JIS_CHAR_TO_FREQ_ORDER,
  50. JIS_TABLE_SIZE,
  51. JIS_TYPICAL_DISTRIBUTION_RATIO,
  52. )
  53. from .johabfreq import JOHAB_TO_EUCKR_ORDER_TABLE
  54. class CharDistributionAnalysis:
  55. ENOUGH_DATA_THRESHOLD = 1024
  56. SURE_YES = 0.99
  57. SURE_NO = 0.01
  58. MINIMUM_DATA_THRESHOLD = 3
  59. def __init__(self) -> None:
  60. # Mapping table to get frequency order from char order (get from
  61. # GetOrder())
  62. self._char_to_freq_order: Tuple[int, ...] = tuple()
  63. self._table_size = 0 # Size of above table
  64. # This is a constant value which varies from language to language,
  65. # used in calculating confidence. See
  66. # http://www.mozilla.org/projects/intl/UniversalCharsetDetection.html
  67. # for further detail.
  68. self.typical_distribution_ratio = 0.0
  69. self._done = False
  70. self._total_chars = 0
  71. self._freq_chars = 0
  72. self.reset()
  73. def reset(self) -> None:
  74. """reset analyser, clear any state"""
  75. # If this flag is set to True, detection is done and conclusion has
  76. # been made
  77. self._done = False
  78. self._total_chars = 0 # Total characters encountered
  79. # The number of characters whose frequency order is less than 512
  80. self._freq_chars = 0
  81. def feed(self, char: Union[bytes, bytearray], char_len: int) -> None:
  82. """feed a character with known length"""
  83. if char_len == 2:
  84. # we only care about 2-bytes character in our distribution analysis
  85. order = self.get_order(char)
  86. else:
  87. order = -1
  88. if order >= 0:
  89. self._total_chars += 1
  90. # order is valid
  91. if order < self._table_size:
  92. if 512 > self._char_to_freq_order[order]:
  93. self._freq_chars += 1
  94. def get_confidence(self) -> float:
  95. """return confidence based on existing data"""
  96. # if we didn't receive any character in our consideration range,
  97. # return negative answer
  98. if self._total_chars <= 0 or self._freq_chars <= self.MINIMUM_DATA_THRESHOLD:
  99. return self.SURE_NO
  100. if self._total_chars != self._freq_chars:
  101. r = self._freq_chars / (
  102. (self._total_chars - self._freq_chars) * self.typical_distribution_ratio
  103. )
  104. if r < self.SURE_YES:
  105. return r
  106. # normalize confidence (we don't want to be 100% sure)
  107. return self.SURE_YES
  108. def got_enough_data(self) -> bool:
  109. # It is not necessary to receive all data to draw conclusion.
  110. # For charset detection, certain amount of data is enough
  111. return self._total_chars > self.ENOUGH_DATA_THRESHOLD
  112. def get_order(self, _: Union[bytes, bytearray]) -> int:
  113. # We do not handle characters based on the original encoding string,
  114. # but convert this encoding string to a number, here called order.
  115. # This allows multiple encodings of a language to share one frequency
  116. # table.
  117. return -1
  118. class EUCTWDistributionAnalysis(CharDistributionAnalysis):
  119. def __init__(self) -> None:
  120. super().__init__()
  121. self._char_to_freq_order = EUCTW_CHAR_TO_FREQ_ORDER
  122. self._table_size = EUCTW_TABLE_SIZE
  123. self.typical_distribution_ratio = EUCTW_TYPICAL_DISTRIBUTION_RATIO
  124. def get_order(self, byte_str: Union[bytes, bytearray]) -> int:
  125. # for euc-TW encoding, we are interested
  126. # first byte range: 0xc4 -- 0xfe
  127. # second byte range: 0xa1 -- 0xfe
  128. # no validation needed here. State machine has done that
  129. first_char = byte_str[0]
  130. if first_char >= 0xC4:
  131. return 94 * (first_char - 0xC4) + byte_str[1] - 0xA1
  132. return -1
  133. class EUCKRDistributionAnalysis(CharDistributionAnalysis):
  134. def __init__(self) -> None:
  135. super().__init__()
  136. self._char_to_freq_order = EUCKR_CHAR_TO_FREQ_ORDER
  137. self._table_size = EUCKR_TABLE_SIZE
  138. self.typical_distribution_ratio = EUCKR_TYPICAL_DISTRIBUTION_RATIO
  139. def get_order(self, byte_str: Union[bytes, bytearray]) -> int:
  140. # for euc-KR encoding, we are interested
  141. # first byte range: 0xb0 -- 0xfe
  142. # second byte range: 0xa1 -- 0xfe
  143. # no validation needed here. State machine has done that
  144. first_char = byte_str[0]
  145. if first_char >= 0xB0:
  146. return 94 * (first_char - 0xB0) + byte_str[1] - 0xA1
  147. return -1
  148. class JOHABDistributionAnalysis(CharDistributionAnalysis):
  149. def __init__(self) -> None:
  150. super().__init__()
  151. self._char_to_freq_order = EUCKR_CHAR_TO_FREQ_ORDER
  152. self._table_size = EUCKR_TABLE_SIZE
  153. self.typical_distribution_ratio = EUCKR_TYPICAL_DISTRIBUTION_RATIO
  154. def get_order(self, byte_str: Union[bytes, bytearray]) -> int:
  155. first_char = byte_str[0]
  156. if 0x88 <= first_char < 0xD4:
  157. code = first_char * 256 + byte_str[1]
  158. return JOHAB_TO_EUCKR_ORDER_TABLE.get(code, -1)
  159. return -1
  160. class GB2312DistributionAnalysis(CharDistributionAnalysis):
  161. def __init__(self) -> None:
  162. super().__init__()
  163. self._char_to_freq_order = GB2312_CHAR_TO_FREQ_ORDER
  164. self._table_size = GB2312_TABLE_SIZE
  165. self.typical_distribution_ratio = GB2312_TYPICAL_DISTRIBUTION_RATIO
  166. def get_order(self, byte_str: Union[bytes, bytearray]) -> int:
  167. # for GB2312 encoding, we are interested
  168. # first byte range: 0xb0 -- 0xfe
  169. # second byte range: 0xa1 -- 0xfe
  170. # no validation needed here. State machine has done that
  171. first_char, second_char = byte_str[0], byte_str[1]
  172. if (first_char >= 0xB0) and (second_char >= 0xA1):
  173. return 94 * (first_char - 0xB0) + second_char - 0xA1
  174. return -1
  175. class Big5DistributionAnalysis(CharDistributionAnalysis):
  176. def __init__(self) -> None:
  177. super().__init__()
  178. self._char_to_freq_order = BIG5_CHAR_TO_FREQ_ORDER
  179. self._table_size = BIG5_TABLE_SIZE
  180. self.typical_distribution_ratio = BIG5_TYPICAL_DISTRIBUTION_RATIO
  181. def get_order(self, byte_str: Union[bytes, bytearray]) -> int:
  182. # for big5 encoding, we are interested
  183. # first byte range: 0xa4 -- 0xfe
  184. # second byte range: 0x40 -- 0x7e , 0xa1 -- 0xfe
  185. # no validation needed here. State machine has done that
  186. first_char, second_char = byte_str[0], byte_str[1]
  187. if first_char >= 0xA4:
  188. if second_char >= 0xA1:
  189. return 157 * (first_char - 0xA4) + second_char - 0xA1 + 63
  190. return 157 * (first_char - 0xA4) + second_char - 0x40
  191. return -1
  192. class SJISDistributionAnalysis(CharDistributionAnalysis):
  193. def __init__(self) -> None:
  194. super().__init__()
  195. self._char_to_freq_order = JIS_CHAR_TO_FREQ_ORDER
  196. self._table_size = JIS_TABLE_SIZE
  197. self.typical_distribution_ratio = JIS_TYPICAL_DISTRIBUTION_RATIO
  198. def get_order(self, byte_str: Union[bytes, bytearray]) -> int:
  199. # for sjis encoding, we are interested
  200. # first byte range: 0x81 -- 0x9f , 0xe0 -- 0xfe
  201. # second byte range: 0x40 -- 0x7e, 0x81 -- oxfe
  202. # no validation needed here. State machine has done that
  203. first_char, second_char = byte_str[0], byte_str[1]
  204. if 0x81 <= first_char <= 0x9F:
  205. order = 188 * (first_char - 0x81)
  206. elif 0xE0 <= first_char <= 0xEF:
  207. order = 188 * (first_char - 0xE0 + 31)
  208. else:
  209. return -1
  210. order = order + second_char - 0x40
  211. if second_char > 0x7F:
  212. order = -1
  213. return order
  214. class EUCJPDistributionAnalysis(CharDistributionAnalysis):
  215. def __init__(self) -> None:
  216. super().__init__()
  217. self._char_to_freq_order = JIS_CHAR_TO_FREQ_ORDER
  218. self._table_size = JIS_TABLE_SIZE
  219. self.typical_distribution_ratio = JIS_TYPICAL_DISTRIBUTION_RATIO
  220. def get_order(self, byte_str: Union[bytes, bytearray]) -> int:
  221. # for euc-JP encoding, we are interested
  222. # first byte range: 0xa0 -- 0xfe
  223. # second byte range: 0xa1 -- 0xfe
  224. # no validation needed here. State machine has done that
  225. char = byte_str[0]
  226. if char >= 0xA0:
  227. return 94 * (char - 0xA1) + byte_str[1] - 0xA1
  228. return -1