1
0

utf8prober.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. ######################## BEGIN LICENSE BLOCK ########################
  2. # The Original Code is mozilla.org 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 .charsetprober import CharSetProber
  28. from .enums import ProbingState, MachineState
  29. from .codingstatemachine import CodingStateMachine
  30. from .mbcssm import UTF8_SM_MODEL
  31. class UTF8Prober(CharSetProber):
  32. ONE_CHAR_PROB = 0.5
  33. def __init__(self):
  34. super(UTF8Prober, self).__init__()
  35. self.coding_sm = CodingStateMachine(UTF8_SM_MODEL)
  36. self._num_mb_chars = None
  37. self.reset()
  38. def reset(self):
  39. super(UTF8Prober, self).reset()
  40. self.coding_sm.reset()
  41. self._num_mb_chars = 0
  42. @property
  43. def charset_name(self):
  44. return "utf-8"
  45. @property
  46. def language(self):
  47. return ""
  48. def feed(self, byte_str):
  49. for c in byte_str:
  50. coding_state = self.coding_sm.next_state(c)
  51. if coding_state == MachineState.ERROR:
  52. self._state = ProbingState.NOT_ME
  53. break
  54. elif coding_state == MachineState.ITS_ME:
  55. self._state = ProbingState.FOUND_IT
  56. break
  57. elif coding_state == MachineState.START:
  58. if self.coding_sm.get_current_charlen() >= 2:
  59. self._num_mb_chars += 1
  60. if self.state == ProbingState.DETECTING:
  61. if self.get_confidence() > self.SHORTCUT_THRESHOLD:
  62. self._state = ProbingState.FOUND_IT
  63. return self.state
  64. def get_confidence(self):
  65. unlike = 0.99
  66. if self._num_mb_chars < 6:
  67. unlike *= self.ONE_CHAR_PROB ** self._num_mb_chars
  68. return 1.0 - unlike
  69. else:
  70. return unlike