utf8prober.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 . import constants
  28. from .charsetprober import CharSetProber
  29. from .codingstatemachine import CodingStateMachine
  30. from .mbcssm import UTF8SMModel
  31. ONE_CHAR_PROB = 0.5
  32. class UTF8Prober(CharSetProber):
  33. def __init__(self):
  34. CharSetProber.__init__(self)
  35. self._mCodingSM = CodingStateMachine(UTF8SMModel)
  36. self.reset()
  37. def reset(self):
  38. CharSetProber.reset(self)
  39. self._mCodingSM.reset()
  40. self._mNumOfMBChar = 0
  41. def get_charset_name(self):
  42. return "utf-8"
  43. def feed(self, aBuf):
  44. for c in aBuf:
  45. codingState = self._mCodingSM.next_state(c)
  46. if codingState == constants.eError:
  47. self._mState = constants.eNotMe
  48. break
  49. elif codingState == constants.eItsMe:
  50. self._mState = constants.eFoundIt
  51. break
  52. elif codingState == constants.eStart:
  53. if self._mCodingSM.get_current_charlen() >= 2:
  54. self._mNumOfMBChar += 1
  55. if self.get_state() == constants.eDetecting:
  56. if self.get_confidence() > constants.SHORTCUT_THRESHOLD:
  57. self._mState = constants.eFoundIt
  58. return self.get_state()
  59. def get_confidence(self):
  60. unlike = 0.99
  61. if self._mNumOfMBChar < 6:
  62. for i in range(0, self._mNumOfMBChar):
  63. unlike = unlike * ONE_CHAR_PROB
  64. return 1.0 - unlike
  65. else:
  66. return unlike