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# Netscape Communications Corporation.
6# Portions created by the Initial Developer are Copyright (C) 2001
7# the Initial Developer. All Rights Reserved.
8#
9# Contributor(s):
10# Mark Pilgrim - port to Python
11# Shy Shalom - original C code
12#
13# This library is free software; you can redistribute it and/or
14# modify it under the terms of the GNU Lesser General Public
15# License as published by the Free Software Foundation; either
16# version 2.1 of the License, or (at your option) any later version.
17#
18# This library is distributed in the hope that it will be useful,
19# but WITHOUT ANY WARRANTY; without even the implied warranty of
20# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21# Lesser General Public License for more details.
22#
23# You should have received a copy of the GNU Lesser General Public
24# License along with this library; if not, see
25# <https://www.gnu.org/licenses/>.
26######################### END LICENSE BLOCK #########################
27
28from typing import Dict, List, NamedTuple, Optional, Union
29
30from .charsetprober import CharSetProber
31from .enums import CharacterCategory, ProbingState, SequenceLikelihood
32
33
34class SingleByteCharSetModel(NamedTuple):
35 charset_name: str
36 language: str
37 char_to_order_map: Dict[int, int]
38 language_model: Dict[int, Dict[int, int]]
39 typical_positive_ratio: float
40 keep_ascii_letters: bool
41 alphabet: str
42
43
44class SingleByteCharSetProber(CharSetProber):
45 SAMPLE_SIZE = 64
46 SB_ENOUGH_REL_THRESHOLD = 1024 # 0.25 * SAMPLE_SIZE^2
47 POSITIVE_SHORTCUT_THRESHOLD = 0.95
48 NEGATIVE_SHORTCUT_THRESHOLD = 0.05
49
50 def __init__(
51 self,
52 model: SingleByteCharSetModel,
53 is_reversed: bool = False,
54 name_prober: Optional[CharSetProber] = None,
55 ) -> None:
56 super().__init__()
57 self._model = model
58 # TRUE if we need to reverse every pair in the model lookup
59 self._reversed = is_reversed
60 # Optional auxiliary prober for name decision
61 self._name_prober = name_prober
62 self._last_order = 255
63 self._seq_counters: List[int] = []
64 self._total_seqs = 0
65 self._total_char = 0
66 self._control_char = 0
67 self._freq_char = 0
68 self.reset()
69
70 def reset(self) -> None:
71 super().reset()
72 # char order of last character
73 self._last_order = 255
74 self._seq_counters = [0] * SequenceLikelihood.get_num_categories()
75 self._total_seqs = 0
76 self._total_char = 0
77 self._control_char = 0
78 # characters that fall in our sampling range
79 self._freq_char = 0
80
81 @property
82 def charset_name(self) -> Optional[str]:
83 if self._name_prober:
84 return self._name_prober.charset_name
85 return self._model.charset_name
86
87 @property
88 def language(self) -> Optional[str]:
89 if self._name_prober:
90 return self._name_prober.language
91 return self._model.language
92
93 def feed(self, byte_str: Union[bytes, bytearray]) -> ProbingState:
94 # TODO: Make filter_international_words keep things in self.alphabet
95 if not self._model.keep_ascii_letters:
96 byte_str = self.filter_international_words(byte_str)
97 else:
98 byte_str = self.remove_xml_tags(byte_str)
99 if not byte_str:
100 return self.state
101 char_to_order_map = self._model.char_to_order_map
102 language_model = self._model.language_model
103 for char in byte_str:
104 order = char_to_order_map.get(char, CharacterCategory.UNDEFINED)
105 # XXX: This was SYMBOL_CAT_ORDER before, with a value of 250, but
106 # CharacterCategory.SYMBOL is actually 253, so we use CONTROL
107 # to make it closer to the original intent. The only difference
108 # is whether or not we count digits and control characters for
109 # _total_char purposes.
110 if order < CharacterCategory.CONTROL:
111 self._total_char += 1
112 if order < self.SAMPLE_SIZE:
113 self._freq_char += 1
114 if self._last_order < self.SAMPLE_SIZE:
115 self._total_seqs += 1
116 if not self._reversed:
117 lm_cat = language_model[self._last_order][order]
118 else:
119 lm_cat = language_model[order][self._last_order]
120 self._seq_counters[lm_cat] += 1
121 self._last_order = order
122
123 charset_name = self._model.charset_name
124 if self.state == ProbingState.DETECTING:
125 if self._total_seqs > self.SB_ENOUGH_REL_THRESHOLD:
126 confidence = self.get_confidence()
127 if confidence > self.POSITIVE_SHORTCUT_THRESHOLD:
128 self.logger.debug(
129 "%s confidence = %s, we have a winner", charset_name, confidence
130 )
131 self._state = ProbingState.FOUND_IT
132 elif confidence < self.NEGATIVE_SHORTCUT_THRESHOLD:
133 self.logger.debug(
134 "%s confidence = %s, below negative shortcut threshold %s",
135 charset_name,
136 confidence,
137 self.NEGATIVE_SHORTCUT_THRESHOLD,
138 )
139 self._state = ProbingState.NOT_ME
140
141 return self.state
142
143 def get_confidence(self) -> float:
144 r = 0.01
145 if self._total_seqs > 0:
146 r = (
147 (
148 self._seq_counters[SequenceLikelihood.POSITIVE]
149 + 0.25 * self._seq_counters[SequenceLikelihood.LIKELY]
150 )
151 / self._total_seqs
152 / self._model.typical_positive_ratio
153 )
154 # The more control characters (proportionnaly to the size
155 # of the text), the less confident we become in the current
156 # charset.
157 r = r * (self._total_char - self._control_char) / self._total_char
158 r = r * self._freq_char / self._total_char
159 if r >= 1.0:
160 r = 0.99
161 return r