ooggss commited on
Commit ·
f0f4f2b
1
Parent(s): 20b61db
initial
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+2
- Dataset_Construction/__pycache__/generation.cpython-312.pycAdded
- Dataset_Construction/__pycache__/generation.cpython-38.pycAdded
- Dataset_Construction/extract_function.pyAdded+174
- Dataset_Construction/generation.pyAdded+4
- Dataset_Construction/match_function_throughBm25.pyAdded+104
- Dataset_Construction/match_function_throughLLM.pyAdded+70
- Dataset_Construction/projects/charset-normalizer/python/__init__.pyAdded+46
- Dataset_Construction/projects/charset-normalizer/python/__main__.pyAdded+4
- Dataset_Construction/projects/charset-normalizer/python/api.pyAdded+626
- Dataset_Construction/projects/charset-normalizer/python/cd.pyAdded+395
- Dataset_Construction/projects/charset-normalizer/python/cli/__init__.pyAdded+6
- Dataset_Construction/projects/charset-normalizer/python/cli/__main__.pyAdded+296
- Dataset_Construction/projects/charset-normalizer/python/constant.pyAdded+1995
- Dataset_Construction/projects/charset-normalizer/python/legacy.pyAdded+65
- Dataset_Construction/projects/charset-normalizer/python/md.pyAdded+615
- Dataset_Construction/projects/charset-normalizer/python/models.pyAdded+338
- Dataset_Construction/projects/charset-normalizer/python/py.typedAdded
- Dataset_Construction/projects/charset-normalizer/python/utils.pyAdded+421
- Dataset_Construction/projects/charset-normalizer/python/version.pyAdded+6
- Dataset_Construction/projects/charset-normalizer/rust/CODE_OF_CONDUCT.mdAdded+76
- Dataset_Construction/projects/charset-normalizer/rust/CONTRIBUTING.mdAdded+73
- Dataset_Construction/projects/charset-normalizer/rust/Cargo.lockAdded+1795
- Dataset_Construction/projects/charset-normalizer/rust/Cargo.tomlAdded+70
- Dataset_Construction/projects/charset-normalizer/rust/LICENSEAdded+22
- Dataset_Construction/projects/charset-normalizer/rust/README.mdAdded+199
- Dataset_Construction/projects/charset-normalizer/rust/benches/large_datasets.rsAdded+31
- Dataset_Construction/projects/charset-normalizer/rust/benches/large_payload.rsAdded+18
- Dataset_Construction/projects/charset-normalizer/rust/rust-toolchain.tomlAdded+2
- Dataset_Construction/projects/charset-normalizer/rust/src/assets.rsAdded+66
- Dataset_Construction/projects/charset-normalizer/rust/src/cd.rsAdded+252
- Dataset_Construction/projects/charset-normalizer/rust/src/consts.rsAdded+752
- Dataset_Construction/projects/charset-normalizer/rust/src/entity.rsAdded+518
- Dataset_Construction/projects/charset-normalizer/rust/src/lib.rsAdded+597
- Dataset_Construction/projects/charset-normalizer/rust/src/md.rsAdded+82
- Dataset_Construction/projects/charset-normalizer/rust/src/md/plugins.rsAdded+448
- Dataset_Construction/projects/charset-normalizer/rust/src/md/structs.rsAdded+197
- Dataset_Construction/projects/charset-normalizer/rust/src/normalizer.rsAdded+171
- Dataset_Construction/projects/charset-normalizer/rust/src/performance.rsAdded+219
- Dataset_Construction/projects/charset-normalizer/rust/src/tests/cd.rsAdded+195
- Dataset_Construction/projects/charset-normalizer/rust/src/tests/data/largesets/None/sample-1.gifAdded
- Dataset_Construction/projects/charset-normalizer/rust/src/tests/data/largesets/None/sample-1.jpgAdded
- Dataset_Construction/projects/charset-normalizer/rust/src/tests/data/largesets/None/sample-1.mp4Added+3
- Dataset_Construction/projects/charset-normalizer/rust/src/tests/data/largesets/None/sample-1.pngAdded
- Dataset_Construction/projects/charset-normalizer/rust/src/tests/data/largesets/None/sample-1.webpAdded
- Dataset_Construction/projects/charset-normalizer/rust/src/tests/data/largesets/None/sample-1.xlsxAdded
- Dataset_Construction/projects/charset-normalizer/rust/src/tests/data/largesets/None/sample-2.pngAdded
- Dataset_Construction/projects/charset-normalizer/rust/src/tests/data/largesets/None/sample-3.pngAdded
- Dataset_Construction/projects/charset-normalizer/rust/src/tests/data/largesets/ascii/CHANGELOG.mdAdded+200
- Dataset_Construction/projects/charset-normalizer/rust/src/tests/data/largesets/ascii/_chromium_iso-8859-1_with_no_encoding_specified.htmlAdded+10
56 unmodified lines575859606156 unmodified lines# Video files - compressed*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -text*.json filter=lfs diff=lfs merge=lfs -text*.csv filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174import re
import os
import sys
total_functions = set()
def extract_functions_from_code(code, pattern):
function_head_pattern = re.compile(pattern)
lines = code.split('\n')
functions = []
brace_count = 0
function_code = []
inside_function = False
key = False
for i, line in enumerate(lines):
if not inside_function and function_head_pattern.search(line):
inside_function = True
if inside_function:
function_code.append(line)
if not line.lstrip(" ").startswith("//"):
brace_count += line.count('{')
brace_count -= line.count('}')
if brace_count == 0 :
if line.strip().endswith('}'):
inside_function = False
functions.append('\n'.join(function_code))
function_code = []
elif line.strip().endswith(';'):
inside_function = False
function_code = []
return functions
def extract_functions_from_code_py(code):
lines = code.split('\n')
functions = []
function_code = []
inside_function = False
for line in lines:
if not inside_function and line.lstrip().startswith("def "):
# 获取函数起始的缩进长度
pre_cnt = len(line) - len(line.lstrip())
function_code.append(line)
inside_function = True
# 跳过def那一行
continue
if inside_function:
# 空行和缩进比def要小表示还在函数内
if len(line) == 0 or len(line) - len(line.lstrip()) >= pre_cnt + 4:
function_code.append(line)
else:
functions.append('\n'.join(function_code))
function_code = []
# 当前行有可能是下一个函数的声明行,不处理会跳过该函数
if line.lstrip().startswith("def "):
pre_cnt = len(line) - len(line.lstrip())
function_code.append(line)
else:
inside_function = False
# 处理在文件末尾声明定义的function
if function_code:
functions.append('\n'.join(function_code))
return functions
def extract_functions_from_code_rb(code):
lines = code.split('\n')
functions = []
function_code = []
inside_function = False
for line in lines:
if not inside_function and line.lstrip().startswith("def "):
# 获取函数起始的缩进长度
pre_cnt = len(line) - len(line.lstrip())
function_code.append(line)
inside_function = True
# 跳过def那一行
continue
if inside_function:
if len(line) - len(line.lstrip()) == pre_cnt and line.lstrip().startswith("end"):
inside_function = False
functions.append('\n'.join(function_code))
function_code = []
else:
function_code.append(line)
return functions
def save_functions_to_files(functions, output_dir, output_file_name):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
try:
for i, func in enumerate(functions):
# influxdb-1.8\\client\\influxdb_test.go -> influxdb-1.8__client__influxdb_test
output_file = os.path.splitext(output_file_name)
output_file = output_file[0].replace("/", "__") + "__" + output_file[1]
file_path = os.path.join(output_dir, f'{output_file}__function__{i + 1}.txt')
with open(file_path, 'w', encoding='utf-8') as file:
file.write(f"<path>\n{output_file_name}\n</path>\n")
file.write(f"<function>\n{func}\n</function>")
except Exception as e:
print(e)
pass
def process_file(input_file, lang, output_dir, pattern):
with open(input_file, 'r', encoding='utf-8', errors='ignore') as file:
code = file.read()
if lang == "py":
functions = extract_functions_from_code_py(code)
elif lang == "rb":
functions = extract_functions_from_code_rb(code)
else:
functions = extract_functions_from_code(code, pattern)
save_functions_to_files(functions, output_dir, input_file)
def main():
project_dir = "projects"
target_project = sys.argv[1]
patterns = {
'cpp': r'^\s*[\w\s\*\[\]\<\>\:]+\s+[\w\s\*\[\]\<\>\:]+\s*\(',
'cxx': r'^\s*[\w\s\*\[\]\<\>\:]+\s+[\w\s\*\[\]\<\>\:]+\s*\(',
'h': r'^\s*[\w\s\*\[\]\<\>\:]+\s+[\w\s\*\[\]\<\>\:]+\s*\(',
'java': r'^\s*(public|protected|private|static|final|synchronized|native|abstract|strictfp|default)?\s*(public|protected|private|static|final|synchronized|native|abstract|strictfp|default)?\s*[\w\<\>\[\] ]+\s+[\w\<\>\[\]]+\s*\(',
'rs': r'^\s*(unsafe)?\s*(pub(\(crate\))?)?\s*(async)?\s*fn\s',
'c': r'^\s*[\w\s\*\[\]]*\s*\w+\s*\(',
'py': r''
}
lang_to_fileType = {
'cpp' : ['cpp', 'cxx', 'h'],
'c' : ['c', 'h'],
'java' : ['java'],
'rust' : ['rs'],
'python' : ['py']
}
projects = os.listdir(project_dir)
for project in projects:
if project != target_project:
continue
project_pair_path = os.path.join(project_dir, project)
langs = os.listdir(project_pair_path)
for lang in langs:
root_dir = os.path.join(project_pair_path, lang)
# 对项目进行遍历
for current_path, dirs, files in os.walk(root_dir):
dirs[:] = [d for d in dirs if not d.startswith('.')]
for file in files:
try :
file_lang = file.split('.')[-1]
except:
continue
if file_lang in lang_to_fileType[lang]:
file_path = os.path.join(current_path, file)
if "test" in file_path or "Test" in file_path:
continue
process_file(file_path, file_lang, root_dir.replace("projects", "functions"), patterns[file_lang])
if __name__ == '__main__':
main()1234
def generation(message): # todo : complete the generation function with target LLM return None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104from rank_bm25 import BM25Plusimport osimport sysimport refrom nltk.corpus import stopwordsfrom nltk.stem import PorterStemmer, WordNetLemmatizer
def read_corpus(corpus_files_path): corpus = []
corpus_files = os.listdir(corpus_files_path) for corpus_file in corpus_files: with open(os.path.join(corpus_files_path, corpus_file), 'r') as input_file: tmp = input_file.read()
corpus.append(tmp) return corpus
def normalize_text(text): # 大小写归一化 text = text.lower() # 分词 words = re.findall(r'\w+|[^\s\w]+', text) # 去除停用词 stop_words = set(stopwords.words('english')) words = [word for word in words if word not in stop_words] # 词干提取 stemmer = PorterStemmer() words = [stemmer.stem(word) for word in words] # 词形还原 lemmatizer = WordNetLemmatizer() words = [lemmatizer.lemmatize(word) for word in words] return words
# 使用正则表达式进行分词def tokenize_code(code): # 使用归一化 return normalize_text(code)
def main(): corpus_files_path = "functions" query_files_path = "functions_with_unitTest" match_results_path = "potential_function_pair"
project = sys.argv[1] corpus_lang = sys.argv[2] query_lang = sys.argv[3]
corpus_files_path = os.path.join(corpus_files_path, project, corpus_lang) query_files_path = os.path.join(query_files_path, project, query_lang) match_results_path = os.path.join(match_results_path, project, f"{query_lang}__{corpus_lang}") query_files = os.listdir(query_files_path)
# 获取匹配池子 corpus = read_corpus(corpus_files_path) tokenized_corpus = [tokenize_code(doc) for doc in corpus] bm25 = BM25Plus(tokenized_corpus)
# 获取请求 for query_file in query_files: with open(os.path.join(query_files_path, query_file), 'r') as input_file: query = input_file.read()
# 对于每个请求计算前n个匹配结果 # 放大函数名的权重 tokenized_query = tokenize_code(query) # 获取相关性评分 scores = bm25.get_scores(tokenized_query) # 获取最相关的前几个函数定义 top_n = 10 match_results_index = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True)[:top_n]
# 如果文件夹不存在,则创建它 if not os.path.exists(match_results_path): os.makedirs(match_results_path) # 记录匹配结果 with open(os.path.join(match_results_path, query_file), 'w') as output_file: output_file.write("<Target function>\n") output_file.write(query) output_file.write("\n</Target function>\n\n") # for match_result in match_results: # output_file.write(match_result) # output_file.write("\n") output_file.write("<Possible matching functions>\n") i = 1 for index in match_results_index: output_file.write("<Function {}> \n{}\n</Function {}>\n\n".format(i, corpus[index], i)) # output_file.write("Score: {}\n".format(scores[index])) i += 1 output_file.write("</Possible matching functions>\n")
if __name__ == "__main__" : main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970import os
import logging
import time
import sys
from generation import generation
source_dir = sys.argv[1]
target_dir = sys.argv[2]
project = sys.argv[3]
# 设置日志配置
logging.basicConfig(filename=f"match_function_throughLLM_{project}.log", level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def process(projects_path, project, target_dir):
lang_pairs = os.listdir(projects_path)
for lang_pair in lang_pairs:
# print(lang_pair)
if not os.path.exists(os.path.join(target_dir, project, lang_pair)):
os.makedirs(os.path.join(target_dir, project, lang_pair))
query_lang = lang_pair.split("__")[0]
corpus_lang = lang_pair.split("__")[1]
questions_path = os.listdir(os.path.join(projects_path, lang_pair))
for question_path in questions_path:
if os.path.exists(os.path.join(target_dir, project, lang_pair, question_path)):
logging.info(f"{lang_pair}'s {question_path} already exist")
continue
# match
with open(os.path.join(projects_path, lang_pair, question_path), 'r', encoding='utf-8') as input_file:
question = input_file.read()
query_func = question[len("<Target function>\n"):question.find("</Target function>")]
while True:
try:
# match function
message = f"You are a professional who is expert in programming language {query_lang} and programming language {corpus_lang}. You will be provided with 1 Target function written in {query_lang} and 10 Possible matching functions written in {corpus_lang}(delimited with XML tags).Please select a function that has the same functionality as the Target function from 10 Possible matching functions.You should only response the serial number of the matching function or \"None\" if it doesn't exit.\n{question}"
response = generation(message)
# print(f"successfully get {question_path}")
with open(os.path.join(target_dir, project, lang_pair, question_path), 'w', encoding='utf-8', errors='ignore') as output_file:
# match
if response == "None":
output_file.write("None")
else:
start = question.find(f"<Function {response}>") + len(f"<Function {response}>\n")
end = question.find(f"</Function {response}>")
output_file.write(query_func)
output_file.write("------\n")
output_file.write(question[start:end])
break
except Exception as e:
logging.error(f"error with {lang_pair} {question_path}, detail is: {e}")
print(f"error with {lang_pair} {question_path}, detail is: {e}")
time.sleep(10)
break
if __name__ == "__main__":
projects_path = os.path.join(source_dir, project) # 替换为实际的文件路径
process(projects_path, project, target_dir)12345678910111213141516171819202122232425262728293031323334353637383940414243444546# -*- coding: utf-8 -*-"""Charset-Normalizer~~~~~~~~~~~~~~The Real First Universal Charset Detector.A library that helps you read text from an unknown charset encoding.Motivated by chardet, This package is trying to resolve the issue by taking a new approach.All IANA character set names for which the Python core library provides codecs are supported.
Basic usage: >>> from charset_normalizer import from_bytes >>> results = from_bytes('Bсеки човек има право на образование. Oбразованието!'.encode('utf_8')) >>> best_guess = results.best() >>> str(best_guess) 'Bсеки човек има право на образование. Oбразованието!'
Others methods and usages are available - see the full documentationat <https://github.com/Ousret/charset_normalizer>.:copyright: (c) 2021 by Ahmed TAHRI:license: MIT, see LICENSE for more details."""import logging
from .api import from_bytes, from_fp, from_path, is_binaryfrom .legacy import detectfrom .models import CharsetMatch, CharsetMatchesfrom .utils import set_logging_handlerfrom .version import VERSION, __version__
__all__ = ( "from_fp", "from_path", "from_bytes", "is_binary", "detect", "CharsetMatch", "CharsetMatches", "__version__", "VERSION", "set_logging_handler",)
# Attach a NullHandler to the top level logger by default# https://docs.python.org/3.3/howto/logging.html#configuring-logging-for-a-library
logging.getLogger("charset_normalizer").addHandler(logging.NullHandler())1234from .cli import cli_detect
if __name__ == "__main__": cli_detect()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626import loggingfrom os import PathLikefrom typing import BinaryIO, List, Optional, Set, Union
from .cd import ( coherence_ratio, encoding_languages, mb_encoding_languages, merge_coherence_ratios,)from .constant import IANA_SUPPORTED, TOO_BIG_SEQUENCE, TOO_SMALL_SEQUENCE, TRACEfrom .md import mess_ratiofrom .models import CharsetMatch, CharsetMatchesfrom .utils import ( any_specified_encoding, cut_sequence_chunks, iana_name, identify_sig_or_bom, is_cp_similar, is_multi_byte_encoding, should_strip_sig_or_bom,)
# Will most likely be controversial# logging.addLevelName(TRACE, "TRACE")logger = logging.getLogger("charset_normalizer")explain_handler = logging.StreamHandler()explain_handler.setFormatter( logging.Formatter("%(asctime)s | %(levelname)s | %(message)s"))
def from_bytes( sequences: Union[bytes, bytearray], steps: int = 5, chunk_size: int = 512, threshold: float = 0.2, cp_isolation: Optional[List[str]] = None, cp_exclusion: Optional[List[str]] = None, preemptive_behaviour: bool = True, explain: bool = False, language_threshold: float = 0.1, enable_fallback: bool = True,) -> CharsetMatches: """ Given a raw bytes sequence, return the best possibles charset usable to render str objects. If there is no results, it is a strong indicator that the source is binary/not text. By default, the process will extract 5 blocks of 512o each to assess the mess and coherence of a given sequence. And will give up a particular code page after 20% of measured mess. Those criteria are customizable at will.
The preemptive behavior DOES NOT replace the traditional detection workflow, it prioritize a particular code page but never take it for granted. Can improve the performance.
You may want to focus your attention to some code page or/and not others, use cp_isolation and cp_exclusion for that purpose.
This function will strip the SIG in the payload/sequence every time except on UTF-16, UTF-32. By default the library does not setup any handler other than the NullHandler, if you choose to set the 'explain' toggle to True it will alter the logger configuration to add a StreamHandler that is suitable for debugging. Custom logging format and handler can be set manually. """
if not isinstance(sequences, (bytearray, bytes)): raise TypeError( "Expected object of type bytes or bytearray, got: {0}".format( type(sequences) ) )
if explain: previous_logger_level: int = logger.level logger.addHandler(explain_handler) logger.setLevel(TRACE)
length: int = len(sequences)
if length == 0: logger.debug("Encoding detection on empty bytes, assuming utf_8 intention.") if explain: logger.removeHandler(explain_handler) logger.setLevel(previous_logger_level or logging.WARNING) return CharsetMatches([CharsetMatch(sequences, "utf_8", 0.0, False, [], "")])
if cp_isolation is not None: logger.log( TRACE, "cp_isolation is set. use this flag for debugging purpose. " "limited list of encoding allowed : %s.", ", ".join(cp_isolation), ) cp_isolation = [iana_name(cp, False) for cp in cp_isolation] else: cp_isolation = []
if cp_exclusion is not None: logger.log( TRACE, "cp_exclusion is set. use this flag for debugging purpose. " "limited list of encoding excluded : %s.", ", ".join(cp_exclusion), ) cp_exclusion = [iana_name(cp, False) for cp in cp_exclusion] else: cp_exclusion = []
if length <= (chunk_size * steps): logger.log( TRACE, "override steps (%i) and chunk_size (%i) as content does not fit (%i byte(s) given) parameters.", steps, chunk_size, length, ) steps = 1 chunk_size = length
if steps > 1 and length / steps < chunk_size: chunk_size = int(length / steps)
is_too_small_sequence: bool = len(sequences) < TOO_SMALL_SEQUENCE is_too_large_sequence: bool = len(sequences) >= TOO_BIG_SEQUENCE
if is_too_small_sequence: logger.log( TRACE, "Trying to detect encoding from a tiny portion of ({}) byte(s).".format( length ), ) elif is_too_large_sequence: logger.log( TRACE, "Using lazy str decoding because the payload is quite large, ({}) byte(s).".format( length ), )
prioritized_encodings: List[str] = []
specified_encoding: Optional[str] = ( any_specified_encoding(sequences) if preemptive_behaviour else None )
if specified_encoding is not None: prioritized_encodings.append(specified_encoding) logger.log( TRACE, "Detected declarative mark in sequence. Priority +1 given for %s.", specified_encoding, )
tested: Set[str] = set() tested_but_hard_failure: List[str] = [] tested_but_soft_failure: List[str] = []
fallback_ascii: Optional[CharsetMatch] = None fallback_u8: Optional[CharsetMatch] = None fallback_specified: Optional[CharsetMatch] = None
results: CharsetMatches = CharsetMatches()
sig_encoding, sig_payload = identify_sig_or_bom(sequences)
if sig_encoding is not None: prioritized_encodings.append(sig_encoding) logger.log( TRACE, "Detected a SIG or BOM mark on first %i byte(s). Priority +1 given for %s.", len(sig_payload), sig_encoding, )
prioritized_encodings.append("ascii")
if "utf_8" not in prioritized_encodings: prioritized_encodings.append("utf_8")
for encoding_iana in prioritized_encodings + IANA_SUPPORTED: if cp_isolation and encoding_iana not in cp_isolation: continue
if cp_exclusion and encoding_iana in cp_exclusion: continue
if encoding_iana in tested: continue
tested.add(encoding_iana)
decoded_payload: Optional[str] = None bom_or_sig_available: bool = sig_encoding == encoding_iana strip_sig_or_bom: bool = bom_or_sig_available and should_strip_sig_or_bom( encoding_iana )
if encoding_iana in {"utf_16", "utf_32"} and not bom_or_sig_available: logger.log( TRACE, "Encoding %s won't be tested as-is because it require a BOM. Will try some sub-encoder LE/BE.", encoding_iana, ) continue if encoding_iana in {"utf_7"} and not bom_or_sig_available: logger.log( TRACE, "Encoding %s won't be tested as-is because detection is unreliable without BOM/SIG.", encoding_iana, ) continue
try: is_multi_byte_decoder: bool = is_multi_byte_encoding(encoding_iana) except (ModuleNotFoundError, ImportError): logger.log( TRACE, "Encoding %s does not provide an IncrementalDecoder", encoding_iana, ) continue
try: if is_too_large_sequence and is_multi_byte_decoder is False: str( sequences[: int(50e4)] if strip_sig_or_bom is False else sequences[len(sig_payload) : int(50e4)], encoding=encoding_iana, ) else: decoded_payload = str( sequences if strip_sig_or_bom is False else sequences[len(sig_payload) :], encoding=encoding_iana, ) except (UnicodeDecodeError, LookupError) as e: if not isinstance(e, LookupError): logger.log( TRACE, "Code page %s does not fit given bytes sequence at ALL. %s", encoding_iana, str(e), ) tested_but_hard_failure.append(encoding_iana) continue
similar_soft_failure_test: bool = False
for encoding_soft_failed in tested_but_soft_failure: if is_cp_similar(encoding_iana, encoding_soft_failed): similar_soft_failure_test = True break
if similar_soft_failure_test: logger.log( TRACE, "%s is deemed too similar to code page %s and was consider unsuited already. Continuing!", encoding_iana, encoding_soft_failed, ) continue
r_ = range( 0 if not bom_or_sig_available else len(sig_payload), length, int(length / steps), )
multi_byte_bonus: bool = ( is_multi_byte_decoder and decoded_payload is not None and len(decoded_payload) < length )
if multi_byte_bonus: logger.log( TRACE, "Code page %s is a multi byte encoding table and it appear that at least one character " "was encoded using n-bytes.", encoding_iana, )
max_chunk_gave_up: int = int(len(r_) / 4)
max_chunk_gave_up = max(max_chunk_gave_up, 2) early_stop_count: int = 0 lazy_str_hard_failure = False
md_chunks: List[str] = [] md_ratios = []
try: for chunk in cut_sequence_chunks( sequences, encoding_iana, r_, chunk_size, bom_or_sig_available, strip_sig_or_bom, sig_payload, is_multi_byte_decoder, decoded_payload, ): md_chunks.append(chunk)
md_ratios.append( mess_ratio( chunk, threshold, explain is True and 1 <= len(cp_isolation) <= 2, ) )
if md_ratios[-1] >= threshold: early_stop_count += 1
if (early_stop_count >= max_chunk_gave_up) or ( bom_or_sig_available and strip_sig_or_bom is False ): break except ( UnicodeDecodeError ) as e: # Lazy str loading may have missed something there logger.log( TRACE, "LazyStr Loading: After MD chunk decode, code page %s does not fit given bytes sequence at ALL. %s", encoding_iana, str(e), ) early_stop_count = max_chunk_gave_up lazy_str_hard_failure = True
# We might want to check the sequence again with the whole content # Only if initial MD tests passes if ( not lazy_str_hard_failure and is_too_large_sequence and not is_multi_byte_decoder ): try: sequences[int(50e3) :].decode(encoding_iana, errors="strict") except UnicodeDecodeError as e: logger.log( TRACE, "LazyStr Loading: After final lookup, code page %s does not fit given bytes sequence at ALL. %s", encoding_iana, str(e), ) tested_but_hard_failure.append(encoding_iana) continue
mean_mess_ratio: float = sum(md_ratios) / len(md_ratios) if md_ratios else 0.0 if mean_mess_ratio >= threshold or early_stop_count >= max_chunk_gave_up: tested_but_soft_failure.append(encoding_iana) logger.log( TRACE, "%s was excluded because of initial chaos probing. Gave up %i time(s). " "Computed mean chaos is %f %%.", encoding_iana, early_stop_count, round(mean_mess_ratio * 100, ndigits=3), ) # Preparing those fallbacks in case we got nothing. if ( enable_fallback and encoding_iana in ["ascii", "utf_8", specified_encoding] and not lazy_str_hard_failure ): fallback_entry = CharsetMatch( sequences, encoding_iana, threshold, False, [], decoded_payload ) if encoding_iana == specified_encoding: fallback_specified = fallback_entry elif encoding_iana == "ascii": fallback_ascii = fallback_entry else: fallback_u8 = fallback_entry continue
logger.log( TRACE, "%s passed initial chaos probing. Mean measured chaos is %f %%", encoding_iana, round(mean_mess_ratio * 100, ndigits=3), )
if not is_multi_byte_decoder: target_languages: List[str] = encoding_languages(encoding_iana) else: target_languages = mb_encoding_languages(encoding_iana)
if target_languages: logger.log( TRACE, "{} should target any language(s) of {}".format( encoding_iana, str(target_languages) ), )
cd_ratios = []
# We shall skip the CD when its about ASCII # Most of the time its not relevant to run "language-detection" on it. if encoding_iana != "ascii": for chunk in md_chunks: chunk_languages = coherence_ratio( chunk, language_threshold, ",".join(target_languages) if target_languages else None, )
cd_ratios.append(chunk_languages)
cd_ratios_merged = merge_coherence_ratios(cd_ratios)
if cd_ratios_merged: logger.log( TRACE, "We detected language {} using {}".format( cd_ratios_merged, encoding_iana ), )
results.append( CharsetMatch( sequences, encoding_iana, mean_mess_ratio, bom_or_sig_available, cd_ratios_merged, decoded_payload, ) )
if ( encoding_iana in [specified_encoding, "ascii", "utf_8"] and mean_mess_ratio < 0.1 ): logger.debug( "Encoding detection: %s is most likely the one.", encoding_iana ) if explain: logger.removeHandler(explain_handler) logger.setLevel(previous_logger_level) return CharsetMatches([results[encoding_iana]])
if encoding_iana == sig_encoding: logger.debug( "Encoding detection: %s is most likely the one as we detected a BOM or SIG within " "the beginning of the sequence.", encoding_iana, ) if explain: logger.removeHandler(explain_handler) logger.setLevel(previous_logger_level) return CharsetMatches([results[encoding_iana]])
if len(results) == 0: if fallback_u8 or fallback_ascii or fallback_specified: logger.log( TRACE, "Nothing got out of the detection process. Using ASCII/UTF-8/Specified fallback.", )
if fallback_specified: logger.debug( "Encoding detection: %s will be used as a fallback match", fallback_specified.encoding, ) results.append(fallback_specified) elif ( (fallback_u8 and fallback_ascii is None) or ( fallback_u8 and fallback_ascii and fallback_u8.fingerprint != fallback_ascii.fingerprint ) or (fallback_u8 is not None) ): logger.debug("Encoding detection: utf_8 will be used as a fallback match") results.append(fallback_u8) elif fallback_ascii: logger.debug("Encoding detection: ascii will be used as a fallback match") results.append(fallback_ascii)
if results: logger.debug( "Encoding detection: Found %s as plausible (best-candidate) for content. With %i alternatives.", results.best().encoding, # type: ignore len(results) - 1, ) else: logger.debug("Encoding detection: Unable to determine any suitable charset.")
if explain: logger.removeHandler(explain_handler) logger.setLevel(previous_logger_level)
return results
def from_fp( fp: BinaryIO, steps: int = 5, chunk_size: int = 512, threshold: float = 0.20, cp_isolation: Optional[List[str]] = None, cp_exclusion: Optional[List[str]] = None, preemptive_behaviour: bool = True, explain: bool = False, language_threshold: float = 0.1, enable_fallback: bool = True,) -> CharsetMatches: """ Same thing than the function from_bytes but using a file pointer that is already ready. Will not close the file pointer. """ return from_bytes( fp.read(), steps, chunk_size, threshold, cp_isolation, cp_exclusion, preemptive_behaviour, explain, language_threshold, enable_fallback, )
def from_path( path: Union[str, bytes, PathLike], # type: ignore[type-arg] steps: int = 5, chunk_size: int = 512, threshold: float = 0.20, cp_isolation: Optional[List[str]] = None, cp_exclusion: Optional[List[str]] = None, preemptive_behaviour: bool = True, explain: bool = False, language_threshold: float = 0.1, enable_fallback: bool = True,) -> CharsetMatches: """ Same thing than the function from_bytes but with one extra step. Opening and reading given file path in binary mode. Can raise IOError. """ with open(path, "rb") as fp: return from_fp( fp, steps, chunk_size, threshold, cp_isolation, cp_exclusion, preemptive_behaviour, explain, language_threshold, enable_fallback, )
def is_binary( fp_or_path_or_payload: Union[PathLike, str, BinaryIO, bytes], # type: ignore[type-arg] steps: int = 5, chunk_size: int = 512, threshold: float = 0.20, cp_isolation: Optional[List[str]] = None, cp_exclusion: Optional[List[str]] = None, preemptive_behaviour: bool = True, explain: bool = False, language_threshold: float = 0.1, enable_fallback: bool = False,) -> bool: """ Detect if the given input (file, bytes, or path) points to a binary file. aka. not a string. Based on the same main heuristic algorithms and default kwargs at the sole exception that fallbacks match are disabled to be stricter around ASCII-compatible but unlikely to be a string. """ if isinstance(fp_or_path_or_payload, (str, PathLike)): guesses = from_path( fp_or_path_or_payload, steps=steps, chunk_size=chunk_size, threshold=threshold, cp_isolation=cp_isolation, cp_exclusion=cp_exclusion, preemptive_behaviour=preemptive_behaviour, explain=explain, language_threshold=language_threshold, enable_fallback=enable_fallback, ) elif isinstance( fp_or_path_or_payload, ( bytes, bytearray, ), ): guesses = from_bytes( fp_or_path_or_payload, steps=steps, chunk_size=chunk_size, threshold=threshold, cp_isolation=cp_isolation, cp_exclusion=cp_exclusion, preemptive_behaviour=preemptive_behaviour, explain=explain, language_threshold=language_threshold, enable_fallback=enable_fallback, ) else: guesses = from_fp( fp_or_path_or_payload, steps=steps, chunk_size=chunk_size, threshold=threshold, cp_isolation=cp_isolation, cp_exclusion=cp_exclusion, preemptive_behaviour=preemptive_behaviour, explain=explain, language_threshold=language_threshold, enable_fallback=enable_fallback, )
return not guesses123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395import importlibfrom codecs import IncrementalDecoderfrom collections import Counterfrom functools import lru_cachefrom typing import Counter as TypeCounter, Dict, List, Optional, Tuple
from .constant import ( FREQUENCIES, KO_NAMES, LANGUAGE_SUPPORTED_COUNT, TOO_SMALL_SEQUENCE, ZH_NAMES,)from .md import is_suspiciously_successive_rangefrom .models import CoherenceMatchesfrom .utils import ( is_accentuated, is_latin, is_multi_byte_encoding, is_unicode_range_secondary, unicode_range,)
def encoding_unicode_range(iana_name: str) -> List[str]: """ Return associated unicode ranges in a single byte code page. """ if is_multi_byte_encoding(iana_name): raise IOError("Function not supported on multi-byte code page")
decoder = importlib.import_module( "encodings.{}".format(iana_name) ).IncrementalDecoder
p: IncrementalDecoder = decoder(errors="ignore") seen_ranges: Dict[str, int] = {} character_count: int = 0
for i in range(0x40, 0xFF): chunk: str = p.decode(bytes([i]))
if chunk: character_range: Optional[str] = unicode_range(chunk)
if character_range is None: continue
if is_unicode_range_secondary(character_range) is False: if character_range not in seen_ranges: seen_ranges[character_range] = 0 seen_ranges[character_range] += 1 character_count += 1
return sorted( [ character_range for character_range in seen_ranges if seen_ranges[character_range] / character_count >= 0.15 ] )
def unicode_range_languages(primary_range: str) -> List[str]: """ Return inferred languages used with a unicode range. """ languages: List[str] = []
for language, characters in FREQUENCIES.items(): for character in characters: if unicode_range(character) == primary_range: languages.append(language) break
return languages
@lru_cache()def encoding_languages(iana_name: str) -> List[str]: """ Single-byte encoding language association. Some code page are heavily linked to particular language(s). This function does the correspondence. """ unicode_ranges: List[str] = encoding_unicode_range(iana_name) primary_range: Optional[str] = None
for specified_range in unicode_ranges: if "Latin" not in specified_range: primary_range = specified_range break
if primary_range is None: return ["Latin Based"]
return unicode_range_languages(primary_range)
@lru_cache()def mb_encoding_languages(iana_name: str) -> List[str]: """ Multi-byte encoding language association. Some code page are heavily linked to particular language(s). This function does the correspondence. """ if ( iana_name.startswith("shift_") or iana_name.startswith("iso2022_jp") or iana_name.startswith("euc_j") or iana_name == "cp932" ): return ["Japanese"] if iana_name.startswith("gb") or iana_name in ZH_NAMES: return ["Chinese"] if iana_name.startswith("iso2022_kr") or iana_name in KO_NAMES: return ["Korean"]
return []
@lru_cache(maxsize=LANGUAGE_SUPPORTED_COUNT)def get_target_features(language: str) -> Tuple[bool, bool]: """ Determine main aspects from a supported language if it contains accents and if is pure Latin. """ target_have_accents: bool = False target_pure_latin: bool = True
for character in FREQUENCIES[language]: if not target_have_accents and is_accentuated(character): target_have_accents = True if target_pure_latin and is_latin(character) is False: target_pure_latin = False
return target_have_accents, target_pure_latin
def alphabet_languages( characters: List[str], ignore_non_latin: bool = False) -> List[str]: """ Return associated languages associated to given characters. """ languages: List[Tuple[str, float]] = []
source_have_accents = any(is_accentuated(character) for character in characters)
for language, language_characters in FREQUENCIES.items(): target_have_accents, target_pure_latin = get_target_features(language)
if ignore_non_latin and target_pure_latin is False: continue
if target_have_accents is False and source_have_accents: continue
character_count: int = len(language_characters)
character_match_count: int = len( [c for c in language_characters if c in characters] )
ratio: float = character_match_count / character_count
if ratio >= 0.2: languages.append((language, ratio))
languages = sorted(languages, key=lambda x: x[1], reverse=True)
return [compatible_language[0] for compatible_language in languages]
def characters_popularity_compare( language: str, ordered_characters: List[str]) -> float: """ Determine if a ordered characters list (by occurrence from most appearance to rarest) match a particular language. The result is a ratio between 0. (absolutely no correspondence) and 1. (near perfect fit). Beware that is function is not strict on the match in order to ease the detection. (Meaning close match is 1.) """ if language not in FREQUENCIES: raise ValueError("{} not available".format(language))
character_approved_count: int = 0 FREQUENCIES_language_set = set(FREQUENCIES[language])
ordered_characters_count: int = len(ordered_characters) target_language_characters_count: int = len(FREQUENCIES[language])
large_alphabet: bool = target_language_characters_count > 26
for character, character_rank in zip( ordered_characters, range(0, ordered_characters_count) ): if character not in FREQUENCIES_language_set: continue
character_rank_in_language: int = FREQUENCIES[language].index(character) expected_projection_ratio: float = ( target_language_characters_count / ordered_characters_count ) character_rank_projection: int = int(character_rank * expected_projection_ratio)
if ( large_alphabet is False and abs(character_rank_projection - character_rank_in_language) > 4 ): continue
if ( large_alphabet is True and abs(character_rank_projection - character_rank_in_language) < target_language_characters_count / 3 ): character_approved_count += 1 continue
characters_before_source: List[str] = FREQUENCIES[language][ 0:character_rank_in_language ] characters_after_source: List[str] = FREQUENCIES[language][ character_rank_in_language: ] characters_before: List[str] = ordered_characters[0:character_rank] characters_after: List[str] = ordered_characters[character_rank:]
before_match_count: int = len( set(characters_before) & set(characters_before_source) )
after_match_count: int = len( set(characters_after) & set(characters_after_source) )
if len(characters_before_source) == 0 and before_match_count <= 4: character_approved_count += 1 continue
if len(characters_after_source) == 0 and after_match_count <= 4: character_approved_count += 1 continue
if ( before_match_count / len(characters_before_source) >= 0.4 or after_match_count / len(characters_after_source) >= 0.4 ): character_approved_count += 1 continue
return character_approved_count / len(ordered_characters)
def alpha_unicode_split(decoded_sequence: str) -> List[str]: """ Given a decoded text sequence, return a list of str. Unicode range / alphabet separation. Ex. a text containing English/Latin with a bit a Hebrew will return two items in the resulting list; One containing the latin letters and the other hebrew. """ layers: Dict[str, str] = {}
for character in decoded_sequence: if character.isalpha() is False: continue
character_range: Optional[str] = unicode_range(character)
if character_range is None: continue
layer_target_range: Optional[str] = None
for discovered_range in layers: if ( is_suspiciously_successive_range(discovered_range, character_range) is False ): layer_target_range = discovered_range break
if layer_target_range is None: layer_target_range = character_range
if layer_target_range not in layers: layers[layer_target_range] = character.lower() continue
layers[layer_target_range] += character.lower()
return list(layers.values())
def merge_coherence_ratios(results: List[CoherenceMatches]) -> CoherenceMatches: """ This function merge results previously given by the function coherence_ratio. The return type is the same as coherence_ratio. """ per_language_ratios: Dict[str, List[float]] = {} for result in results: for sub_result in result: language, ratio = sub_result if language not in per_language_ratios: per_language_ratios[language] = [ratio] continue per_language_ratios[language].append(ratio)
merge = [ ( language, round( sum(per_language_ratios[language]) / len(per_language_ratios[language]), 4, ), ) for language in per_language_ratios ]
return sorted(merge, key=lambda x: x[1], reverse=True)
def filter_alt_coherence_matches(results: CoherenceMatches) -> CoherenceMatches: """ We shall NOT return "English—" in CoherenceMatches because it is an alternative of "English". This function only keeps the best match and remove the em-dash in it. """ index_results: Dict[str, List[float]] = dict()
for result in results: language, ratio = result no_em_name: str = language.replace("—", "")
if no_em_name not in index_results: index_results[no_em_name] = []
index_results[no_em_name].append(ratio)
if any(len(index_results[e]) > 1 for e in index_results): filtered_results: CoherenceMatches = []
for language in index_results: filtered_results.append((language, max(index_results[language])))
return filtered_results
return results
@lru_cache(maxsize=2048)def coherence_ratio( decoded_sequence: str, threshold: float = 0.1, lg_inclusion: Optional[str] = None) -> CoherenceMatches: """ Detect ANY language that can be identified in given sequence. The sequence will be analysed by layers. A layer = Character extraction by alphabets/ranges. """
results: List[Tuple[str, float]] = [] ignore_non_latin: bool = False
sufficient_match_count: int = 0
lg_inclusion_list = lg_inclusion.split(",") if lg_inclusion is not None else [] if "Latin Based" in lg_inclusion_list: ignore_non_latin = True lg_inclusion_list.remove("Latin Based")
for layer in alpha_unicode_split(decoded_sequence): sequence_frequencies: TypeCounter[str] = Counter(layer) most_common = sequence_frequencies.most_common()
character_count: int = sum(o for c, o in most_common)
if character_count <= TOO_SMALL_SEQUENCE: continue
popular_character_ordered: List[str] = [c for c, o in most_common]
for language in lg_inclusion_list or alphabet_languages( popular_character_ordered, ignore_non_latin ): ratio: float = characters_popularity_compare( language, popular_character_ordered )
if ratio < threshold: continue elif ratio >= 0.8: sufficient_match_count += 1
results.append((language, round(ratio, 4)))
if sufficient_match_count >= 3: break
return sorted( filter_alt_coherence_matches(results), key=lambda x: x[1], reverse=True )123456from .__main__ import cli_detect, query_yes_no
__all__ = ( "cli_detect", "query_yes_no",)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296import argparseimport sysfrom json import dumpsfrom os.path import abspath, basename, dirname, join, realpathfrom platform import python_versionfrom typing import List, Optionalfrom unicodedata import unidata_version
import charset_normalizer.md as md_modulefrom charset_normalizer import from_fpfrom charset_normalizer.models import CliDetectionResultfrom charset_normalizer.version import __version__
def query_yes_no(question: str, default: str = "yes") -> bool: """Ask a yes/no question via input() and return their answer.
"question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "no" or None (meaning an answer is required of the user).
The "answer" return value is True for "yes" or False for "no".
Credit goes to (c) https://stackoverflow.com/questions/3041986/apt-command-line-interface-like-yes-no-input """ valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} if default is None: prompt = " [y/n] " elif default == "yes": prompt = " [Y/n] " elif default == "no": prompt = " [y/N] " else: raise ValueError("invalid default answer: '%s'" % default)
while True: sys.stdout.write(question + prompt) choice = input().lower() if default is not None and choice == "": return valid[default] elif choice in valid: return valid[choice] else: sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n")
def cli_detect(argv: Optional[List[str]] = None) -> int: """ CLI assistant using ARGV and ArgumentParser :param argv: :return: 0 if everything is fine, anything else equal trouble """ parser = argparse.ArgumentParser( description="The Real First Universal Charset Detector. " "Discover originating encoding used on text file. " "Normalize text to unicode." )
parser.add_argument( "files", type=argparse.FileType("rb"), nargs="+", help="File(s) to be analysed" ) parser.add_argument( "-v", "--verbose", action="store_true", default=False, dest="verbose", help="Display complementary information about file if any. " "Stdout will contain logs about the detection process.", ) parser.add_argument( "-a", "--with-alternative", action="store_true", default=False, dest="alternatives", help="Output complementary possibilities if any. Top-level JSON WILL be a list.", ) parser.add_argument( "-n", "--normalize", action="store_true", default=False, dest="normalize", help="Permit to normalize input file. If not set, program does not write anything.", ) parser.add_argument( "-m", "--minimal", action="store_true", default=False, dest="minimal", help="Only output the charset detected to STDOUT. Disabling JSON output.", ) parser.add_argument( "-r", "--replace", action="store_true", default=False, dest="replace", help="Replace file when trying to normalize it instead of creating a new one.", ) parser.add_argument( "-f", "--force", action="store_true", default=False, dest="force", help="Replace file without asking if you are sure, use this flag with caution.", ) parser.add_argument( "-t", "--threshold", action="store", default=0.2, type=float, dest="threshold", help="Define a custom maximum amount of chaos allowed in decoded content. 0. <= chaos <= 1.", ) parser.add_argument( "--version", action="version", version="Charset-Normalizer {} - Python {} - Unicode {} - SpeedUp {}".format( __version__, python_version(), unidata_version, "OFF" if md_module.__file__.lower().endswith(".py") else "ON", ), help="Show version information and exit.", )
args = parser.parse_args(argv)
if args.replace is True and args.normalize is False: print("Use --replace in addition of --normalize only.", file=sys.stderr) return 1
if args.force is True and args.replace is False: print("Use --force in addition of --replace only.", file=sys.stderr) return 1
if args.threshold < 0.0 or args.threshold > 1.0: print("--threshold VALUE should be between 0. AND 1.", file=sys.stderr) return 1
x_ = []
for my_file in args.files: matches = from_fp(my_file, threshold=args.threshold, explain=args.verbose)
best_guess = matches.best()
if best_guess is None: print( 'Unable to identify originating encoding for "{}". {}'.format( my_file.name, "Maybe try increasing maximum amount of chaos." if args.threshold < 1.0 else "", ), file=sys.stderr, ) x_.append( CliDetectionResult( abspath(my_file.name), None, [], [], "Unknown", [], False, 1.0, 0.0, None, True, ) ) else: x_.append( CliDetectionResult( abspath(my_file.name), best_guess.encoding, best_guess.encoding_aliases, [ cp for cp in best_guess.could_be_from_charset if cp != best_guess.encoding ], best_guess.language, best_guess.alphabets, best_guess.bom, best_guess.percent_chaos, best_guess.percent_coherence, None, True, ) )
if len(matches) > 1 and args.alternatives: for el in matches: if el != best_guess: x_.append( CliDetectionResult( abspath(my_file.name), el.encoding, el.encoding_aliases, [ cp for cp in el.could_be_from_charset if cp != el.encoding ], el.language, el.alphabets, el.bom, el.percent_chaos, el.percent_coherence, None, False, ) )
if args.normalize is True: if best_guess.encoding.startswith("utf") is True: print( '"{}" file does not need to be normalized, as it already came from unicode.'.format( my_file.name ), file=sys.stderr, ) if my_file.closed is False: my_file.close() continue
dir_path = dirname(realpath(my_file.name)) file_name = basename(realpath(my_file.name))
o_: List[str] = file_name.split(".")
if args.replace is False: o_.insert(-1, best_guess.encoding) if my_file.closed is False: my_file.close() elif ( args.force is False and query_yes_no( 'Are you sure to normalize "{}" by replacing it ?'.format( my_file.name ), "no", ) is False ): if my_file.closed is False: my_file.close() continue
try: x_[0].unicode_path = join(dir_path, ".".join(o_))
with open(x_[0].unicode_path, "w", encoding="utf-8") as fp: fp.write(str(best_guess)) except IOError as e: print(str(e), file=sys.stderr) if my_file.closed is False: my_file.close() return 2
if my_file.closed is False: my_file.close()
if args.minimal is False: print( dumps( [el.__dict__ for el in x_] if len(x_) > 1 else x_[0].__dict__, ensure_ascii=True, indent=4, ) ) else: for my_file in args.files: print( ", ".join( [ el.encoding or "undefined" for el in x_ if el.path == abspath(my_file.name) ] ) )
return 0
if __name__ == "__main__": cli_detect()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995# -*- coding: utf-8 -*-from codecs import BOM_UTF8, BOM_UTF16_BE, BOM_UTF16_LE, BOM_UTF32_BE, BOM_UTF32_LEfrom encodings.aliases import aliasesfrom re import IGNORECASE, compile as re_compilefrom typing import Dict, List, Set, Union
# Contain for each eligible encoding a list of/item bytes SIG/BOMENCODING_MARKS: Dict[str, Union[bytes, List[bytes]]] = { "utf_8": BOM_UTF8, "utf_7": [ b"\x2b\x2f\x76\x38", b"\x2b\x2f\x76\x39", b"\x2b\x2f\x76\x2b", b"\x2b\x2f\x76\x2f", b"\x2b\x2f\x76\x38\x2d", ], "gb18030": b"\x84\x31\x95\x33", "utf_32": [BOM_UTF32_BE, BOM_UTF32_LE], "utf_16": [BOM_UTF16_BE, BOM_UTF16_LE],}
TOO_SMALL_SEQUENCE: int = 32TOO_BIG_SEQUENCE: int = int(10e6)
UTF8_MAXIMAL_ALLOCATION: int = 1_112_064
# Up-to-date Unicode ucd/15.0.0UNICODE_RANGES_COMBINED: Dict[str, range] = { "Control character": range(32), "Basic Latin": range(32, 128), "Latin-1 Supplement": range(128, 256), "Latin Extended-A": range(256, 384), "Latin Extended-B": range(384, 592), "IPA Extensions": range(592, 688), "Spacing Modifier Letters": range(688, 768), "Combining Diacritical Marks": range(768, 880), "Greek and Coptic": range(880, 1024), "Cyrillic": range(1024, 1280), "Cyrillic Supplement": range(1280, 1328), "Armenian": range(1328, 1424), "Hebrew": range(1424, 1536), "Arabic": range(1536, 1792), "Syriac": range(1792, 1872), "Arabic Supplement": range(1872, 1920), "Thaana": range(1920, 1984), "NKo": range(1984, 2048), "Samaritan": range(2048, 2112), "Mandaic": range(2112, 2144), "Syriac Supplement": range(2144, 2160), "Arabic Extended-B": range(2160, 2208), "Arabic Extended-A": range(2208, 2304), "Devanagari": range(2304, 2432), "Bengali": range(2432, 2560), "Gurmukhi": range(2560, 2688), "Gujarati": range(2688, 2816), "Oriya": range(2816, 2944), "Tamil": range(2944, 3072), "Telugu": range(3072, 3200), "Kannada": range(3200, 3328), "Malayalam": range(3328, 3456), "Sinhala": range(3456, 3584), "Thai": range(3584, 3712), "Lao": range(3712, 3840), "Tibetan": range(3840, 4096), "Myanmar": range(4096, 4256), "Georgian": range(4256, 4352), "Hangul Jamo": range(4352, 4608), "Ethiopic": range(4608, 4992), "Ethiopic Supplement": range(4992, 5024), "Cherokee": range(5024, 5120), "Unified Canadian Aboriginal Syllabics": range(5120, 5760), "Ogham": range(5760, 5792), "Runic": range(5792, 5888), "Tagalog": range(5888, 5920), "Hanunoo": range(5920, 5952), "Buhid": range(5952, 5984), "Tagbanwa": range(5984, 6016), "Khmer": range(6016, 6144), "Mongolian": range(6144, 6320), "Unified Canadian Aboriginal Syllabics Extended": range(6320, 6400), "Limbu": range(6400, 6480), "Tai Le": range(6480, 6528), "New Tai Lue": range(6528, 6624), "Khmer Symbols": range(6624, 6656), "Buginese": range(6656, 6688), "Tai Tham": range(6688, 6832), "Combining Diacritical Marks Extended": range(6832, 6912), "Balinese": range(6912, 7040), "Sundanese": range(7040, 7104), "Batak": range(7104, 7168), "Lepcha": range(7168, 7248), "Ol Chiki": range(7248, 7296), "Cyrillic Extended-C": range(7296, 7312), "Georgian Extended": range(7312, 7360), "Sundanese Supplement": range(7360, 7376), "Vedic Extensions": range(7376, 7424), "Phonetic Extensions": range(7424, 7552), "Phonetic Extensions Supplement": range(7552, 7616), "Combining Diacritical Marks Supplement": range(7616, 7680), "Latin Extended Additional": range(7680, 7936), "Greek Extended": range(7936, 8192), "General Punctuation": range(8192, 8304), "Superscripts and Subscripts": range(8304, 8352), "Currency Symbols": range(8352, 8400), "Combining Diacritical Marks for Symbols": range(8400, 8448), "Letterlike Symbols": range(8448, 8528), "Number Forms": range(8528, 8592), "Arrows": range(8592, 8704), "Mathematical Operators": range(8704, 8960), "Miscellaneous Technical": range(8960, 9216), "Control Pictures": range(9216, 9280), "Optical Character Recognition": range(9280, 9312), "Enclosed Alphanumerics": range(9312, 9472), "Box Drawing": range(9472, 9600), "Block Elements": range(9600, 9632), "Geometric Shapes": range(9632, 9728), "Miscellaneous Symbols": range(9728, 9984), "Dingbats": range(9984, 10176), "Miscellaneous Mathematical Symbols-A": range(10176, 10224), "Supplemental Arrows-A": range(10224, 10240), "Braille Patterns": range(10240, 10496), "Supplemental Arrows-B": range(10496, 10624), "Miscellaneous Mathematical Symbols-B": range(10624, 10752), "Supplemental Mathematical Operators": range(10752, 11008), "Miscellaneous Symbols and Arrows": range(11008, 11264), "Glagolitic": range(11264, 11360), "Latin Extended-C": range(11360, 11392), "Coptic": range(11392, 11520), "Georgian Supplement": range(11520, 11568), "Tifinagh": range(11568, 11648), "Ethiopic Extended": range(11648, 11744), "Cyrillic Extended-A": range(11744, 11776), "Supplemental Punctuation": range(11776, 11904), "CJK Radicals Supplement": range(11904, 12032), "Kangxi Radicals": range(12032, 12256), "Ideographic Description Characters": range(12272, 12288), "CJK Symbols and Punctuation": range(12288, 12352), "Hiragana": range(12352, 12448), "Katakana": range(12448, 12544), "Bopomofo": range(12544, 12592), "Hangul Compatibility Jamo": range(12592, 12688), "Kanbun": range(12688, 12704), "Bopomofo Extended": range(12704, 12736), "CJK Strokes": range(12736, 12784), "Katakana Phonetic Extensions": range(12784, 12800), "Enclosed CJK Letters and Months": range(12800, 13056), "CJK Compatibility": range(13056, 13312), "CJK Unified Ideographs Extension A": range(13312, 19904), "Yijing Hexagram Symbols": range(19904, 19968), "CJK Unified Ideographs": range(19968, 40960), "Yi Syllables": range(40960, 42128), "Yi Radicals": range(42128, 42192), "Lisu": range(42192, 42240), "Vai": range(42240, 42560), "Cyrillic Extended-B": range(42560, 42656), "Bamum": range(42656, 42752), "Modifier Tone Letters": range(42752, 42784), "Latin Extended-D": range(42784, 43008), "Syloti Nagri": range(43008, 43056), "Common Indic Number Forms": range(43056, 43072), "Phags-pa": range(43072, 43136), "Saurashtra": range(43136, 43232), "Devanagari Extended": range(43232, 43264), "Kayah Li": range(43264, 43312), "Rejang": range(43312, 43360), "Hangul Jamo Extended-A": range(43360, 43392), "Javanese": range(43392, 43488), "Myanmar Extended-B": range(43488, 43520), "Cham": range(43520, 43616), "Myanmar Extended-A": range(43616, 43648), "Tai Viet": range(43648, 43744), "Meetei Mayek Extensions": range(43744, 43776), "Ethiopic Extended-A": range(43776, 43824), "Latin Extended-E": range(43824, 43888), "Cherokee Supplement": range(43888, 43968), "Meetei Mayek": range(43968, 44032), "Hangul Syllables": range(44032, 55216), "Hangul Jamo Extended-B": range(55216, 55296), "High Surrogates": range(55296, 56192), "High Private Use Surrogates": range(56192, 56320), "Low Surrogates": range(56320, 57344), "Private Use Area": range(57344, 63744), "CJK Compatibility Ideographs": range(63744, 64256), "Alphabetic Presentation Forms": range(64256, 64336), "Arabic Presentation Forms-A": range(64336, 65024), "Variation Selectors": range(65024, 65040), "Vertical Forms": range(65040, 65056), "Combining Half Marks": range(65056, 65072), "CJK Compatibility Forms": range(65072, 65104), "Small Form Variants": range(65104, 65136), "Arabic Presentation Forms-B": range(65136, 65280), "Halfwidth and Fullwidth Forms": range(65280, 65520), "Specials": range(65520, 65536), "Linear B Syllabary": range(65536, 65664), "Linear B Ideograms": range(65664, 65792), "Aegean Numbers": range(65792, 65856), "Ancient Greek Numbers": range(65856, 65936), "Ancient Symbols": range(65936, 66000), "Phaistos Disc": range(66000, 66048), "Lycian": range(66176, 66208), "Carian": range(66208, 66272), "Coptic Epact Numbers": range(66272, 66304), "Old Italic": range(66304, 66352), "Gothic": range(66352, 66384), "Old Permic": range(66384, 66432), "Ugaritic": range(66432, 66464), "Old Persian": range(66464, 66528), "Deseret": range(66560, 66640), "Shavian": range(66640, 66688), "Osmanya": range(66688, 66736), "Osage": range(66736, 66816), "Elbasan": range(66816, 66864), "Caucasian Albanian": range(66864, 66928), "Vithkuqi": range(66928, 67008), "Linear A": range(67072, 67456), "Latin Extended-F": range(67456, 67520), "Cypriot Syllabary": range(67584, 67648), "Imperial Aramaic": range(67648, 67680), "Palmyrene": range(67680, 67712), "Nabataean": range(67712, 67760), "Hatran": range(67808, 67840), "Phoenician": range(67840, 67872), "Lydian": range(67872, 67904), "Meroitic Hieroglyphs": range(67968, 68000), "Meroitic Cursive": range(68000, 68096), "Kharoshthi": range(68096, 68192), "Old South Arabian": range(68192, 68224), "Old North Arabian": range(68224, 68256), "Manichaean": range(68288, 68352), "Avestan": range(68352, 68416), "Inscriptional Parthian": range(68416, 68448), "Inscriptional Pahlavi": range(68448, 68480), "Psalter Pahlavi": range(68480, 68528), "Old Turkic": range(68608, 68688), "Old Hungarian": range(68736, 68864), "Hanifi Rohingya": range(68864, 68928), "Rumi Numeral Symbols": range(69216, 69248), "Yezidi": range(69248, 69312), "Arabic Extended-C": range(69312, 69376), "Old Sogdian": range(69376, 69424), "Sogdian": range(69424, 69488), "Old Uyghur": range(69488, 69552), "Chorasmian": range(69552, 69600), "Elymaic": range(69600, 69632), "Brahmi": range(69632, 69760), "Kaithi": range(69760, 69840), "Sora Sompeng": range(69840, 69888), "Chakma": range(69888, 69968), "Mahajani": range(69968, 70016), "Sharada": range(70016, 70112), "Sinhala Archaic Numbers": range(70112, 70144), "Khojki": range(70144, 70224), "Multani": range(70272, 70320), "Khudawadi": range(70320, 70400), "Grantha": range(70400, 70528), "Newa": range(70656, 70784), "Tirhuta": range(70784, 70880), "Siddham": range(71040, 71168), "Modi": range(71168, 71264), "Mongolian Supplement": range(71264, 71296), "Takri": range(71296, 71376), "Ahom": range(71424, 71504), "Dogra": range(71680, 71760), "Warang Citi": range(71840, 71936), "Dives Akuru": range(71936, 72032), "Nandinagari": range(72096, 72192), "Zanabazar Square": range(72192, 72272), "Soyombo": range(72272, 72368), "Unified Canadian Aboriginal Syllabics Extended-A": range(72368, 72384), "Pau Cin Hau": range(72384, 72448), "Devanagari Extended-A": range(72448, 72544), "Bhaiksuki": range(72704, 72816), "Marchen": range(72816, 72896), "Masaram Gondi": range(72960, 73056), "Gunjala Gondi": range(73056, 73136), "Makasar": range(73440, 73472), "Kawi": range(73472, 73568), "Lisu Supplement": range(73648, 73664), "Tamil Supplement": range(73664, 73728), "Cuneiform": range(73728, 74752), "Cuneiform Numbers and Punctuation": range(74752, 74880), "Early Dynastic Cuneiform": range(74880, 75088), "Cypro-Minoan": range(77712, 77824), "Egyptian Hieroglyphs": range(77824, 78896), "Egyptian Hieroglyph Format Controls": range(78896, 78944), "Anatolian Hieroglyphs": range(82944, 83584), "Bamum Supplement": range(92160, 92736), "Mro": range(92736, 92784), "Tangsa": range(92784, 92880), "Bassa Vah": range(92880, 92928), "Pahawh Hmong": range(92928, 93072), "Medefaidrin": range(93760, 93856), "Miao": range(93952, 94112), "Ideographic Symbols and Punctuation": range(94176, 94208), "Tangut": range(94208, 100352), "Tangut Components": range(100352, 101120), "Khitan Small Script": range(101120, 101632), "Tangut Supplement": range(101632, 101760), "Kana Extended-B": range(110576, 110592), "Kana Supplement": range(110592, 110848), "Kana Extended-A": range(110848, 110896), "Small Kana Extension": range(110896, 110960), "Nushu": range(110960, 111360), "Duployan": range(113664, 113824), "Shorthand Format Controls": range(113824, 113840), "Znamenny Musical Notation": range(118528, 118736), "Byzantine Musical Symbols": range(118784, 119040), "Musical Symbols": range(119040, 119296), "Ancient Greek Musical Notation": range(119296, 119376), "Kaktovik Numerals": range(119488, 119520), "Mayan Numerals": range(119520, 119552), "Tai Xuan Jing Symbols": range(119552, 119648), "Counting Rod Numerals": range(119648, 119680), "Mathematical Alphanumeric Symbols": range(119808, 120832), "Sutton SignWriting": range(120832, 121520), "Latin Extended-G": range(122624, 122880), "Glagolitic Supplement": range(122880, 122928), "Cyrillic Extended-D": range(122928, 123024), "Nyiakeng Puachue Hmong": range(123136, 123216), "Toto": range(123536, 123584), "Wancho": range(123584, 123648), "Nag Mundari": range(124112, 124160), "Ethiopic Extended-B": range(124896, 124928), "Mende Kikakui": range(124928, 125152), "Adlam": range(125184, 125280), "Indic Siyaq Numbers": range(126064, 126144), "Ottoman Siyaq Numbers": range(126208, 126288), "Arabic Mathematical Alphabetic Symbols": range(126464, 126720), "Mahjong Tiles": range(126976, 127024), "Domino Tiles": range(127024, 127136), "Playing Cards": range(127136, 127232), "Enclosed Alphanumeric Supplement": range(127232, 127488), "Enclosed Ideographic Supplement": range(127488, 127744), "Miscellaneous Symbols and Pictographs": range(127744, 128512), "Emoticons range(Emoji)": range(128512, 128592), "Ornamental Dingbats": range(128592, 128640), "Transport and Map Symbols": range(128640, 128768), "Alchemical Symbols": range(128768, 128896), "Geometric Shapes Extended": range(128896, 129024), "Supplemental Arrows-C": range(129024, 129280), "Supplemental Symbols and Pictographs": range(129280, 129536), "Chess Symbols": range(129536, 129648), "Symbols and Pictographs Extended-A": range(129648, 129792), "Symbols for Legacy Computing": range(129792, 130048), "CJK Unified Ideographs Extension B": range(131072, 173792), "CJK Unified Ideographs Extension C": range(173824, 177984), "CJK Unified Ideographs Extension D": range(177984, 178208), "CJK Unified Ideographs Extension E": range(178208, 183984), "CJK Unified Ideographs Extension F": range(183984, 191472), "CJK Compatibility Ideographs Supplement": range(194560, 195104), "CJK Unified Ideographs Extension G": range(196608, 201552), "CJK Unified Ideographs Extension H": range(201552, 205744), "Tags": range(917504, 917632), "Variation Selectors Supplement": range(917760, 918000), "Supplementary Private Use Area-A": range(983040, 1048576), "Supplementary Private Use Area-B": range(1048576, 1114112),}
UNICODE_SECONDARY_RANGE_KEYWORD: List[str] = [ "Supplement", "Extended", "Extensions", "Modifier", "Marks", "Punctuation", "Symbols", "Forms", "Operators", "Miscellaneous", "Drawing", "Block", "Shapes", "Supplemental", "Tags",]
RE_POSSIBLE_ENCODING_INDICATION = re_compile( r"(?:(?:encoding)|(?:charset)|(?:coding))(?:[\:= ]{1,10})(?:[\"\']?)([a-zA-Z0-9\-_]+)(?:[\"\']?)", IGNORECASE,)
IANA_NO_ALIASES = [ "cp720", "cp737", "cp856", "cp874", "cp875", "cp1006", "koi8_r", "koi8_t", "koi8_u",]
IANA_SUPPORTED: List[str] = sorted( filter( lambda x: x.endswith("_codec") is False and x not in {"rot_13", "tactis", "mbcs"}, list(set(aliases.values())) + IANA_NO_ALIASES, ))
IANA_SUPPORTED_COUNT: int = len(IANA_SUPPORTED)
# pre-computed code page that are similar using the function cp_similarity.IANA_SUPPORTED_SIMILAR: Dict[str, List[str]] = { "cp037": ["cp1026", "cp1140", "cp273", "cp500"], "cp1026": ["cp037", "cp1140", "cp273", "cp500"], "cp1125": ["cp866"], "cp1140": ["cp037", "cp1026", "cp273", "cp500"], "cp1250": ["iso8859_2"], "cp1251": ["kz1048", "ptcp154"], "cp1252": ["iso8859_15", "iso8859_9", "latin_1"], "cp1253": ["iso8859_7"], "cp1254": ["iso8859_15", "iso8859_9", "latin_1"], "cp1257": ["iso8859_13"], "cp273": ["cp037", "cp1026", "cp1140", "cp500"], "cp437": ["cp850", "cp858", "cp860", "cp861", "cp862", "cp863", "cp865"], "cp500": ["cp037", "cp1026", "cp1140", "cp273"], "cp850": ["cp437", "cp857", "cp858", "cp865"], "cp857": ["cp850", "cp858", "cp865"], "cp858": ["cp437", "cp850", "cp857", "cp865"], "cp860": ["cp437", "cp861", "cp862", "cp863", "cp865"], "cp861": ["cp437", "cp860", "cp862", "cp863", "cp865"], "cp862": ["cp437", "cp860", "cp861", "cp863", "cp865"], "cp863": ["cp437", "cp860", "cp861", "cp862", "cp865"], "cp865": ["cp437", "cp850", "cp857", "cp858", "cp860", "cp861", "cp862", "cp863"], "cp866": ["cp1125"], "iso8859_10": ["iso8859_14", "iso8859_15", "iso8859_4", "iso8859_9", "latin_1"], "iso8859_11": ["tis_620"], "iso8859_13": ["cp1257"], "iso8859_14": [ "iso8859_10", "iso8859_15", "iso8859_16", "iso8859_3", "iso8859_9", "latin_1", ], "iso8859_15": [ "cp1252", "cp1254", "iso8859_10", "iso8859_14", "iso8859_16", "iso8859_3", "iso8859_9", "latin_1", ], "iso8859_16": [ "iso8859_14", "iso8859_15", "iso8859_2", "iso8859_3", "iso8859_9", "latin_1", ], "iso8859_2": ["cp1250", "iso8859_16", "iso8859_4"], "iso8859_3": ["iso8859_14", "iso8859_15", "iso8859_16", "iso8859_9", "latin_1"], "iso8859_4": ["iso8859_10", "iso8859_2", "iso8859_9", "latin_1"], "iso8859_7": ["cp1253"], "iso8859_9": [ "cp1252", "cp1254", "cp1258", "iso8859_10", "iso8859_14", "iso8859_15", "iso8859_16", "iso8859_3", "iso8859_4", "latin_1", ], "kz1048": ["cp1251", "ptcp154"], "latin_1": [ "cp1252", "cp1254", "cp1258", "iso8859_10", "iso8859_14", "iso8859_15", "iso8859_16", "iso8859_3", "iso8859_4", "iso8859_9", ], "mac_iceland": ["mac_roman", "mac_turkish"], "mac_roman": ["mac_iceland", "mac_turkish"], "mac_turkish": ["mac_iceland", "mac_roman"], "ptcp154": ["cp1251", "kz1048"], "tis_620": ["iso8859_11"],}
CHARDET_CORRESPONDENCE: Dict[str, str] = { "iso2022_kr": "ISO-2022-KR", "iso2022_jp": "ISO-2022-JP", "euc_kr": "EUC-KR", "tis_620": "TIS-620", "utf_32": "UTF-32", "euc_jp": "EUC-JP", "koi8_r": "KOI8-R", "iso8859_1": "ISO-8859-1", "iso8859_2": "ISO-8859-2", "iso8859_5": "ISO-8859-5", "iso8859_6": "ISO-8859-6", "iso8859_7": "ISO-8859-7", "iso8859_8": "ISO-8859-8", "utf_16": "UTF-16", "cp855": "IBM855", "mac_cyrillic": "MacCyrillic", "gb2312": "GB2312", "gb18030": "GB18030", "cp932": "CP932", "cp866": "IBM866", "utf_8": "utf-8", "utf_8_sig": "UTF-8-SIG", "shift_jis": "SHIFT_JIS", "big5": "Big5", "cp1250": "windows-1250", "cp1251": "windows-1251", "cp1252": "Windows-1252", "cp1253": "windows-1253", "cp1255": "windows-1255", "cp1256": "windows-1256", "cp1254": "Windows-1254", "cp949": "CP949",}
COMMON_SAFE_ASCII_CHARACTERS: Set[str] = { "<", ">", "=", ":", "/", "&", ";", "{", "}", "[", "]", ",", "|", '"', "-",}
KO_NAMES: Set[str] = {"johab", "cp949", "euc_kr"}ZH_NAMES: Set[str] = {"big5", "cp950", "big5hkscs", "hz"}
# Logging LEVEL below DEBUGTRACE: int = 5
# Language label that contain the em dash "—"# character are to be considered alternative seq to originFREQUENCIES: Dict[str, List[str]] = { "English": [ "e", "a", "t", "i", "o", "n", "s", "r", "h", "l", "d", "c", "u", "m", "f", "p", "g", "w", "y", "b", "v", "k", "x", "j", "z", "q", ], "English—": [ "e", "a", "t", "i", "o", "n", "s", "r", "h", "l", "d", "c", "m", "u", "f", "p", "g", "w", "b", "y", "v", "k", "j", "x", "z", "q", ], "German": [ "e", "n", "i", "r", "s", "t", "a", "d", "h", "u", "l", "g", "o", "c", "m", "b", "f", "k", "w", "z", "p", "v", "ü", "ä", "ö", "j", ], "French": [ "e", "a", "s", "n", "i", "t", "r", "l", "u", "o", "d", "c", "p", "m", "é", "v", "g", "f", "b", "h", "q", "à", "x", "è", "y", "j", ], "Dutch": [ "e", "n", "a", "i", "r", "t", "o", "d", "s", "l", "g", "h", "v", "m", "u", "k", "c", "p", "b", "w", "j", "z", "f", "y", "x", "ë", ], "Italian": [ "e", "i", "a", "o", "n", "l", "t", "r", "s", "c", "d", "u", "p", "m", "g", "v", "f", "b", "z", "h", "q", "è", "à", "k", "y", "ò", ], "Polish": [ "a", "i", "o", "e", "n", "r", "z", "w", "s", "c", "t", "k", "y", "d", "p", "m", "u", "l", "j", "ł", "g", "b", "h", "ą", "ę", "ó", ], "Spanish": [ "e", "a", "o", "n", "s", "r", "i", "l", "d", "t", "c", "u", "m", "p", "b", "g", "v", "f", "y", "ó", "h", "q", "í", "j", "z", "á", ], "Russian": [ "о", "а", "е", "и", "н", "с", "т", "р", "в", "л", "к", "м", "д", "п", "у", "г", "я", "ы", "з", "б", "й", "ь", "ч", "х", "ж", "ц", ], # Jap-Kanji "Japanese": [ "人", "一", "大", "亅", "丁", "丨", "竹", "笑", "口", "日", "今", "二", "彳", "行", "十", "土", "丶", "寸", "寺", "時", "乙", "丿", "乂", "气", "気", "冂", "巾", "亠", "市", "目", "儿", "見", "八", "小", "凵", "県", "月", "彐", "門", "間", "木", "東", "山", "出", "本", "中", "刀", "分", "耳", "又", "取", "最", "言", "田", "心", "思", "刂", "前", "京", "尹", "事", "生", "厶", "云", "会", "未", "来", "白", "冫", "楽", "灬", "馬", "尸", "尺", "駅", "明", "耂", "者", "了", "阝", "都", "高", "卜", "占", "厂", "广", "店", "子", "申", "奄", "亻", "俺", "上", "方", "冖", "学", "衣", "艮", "食", "自", ], # Jap-Katakana "Japanese—": [ "ー", "ン", "ス", "・", "ル", "ト", "リ", "イ", "ア", "ラ", "ッ", "ク", "ド", "シ", "レ", "ジ", "タ", "フ", "ロ", "カ", "テ", "マ", "ィ", "グ", "バ", "ム", "プ", "オ", "コ", "デ", "ニ", "ウ", "メ", "サ", "ビ", "ナ", "ブ", "ャ", "エ", "ュ", "チ", "キ", "ズ", "ダ", "パ", "ミ", "ェ", "ョ", "ハ", "セ", "ベ", "ガ", "モ", "ツ", "ネ", "ボ", "ソ", "ノ", "ァ", "ヴ", "ワ", "ポ", "ペ", "ピ", "ケ", "ゴ", "ギ", "ザ", "ホ", "ゲ", "ォ", "ヤ", "ヒ", "ユ", "ヨ", "ヘ", "ゼ", "ヌ", "ゥ", "ゾ", "ヶ", "ヂ", "ヲ", "ヅ", "ヵ", "ヱ", "ヰ", "ヮ", "ヽ", "゠", "ヾ", "ヷ", "ヿ", "ヸ", "ヹ", "ヺ", ], # Jap-Hiragana "Japanese——": [ "の", "に", "る", "た", "と", "は", "し", "い", "を", "で", "て", "が", "な", "れ", "か", "ら", "さ", "っ", "り", "す", "あ", "も", "こ", "ま", "う", "く", "よ", "き", "ん", "め", "お", "け", "そ", "つ", "だ", "や", "え", "ど", "わ", "ち", "み", "せ", "じ", "ば", "へ", "び", "ず", "ろ", "ほ", "げ", "む", "べ", "ひ", "ょ", "ゆ", "ぶ", "ご", "ゃ", "ね", "ふ", "ぐ", "ぎ", "ぼ", "ゅ", "づ", "ざ", "ぞ", "ぬ", "ぜ", "ぱ", "ぽ", "ぷ", "ぴ", "ぃ", "ぁ", "ぇ", "ぺ", "ゞ", "ぢ", "ぉ", "ぅ", "ゐ", "ゝ", "ゑ", "゛", "゜", "ゎ", "ゔ", "゚", "ゟ", "゙", "ゕ", "ゖ", ], "Portuguese": [ "a", "e", "o", "s", "i", "r", "d", "n", "t", "m", "u", "c", "l", "p", "g", "v", "b", "f", "h", "ã", "q", "é", "ç", "á", "z", "í", ], "Swedish": [ "e", "a", "n", "r", "t", "s", "i", "l", "d", "o", "m", "k", "g", "v", "h", "f", "u", "p", "ä", "c", "b", "ö", "å", "y", "j", "x", ], "Chinese": [ "的", "一", "是", "不", "了", "在", "人", "有", "我", "他", "这", "个", "们", "中", "来", "上", "大", "为", "和", "国", "地", "到", "以", "说", "时", "要", "就", "出", "会", "可", "也", "你", "对", "生", "能", "而", "子", "那", "得", "于", "着", "下", "自", "之", "年", "过", "发", "后", "作", "里", "用", "道", "行", "所", "然", "家", "种", "事", "成", "方", "多", "经", "么", "去", "法", "学", "如", "都", "同", "现", "当", "没", "动", "面", "起", "看", "定", "天", "分", "还", "进", "好", "小", "部", "其", "些", "主", "样", "理", "心", "她", "本", "前", "开", "但", "因", "只", "从", "想", "实", ], "Ukrainian": [ "о", "а", "н", "і", "и", "р", "в", "т", "е", "с", "к", "л", "у", "д", "м", "п", "з", "я", "ь", "б", "г", "й", "ч", "х", "ц", "ї", ], "Norwegian": [ "e", "r", "n", "t", "a", "s", "i", "o", "l", "d", "g", "k", "m", "v", "f", "p", "u", "b", "h", "å", "y", "j", "ø", "c", "æ", "w", ], "Finnish": [ "a", "i", "n", "t", "e", "s", "l", "o", "u", "k", "ä", "m", "r", "v", "j", "h", "p", "y", "d", "ö", "g", "c", "b", "f", "w", "z", ], "Vietnamese": [ "n", "h", "t", "i", "c", "g", "a", "o", "u", "m", "l", "r", "à", "đ", "s", "e", "v", "p", "b", "y", "ư", "d", "á", "k", "ộ", "ế", ], "Czech": [ "o", "e", "a", "n", "t", "s", "i", "l", "v", "r", "k", "d", "u", "m", "p", "í", "c", "h", "z", "á", "y", "j", "b", "ě", "é", "ř", ], "Hungarian": [ "e", "a", "t", "l", "s", "n", "k", "r", "i", "o", "z", "á", "é", "g", "m", "b", "y", "v", "d", "h", "u", "p", "j", "ö", "f", "c", ], "Korean": [ "이", "다", "에", "의", "는", "로", "하", "을", "가", "고", "지", "서", "한", "은", "기", "으", "년", "대", "사", "시", "를", "리", "도", "인", "스", "일", ], "Indonesian": [ "a", "n", "e", "i", "r", "t", "u", "s", "d", "k", "m", "l", "g", "p", "b", "o", "h", "y", "j", "c", "w", "f", "v", "z", "x", "q", ], "Turkish": [ "a", "e", "i", "n", "r", "l", "ı", "k", "d", "t", "s", "m", "y", "u", "o", "b", "ü", "ş", "v", "g", "z", "h", "c", "p", "ç", "ğ", ], "Romanian": [ "e", "i", "a", "r", "n", "t", "u", "l", "o", "c", "s", "d", "p", "m", "ă", "f", "v", "î", "g", "b", "ș", "ț", "z", "h", "â", "j", ], "Farsi": [ "ا", "ی", "ر", "د", "ن", "ه", "و", "م", "ت", "ب", "س", "ل", "ک", "ش", "ز", "ف", "گ", "ع", "خ", "ق", "ج", "آ", "پ", "ح", "ط", "ص", ], "Arabic": [ "ا", "ل", "ي", "م", "و", "ن", "ر", "ت", "ب", "ة", "ع", "د", "س", "ف", "ه", "ك", "ق", "أ", "ح", "ج", "ش", "ط", "ص", "ى", "خ", "إ", ], "Danish": [ "e", "r", "n", "t", "a", "i", "s", "d", "l", "o", "g", "m", "k", "f", "v", "u", "b", "h", "p", "å", "y", "ø", "æ", "c", "j", "w", ], "Serbian": [ "а", "и", "о", "е", "н", "р", "с", "у", "т", "к", "ј", "в", "д", "м", "п", "л", "г", "з", "б", "a", "i", "e", "o", "n", "ц", "ш", ], "Lithuanian": [ "i", "a", "s", "o", "r", "e", "t", "n", "u", "k", "m", "l", "p", "v", "d", "j", "g", "ė", "b", "y", "ų", "š", "ž", "c", "ą", "į", ], "Slovene": [ "e", "a", "i", "o", "n", "r", "s", "l", "t", "j", "v", "k", "d", "p", "m", "u", "z", "b", "g", "h", "č", "c", "š", "ž", "f", "y", ], "Slovak": [ "o", "a", "e", "n", "i", "r", "v", "t", "s", "l", "k", "d", "m", "p", "u", "c", "h", "j", "b", "z", "á", "y", "ý", "í", "č", "é", ], "Hebrew": [ "י", "ו", "ה", "ל", "ר", "ב", "ת", "מ", "א", "ש", "נ", "ע", "ם", "ד", "ק", "ח", "פ", "ס", "כ", "ג", "ט", "צ", "ן", "ז", "ך", ], "Bulgarian": [ "а", "и", "о", "е", "н", "т", "р", "с", "в", "л", "к", "д", "п", "м", "з", "г", "я", "ъ", "у", "б", "ч", "ц", "й", "ж", "щ", "х", ], "Croatian": [ "a", "i", "o", "e", "n", "r", "j", "s", "t", "u", "k", "l", "v", "d", "m", "p", "g", "z", "b", "c", "č", "h", "š", "ž", "ć", "f", ], "Hindi": [ "क", "र", "स", "न", "त", "म", "ह", "प", "य", "ल", "व", "ज", "द", "ग", "ब", "श", "ट", "अ", "ए", "थ", "भ", "ड", "च", "ध", "ष", "इ", ], "Estonian": [ "a", "i", "e", "s", "t", "l", "u", "n", "o", "k", "r", "d", "m", "v", "g", "p", "j", "h", "ä", "b", "õ", "ü", "f", "c", "ö", "y", ], "Thai": [ "า", "น", "ร", "อ", "ก", "เ", "ง", "ม", "ย", "ล", "ว", "ด", "ท", "ส", "ต", "ะ", "ป", "บ", "ค", "ห", "แ", "จ", "พ", "ช", "ข", "ใ", ], "Greek": [ "α", "τ", "ο", "ι", "ε", "ν", "ρ", "σ", "κ", "η", "π", "ς", "υ", "μ", "λ", "ί", "ό", "ά", "γ", "έ", "δ", "ή", "ω", "χ", "θ", "ύ", ], "Tamil": [ "க", "த", "ப", "ட", "ர", "ம", "ல", "ன", "வ", "ற", "ய", "ள", "ச", "ந", "இ", "ண", "அ", "ஆ", "ழ", "ங", "எ", "உ", "ஒ", "ஸ", ], "Kazakh": [ "а", "ы", "е", "н", "т", "р", "л", "і", "д", "с", "м", "қ", "к", "о", "б", "и", "у", "ғ", "ж", "ң", "з", "ш", "й", "п", "г", "ө", ],}
LANGUAGE_SUPPORTED_COUNT: int = len(FREQUENCIES)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465from __future__ import annotations
from typing import TYPE_CHECKING, Any, Optionalfrom warnings import warn
from .api import from_bytesfrom .constant import CHARDET_CORRESPONDENCE
# TODO: remove this check when dropping Python 3.7 supportif TYPE_CHECKING: from typing_extensions import TypedDict
class ResultDict(TypedDict): encoding: Optional[str] language: str confidence: Optional[float]
def detect( byte_str: bytes, should_rename_legacy: bool = False, **kwargs: Any) -> ResultDict: """ chardet legacy method Detect the encoding of the given byte string. It should be mostly backward-compatible. Encoding name will match Chardet own writing whenever possible. (Not on encoding name unsupported by it) This function is deprecated and should be used to migrate your project easily, consult the documentation for further information. Not planned for removal.
:param byte_str: The byte sequence to examine. :param should_rename_legacy: Should we rename legacy encodings to their more modern equivalents? """ if len(kwargs): warn( f"charset-normalizer disregard arguments '{','.join(list(kwargs.keys()))}' in legacy function detect()" )
if not isinstance(byte_str, (bytearray, bytes)): raise TypeError( # pragma: nocover "Expected object of type bytes or bytearray, got: " "{0}".format(type(byte_str)) )
if isinstance(byte_str, bytearray): byte_str = bytes(byte_str)
r = from_bytes(byte_str).best()
encoding = r.encoding if r is not None else None language = r.language if r is not None and r.language != "Unknown" else "" confidence = 1.0 - r.chaos if r is not None else None
# Note: CharsetNormalizer does not return 'UTF-8-SIG' as the sig get stripped in the detection/normalization process # but chardet does return 'utf-8-sig' and it is a valid codec name. if r is not None and encoding == "utf_8" and r.bom: encoding += "_sig"
if should_rename_legacy is False and encoding in CHARDET_CORRESPONDENCE: encoding = CHARDET_CORRESPONDENCE[encoding]
return { "encoding": encoding, "language": language, "confidence": confidence, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615from functools import lru_cachefrom logging import getLoggerfrom typing import List, Optional
from .constant import ( COMMON_SAFE_ASCII_CHARACTERS, TRACE, UNICODE_SECONDARY_RANGE_KEYWORD,)from .utils import ( is_accentuated, is_arabic, is_arabic_isolated_form, is_case_variable, is_cjk, is_emoticon, is_hangul, is_hiragana, is_katakana, is_latin, is_punctuation, is_separator, is_symbol, is_thai, is_unprintable, remove_accent, unicode_range,)
class MessDetectorPlugin: """ Base abstract class used for mess detection plugins. All detectors MUST extend and implement given methods. """
def eligible(self, character: str) -> bool: """ Determine if given character should be fed in. """ raise NotImplementedError # pragma: nocover
def feed(self, character: str) -> None: """ The main routine to be executed upon character. Insert the logic in witch the text would be considered chaotic. """ raise NotImplementedError # pragma: nocover
def reset(self) -> None: # pragma: no cover """ Permit to reset the plugin to the initial state. """ raise NotImplementedError
@property def ratio(self) -> float: """ Compute the chaos ratio based on what your feed() has seen. Must NOT be lower than 0.; No restriction gt 0. """ raise NotImplementedError # pragma: nocover
class TooManySymbolOrPunctuationPlugin(MessDetectorPlugin): def __init__(self) -> None: self._punctuation_count: int = 0 self._symbol_count: int = 0 self._character_count: int = 0
self._last_printable_char: Optional[str] = None self._frenzy_symbol_in_word: bool = False
def eligible(self, character: str) -> bool: return character.isprintable()
def feed(self, character: str) -> None: self._character_count += 1
if ( character != self._last_printable_char and character not in COMMON_SAFE_ASCII_CHARACTERS ): if is_punctuation(character): self._punctuation_count += 1 elif ( character.isdigit() is False and is_symbol(character) and is_emoticon(character) is False ): self._symbol_count += 2
self._last_printable_char = character
def reset(self) -> None: # pragma: no cover self._punctuation_count = 0 self._character_count = 0 self._symbol_count = 0
@property def ratio(self) -> float: if self._character_count == 0: return 0.0
ratio_of_punctuation: float = ( self._punctuation_count + self._symbol_count ) / self._character_count
return ratio_of_punctuation if ratio_of_punctuation >= 0.3 else 0.0
class TooManyAccentuatedPlugin(MessDetectorPlugin): def __init__(self) -> None: self._character_count: int = 0 self._accentuated_count: int = 0
def eligible(self, character: str) -> bool: return character.isalpha()
def feed(self, character: str) -> None: self._character_count += 1
if is_accentuated(character): self._accentuated_count += 1
def reset(self) -> None: # pragma: no cover self._character_count = 0 self._accentuated_count = 0
@property def ratio(self) -> float: if self._character_count < 8: return 0.0
ratio_of_accentuation: float = self._accentuated_count / self._character_count return ratio_of_accentuation if ratio_of_accentuation >= 0.35 else 0.0
class UnprintablePlugin(MessDetectorPlugin): def __init__(self) -> None: self._unprintable_count: int = 0 self._character_count: int = 0
def eligible(self, character: str) -> bool: return True
def feed(self, character: str) -> None: if is_unprintable(character): self._unprintable_count += 1 self._character_count += 1
def reset(self) -> None: # pragma: no cover self._unprintable_count = 0
@property def ratio(self) -> float: if self._character_count == 0: return 0.0
return (self._unprintable_count * 8) / self._character_count
class SuspiciousDuplicateAccentPlugin(MessDetectorPlugin): def __init__(self) -> None: self._successive_count: int = 0 self._character_count: int = 0
self._last_latin_character: Optional[str] = None
def eligible(self, character: str) -> bool: return character.isalpha() and is_latin(character)
def feed(self, character: str) -> None: self._character_count += 1 if ( self._last_latin_character is not None and is_accentuated(character) and is_accentuated(self._last_latin_character) ): if character.isupper() and self._last_latin_character.isupper(): self._successive_count += 1 # Worse if its the same char duplicated with different accent. if remove_accent(character) == remove_accent(self._last_latin_character): self._successive_count += 1 self._last_latin_character = character
def reset(self) -> None: # pragma: no cover self._successive_count = 0 self._character_count = 0 self._last_latin_character = None
@property def ratio(self) -> float: if self._character_count == 0: return 0.0
return (self._successive_count * 2) / self._character_count
class SuspiciousRange(MessDetectorPlugin): def __init__(self) -> None: self._suspicious_successive_range_count: int = 0 self._character_count: int = 0 self._last_printable_seen: Optional[str] = None
def eligible(self, character: str) -> bool: return character.isprintable()
def feed(self, character: str) -> None: self._character_count += 1
if ( character.isspace() or is_punctuation(character) or character in COMMON_SAFE_ASCII_CHARACTERS ): self._last_printable_seen = None return
if self._last_printable_seen is None: self._last_printable_seen = character return
unicode_range_a: Optional[str] = unicode_range(self._last_printable_seen) unicode_range_b: Optional[str] = unicode_range(character)
if is_suspiciously_successive_range(unicode_range_a, unicode_range_b): self._suspicious_successive_range_count += 1
self._last_printable_seen = character
def reset(self) -> None: # pragma: no cover self._character_count = 0 self._suspicious_successive_range_count = 0 self._last_printable_seen = None
@property def ratio(self) -> float: if self._character_count <= 24: return 0.0
ratio_of_suspicious_range_usage: float = ( self._suspicious_successive_range_count * 2 ) / self._character_count
return ratio_of_suspicious_range_usage
class SuperWeirdWordPlugin(MessDetectorPlugin): def __init__(self) -> None: self._word_count: int = 0 self._bad_word_count: int = 0 self._foreign_long_count: int = 0
self._is_current_word_bad: bool = False self._foreign_long_watch: bool = False
self._character_count: int = 0 self._bad_character_count: int = 0
self._buffer: str = "" self._buffer_accent_count: int = 0
def eligible(self, character: str) -> bool: return True
def feed(self, character: str) -> None: if character.isalpha(): self._buffer += character if is_accentuated(character): self._buffer_accent_count += 1 if ( self._foreign_long_watch is False and (is_latin(character) is False or is_accentuated(character)) and is_cjk(character) is False and is_hangul(character) is False and is_katakana(character) is False and is_hiragana(character) is False and is_thai(character) is False ): self._foreign_long_watch = True return if not self._buffer: return if ( character.isspace() or is_punctuation(character) or is_separator(character) ) and self._buffer: self._word_count += 1 buffer_length: int = len(self._buffer)
self._character_count += buffer_length
if buffer_length >= 4: if self._buffer_accent_count / buffer_length > 0.34: self._is_current_word_bad = True # Word/Buffer ending with an upper case accentuated letter are so rare, # that we will consider them all as suspicious. Same weight as foreign_long suspicious. if ( is_accentuated(self._buffer[-1]) and self._buffer[-1].isupper() and all(_.isupper() for _ in self._buffer) is False ): self._foreign_long_count += 1 self._is_current_word_bad = True if buffer_length >= 24 and self._foreign_long_watch: camel_case_dst = [ i for c, i in zip(self._buffer, range(0, buffer_length)) if c.isupper() ] probable_camel_cased: bool = False
if camel_case_dst and (len(camel_case_dst) / buffer_length <= 0.3): probable_camel_cased = True
if not probable_camel_cased: self._foreign_long_count += 1 self._is_current_word_bad = True
if self._is_current_word_bad: self._bad_word_count += 1 self._bad_character_count += len(self._buffer) self._is_current_word_bad = False
self._foreign_long_watch = False self._buffer = "" self._buffer_accent_count = 0 elif ( character not in {"<", ">", "-", "=", "~", "|", "_"} and character.isdigit() is False and is_symbol(character) ): self._is_current_word_bad = True self._buffer += character
def reset(self) -> None: # pragma: no cover self._buffer = "" self._is_current_word_bad = False self._foreign_long_watch = False self._bad_word_count = 0 self._word_count = 0 self._character_count = 0 self._bad_character_count = 0 self._foreign_long_count = 0
@property def ratio(self) -> float: if self._word_count <= 10 and self._foreign_long_count == 0: return 0.0
return self._bad_character_count / self._character_count
class CjkInvalidStopPlugin(MessDetectorPlugin): """ GB(Chinese) based encoding often render the stop incorrectly when the content does not fit and can be easily detected. Searching for the overuse of '丅' and '丄'. """
def __init__(self) -> None: self._wrong_stop_count: int = 0 self._cjk_character_count: int = 0
def eligible(self, character: str) -> bool: return True
def feed(self, character: str) -> None: if character in {"丅", "丄"}: self._wrong_stop_count += 1 return if is_cjk(character): self._cjk_character_count += 1
def reset(self) -> None: # pragma: no cover self._wrong_stop_count = 0 self._cjk_character_count = 0
@property def ratio(self) -> float: if self._cjk_character_count < 16: return 0.0 return self._wrong_stop_count / self._cjk_character_count
class ArchaicUpperLowerPlugin(MessDetectorPlugin): def __init__(self) -> None: self._buf: bool = False
self._character_count_since_last_sep: int = 0
self._successive_upper_lower_count: int = 0 self._successive_upper_lower_count_final: int = 0
self._character_count: int = 0
self._last_alpha_seen: Optional[str] = None self._current_ascii_only: bool = True
def eligible(self, character: str) -> bool: return True
def feed(self, character: str) -> None: is_concerned = character.isalpha() and is_case_variable(character) chunk_sep = is_concerned is False
if chunk_sep and self._character_count_since_last_sep > 0: if ( self._character_count_since_last_sep <= 64 and character.isdigit() is False and self._current_ascii_only is False ): self._successive_upper_lower_count_final += ( self._successive_upper_lower_count )
self._successive_upper_lower_count = 0 self._character_count_since_last_sep = 0 self._last_alpha_seen = None self._buf = False self._character_count += 1 self._current_ascii_only = True
return
if self._current_ascii_only is True and character.isascii() is False: self._current_ascii_only = False
if self._last_alpha_seen is not None: if (character.isupper() and self._last_alpha_seen.islower()) or ( character.islower() and self._last_alpha_seen.isupper() ): if self._buf is True: self._successive_upper_lower_count += 2 self._buf = False else: self._buf = True else: self._buf = False
self._character_count += 1 self._character_count_since_last_sep += 1 self._last_alpha_seen = character
def reset(self) -> None: # pragma: no cover self._character_count = 0 self._character_count_since_last_sep = 0 self._successive_upper_lower_count = 0 self._successive_upper_lower_count_final = 0 self._last_alpha_seen = None self._buf = False self._current_ascii_only = True
@property def ratio(self) -> float: if self._character_count == 0: return 0.0
return self._successive_upper_lower_count_final / self._character_count
class ArabicIsolatedFormPlugin(MessDetectorPlugin): def __init__(self) -> None: self._character_count: int = 0 self._isolated_form_count: int = 0
def reset(self) -> None: # pragma: no cover self._character_count = 0 self._isolated_form_count = 0
def eligible(self, character: str) -> bool: return is_arabic(character)
def feed(self, character: str) -> None: self._character_count += 1
if is_arabic_isolated_form(character): self._isolated_form_count += 1
@property def ratio(self) -> float: if self._character_count < 8: return 0.0
isolated_form_usage: float = self._isolated_form_count / self._character_count
return isolated_form_usage
@lru_cache(maxsize=1024)def is_suspiciously_successive_range( unicode_range_a: Optional[str], unicode_range_b: Optional[str]) -> bool: """ Determine if two Unicode range seen next to each other can be considered as suspicious. """ if unicode_range_a is None or unicode_range_b is None: return True
if unicode_range_a == unicode_range_b: return False
if "Latin" in unicode_range_a and "Latin" in unicode_range_b: return False
if "Emoticons" in unicode_range_a or "Emoticons" in unicode_range_b: return False
# Latin characters can be accompanied with a combining diacritical mark # eg. Vietnamese. if ("Latin" in unicode_range_a or "Latin" in unicode_range_b) and ( "Combining" in unicode_range_a or "Combining" in unicode_range_b ): return False
keywords_range_a, keywords_range_b = unicode_range_a.split( " " ), unicode_range_b.split(" ")
for el in keywords_range_a: if el in UNICODE_SECONDARY_RANGE_KEYWORD: continue if el in keywords_range_b: return False
# Japanese Exception range_a_jp_chars, range_b_jp_chars = ( unicode_range_a in ( "Hiragana", "Katakana", ), unicode_range_b in ("Hiragana", "Katakana"), ) if (range_a_jp_chars or range_b_jp_chars) and ( "CJK" in unicode_range_a or "CJK" in unicode_range_b ): return False if range_a_jp_chars and range_b_jp_chars: return False
if "Hangul" in unicode_range_a or "Hangul" in unicode_range_b: if "CJK" in unicode_range_a or "CJK" in unicode_range_b: return False if unicode_range_a == "Basic Latin" or unicode_range_b == "Basic Latin": return False
# Chinese/Japanese use dedicated range for punctuation and/or separators. if ("CJK" in unicode_range_a or "CJK" in unicode_range_b) or ( unicode_range_a in ["Katakana", "Hiragana"] and unicode_range_b in ["Katakana", "Hiragana"] ): if "Punctuation" in unicode_range_a or "Punctuation" in unicode_range_b: return False if "Forms" in unicode_range_a or "Forms" in unicode_range_b: return False if unicode_range_a == "Basic Latin" or unicode_range_b == "Basic Latin": return False
return True
@lru_cache(maxsize=2048)def mess_ratio( decoded_sequence: str, maximum_threshold: float = 0.2, debug: bool = False) -> float: """ Compute a mess ratio given a decoded bytes sequence. The maximum threshold does stop the computation earlier. """
detectors: List[MessDetectorPlugin] = [ md_class() for md_class in MessDetectorPlugin.__subclasses__() ]
length: int = len(decoded_sequence) + 1
mean_mess_ratio: float = 0.0
if length < 512: intermediary_mean_mess_ratio_calc: int = 32 elif length <= 1024: intermediary_mean_mess_ratio_calc = 64 else: intermediary_mean_mess_ratio_calc = 128
for character, index in zip(decoded_sequence + "\n", range(length)): for detector in detectors: if detector.eligible(character): detector.feed(character)
if ( index > 0 and index % intermediary_mean_mess_ratio_calc == 0 ) or index == length - 1: mean_mess_ratio = sum(dt.ratio for dt in detectors)
if mean_mess_ratio >= maximum_threshold: break
if debug: logger = getLogger("charset_normalizer")
logger.log( TRACE, "Mess-detector extended-analysis start. " f"intermediary_mean_mess_ratio_calc={intermediary_mean_mess_ratio_calc} mean_mess_ratio={mean_mess_ratio} " f"maximum_threshold={maximum_threshold}", )
if len(decoded_sequence) > 16: logger.log(TRACE, f"Starting with: {decoded_sequence[:16]}") logger.log(TRACE, f"Ending with: {decoded_sequence[-16::]}")
for dt in detectors: # pragma: nocover logger.log(TRACE, f"{dt.__class__}: {dt.ratio}")
return round(mean_mess_ratio, 3)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338from encodings.aliases import aliasesfrom hashlib import sha256from json import dumpsfrom typing import Any, Dict, Iterator, List, Optional, Tuple, Union
from .constant import TOO_BIG_SEQUENCEfrom .utils import iana_name, is_multi_byte_encoding, unicode_range
class CharsetMatch: def __init__( self, payload: bytes, guessed_encoding: str, mean_mess_ratio: float, has_sig_or_bom: bool, languages: "CoherenceMatches", decoded_payload: Optional[str] = None, ): self._payload: bytes = payload
self._encoding: str = guessed_encoding self._mean_mess_ratio: float = mean_mess_ratio self._languages: CoherenceMatches = languages self._has_sig_or_bom: bool = has_sig_or_bom self._unicode_ranges: Optional[List[str]] = None
self._leaves: List[CharsetMatch] = [] self._mean_coherence_ratio: float = 0.0
self._output_payload: Optional[bytes] = None self._output_encoding: Optional[str] = None
self._string: Optional[str] = decoded_payload
def __eq__(self, other: object) -> bool: if not isinstance(other, CharsetMatch): if isinstance(other, str): return iana_name(other) == self.encoding return False return self.encoding == other.encoding and self.fingerprint == other.fingerprint
def __lt__(self, other: object) -> bool: """ Implemented to make sorted available upon CharsetMatches items. """ if not isinstance(other, CharsetMatch): raise ValueError
chaos_difference: float = abs(self.chaos - other.chaos) coherence_difference: float = abs(self.coherence - other.coherence)
# Below 1% difference --> Use Coherence if chaos_difference < 0.01 and coherence_difference > 0.02: return self.coherence > other.coherence elif chaos_difference < 0.01 and coherence_difference <= 0.02: # When having a difficult decision, use the result that decoded as many multi-byte as possible. # preserve RAM usage! if len(self._payload) >= TOO_BIG_SEQUENCE: return self.chaos < other.chaos return self.multi_byte_usage > other.multi_byte_usage
return self.chaos < other.chaos
@property def multi_byte_usage(self) -> float: return 1.0 - (len(str(self)) / len(self.raw))
def __str__(self) -> str: # Lazy Str Loading if self._string is None: self._string = str(self._payload, self._encoding, "strict") return self._string
def __repr__(self) -> str: return "<CharsetMatch '{}' bytes({})>".format(self.encoding, self.fingerprint)
def add_submatch(self, other: "CharsetMatch") -> None: if not isinstance(other, CharsetMatch) or other == self: raise ValueError( "Unable to add instance <{}> as a submatch of a CharsetMatch".format( other.__class__ ) )
other._string = None # Unload RAM usage; dirty trick. self._leaves.append(other)
@property def encoding(self) -> str: return self._encoding
@property def encoding_aliases(self) -> List[str]: """ Encoding name are known by many name, using this could help when searching for IBM855 when it's listed as CP855. """ also_known_as: List[str] = [] for u, p in aliases.items(): if self.encoding == u: also_known_as.append(p) elif self.encoding == p: also_known_as.append(u) return also_known_as
@property def bom(self) -> bool: return self._has_sig_or_bom
@property def byte_order_mark(self) -> bool: return self._has_sig_or_bom
@property def languages(self) -> List[str]: """ Return the complete list of possible languages found in decoded sequence. Usually not really useful. Returned list may be empty even if 'language' property return something != 'Unknown'. """ return [e[0] for e in self._languages]
@property def language(self) -> str: """ Most probable language found in decoded sequence. If none were detected or inferred, the property will return "Unknown". """ if not self._languages: # Trying to infer the language based on the given encoding # Its either English or we should not pronounce ourselves in certain cases. if "ascii" in self.could_be_from_charset: return "English"
# doing it there to avoid circular import from charset_normalizer.cd import encoding_languages, mb_encoding_languages
languages = ( mb_encoding_languages(self.encoding) if is_multi_byte_encoding(self.encoding) else encoding_languages(self.encoding) )
if len(languages) == 0 or "Latin Based" in languages: return "Unknown"
return languages[0]
return self._languages[0][0]
@property def chaos(self) -> float: return self._mean_mess_ratio
@property def coherence(self) -> float: if not self._languages: return 0.0 return self._languages[0][1]
@property def percent_chaos(self) -> float: return round(self.chaos * 100, ndigits=3)
@property def percent_coherence(self) -> float: return round(self.coherence * 100, ndigits=3)
@property def raw(self) -> bytes: """ Original untouched bytes. """ return self._payload
@property def submatch(self) -> List["CharsetMatch"]: return self._leaves
@property def has_submatch(self) -> bool: return len(self._leaves) > 0
@property def alphabets(self) -> List[str]: if self._unicode_ranges is not None: return self._unicode_ranges # list detected ranges detected_ranges: List[Optional[str]] = [ unicode_range(char) for char in str(self) ] # filter and sort self._unicode_ranges = sorted(list({r for r in detected_ranges if r})) return self._unicode_ranges
@property def could_be_from_charset(self) -> List[str]: """ The complete list of encoding that output the exact SAME str result and therefore could be the originating encoding. This list does include the encoding available in property 'encoding'. """ return [self._encoding] + [m.encoding for m in self._leaves]
def output(self, encoding: str = "utf_8") -> bytes: """ Method to get re-encoded bytes payload using given target encoding. Default to UTF-8. Any errors will be simply ignored by the encoder NOT replaced. """ if self._output_encoding is None or self._output_encoding != encoding: self._output_encoding = encoding self._output_payload = str(self).encode(encoding, "replace")
return self._output_payload # type: ignore
@property def fingerprint(self) -> str: """ Retrieve the unique SHA256 computed using the transformed (re-encoded) payload. Not the original one. """ return sha256(self.output()).hexdigest()
class CharsetMatches: """ Container with every CharsetMatch items ordered by default from most probable to the less one. Act like a list(iterable) but does not implements all related methods. """
def __init__(self, results: Optional[List[CharsetMatch]] = None): self._results: List[CharsetMatch] = sorted(results) if results else []
def __iter__(self) -> Iterator[CharsetMatch]: yield from self._results
def __getitem__(self, item: Union[int, str]) -> CharsetMatch: """ Retrieve a single item either by its position or encoding name (alias may be used here). Raise KeyError upon invalid index or encoding not present in results. """ if isinstance(item, int): return self._results[item] if isinstance(item, str): item = iana_name(item, False) for result in self._results: if item in result.could_be_from_charset: return result raise KeyError
def __len__(self) -> int: return len(self._results)
def __bool__(self) -> bool: return len(self._results) > 0
def append(self, item: CharsetMatch) -> None: """ Insert a single match. Will be inserted accordingly to preserve sort. Can be inserted as a submatch. """ if not isinstance(item, CharsetMatch): raise ValueError( "Cannot append instance '{}' to CharsetMatches".format( str(item.__class__) ) ) # We should disable the submatch factoring when the input file is too heavy (conserve RAM usage) if len(item.raw) <= TOO_BIG_SEQUENCE: for match in self._results: if match.fingerprint == item.fingerprint and match.chaos == item.chaos: match.add_submatch(item) return self._results.append(item) self._results = sorted(self._results)
def best(self) -> Optional["CharsetMatch"]: """ Simply return the first match. Strict equivalent to matches[0]. """ if not self._results: return None return self._results[0]
def first(self) -> Optional["CharsetMatch"]: """ Redundant method, call the method best(). Kept for BC reasons. """ return self.best()
CoherenceMatch = Tuple[str, float]CoherenceMatches = List[CoherenceMatch]
class CliDetectionResult: def __init__( self, path: str, encoding: Optional[str], encoding_aliases: List[str], alternative_encodings: List[str], language: str, alphabets: List[str], has_sig_or_bom: bool, chaos: float, coherence: float, unicode_path: Optional[str], is_preferred: bool, ): self.path: str = path self.unicode_path: Optional[str] = unicode_path self.encoding: Optional[str] = encoding self.encoding_aliases: List[str] = encoding_aliases self.alternative_encodings: List[str] = alternative_encodings self.language: str = language self.alphabets: List[str] = alphabets self.has_sig_or_bom: bool = has_sig_or_bom self.chaos: float = chaos self.coherence: float = coherence self.is_preferred: bool = is_preferred
@property def __dict__(self) -> Dict[str, Any]: # type: ignore return { "path": self.path, "encoding": self.encoding, "encoding_aliases": self.encoding_aliases, "alternative_encodings": self.alternative_encodings, "language": self.language, "alphabets": self.alphabets, "has_sig_or_bom": self.has_sig_or_bom, "chaos": self.chaos, "coherence": self.coherence, "unicode_path": self.unicode_path, "is_preferred": self.is_preferred, }
def to_json(self) -> str: return dumps(self.__dict__, ensure_ascii=True, indent=4)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421import importlibimport loggingimport unicodedatafrom codecs import IncrementalDecoderfrom encodings.aliases import aliasesfrom functools import lru_cachefrom re import findallfrom typing import Generator, List, Optional, Set, Tuple, Union
from _multibytecodec import MultibyteIncrementalDecoder
from .constant import ( ENCODING_MARKS, IANA_SUPPORTED_SIMILAR, RE_POSSIBLE_ENCODING_INDICATION, UNICODE_RANGES_COMBINED, UNICODE_SECONDARY_RANGE_KEYWORD, UTF8_MAXIMAL_ALLOCATION,)
@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)def is_accentuated(character: str) -> bool: try: description: str = unicodedata.name(character) except ValueError: return False return ( "WITH GRAVE" in description or "WITH ACUTE" in description or "WITH CEDILLA" in description or "WITH DIAERESIS" in description or "WITH CIRCUMFLEX" in description or "WITH TILDE" in description or "WITH MACRON" in description or "WITH RING ABOVE" in description )
@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)def remove_accent(character: str) -> str: decomposed: str = unicodedata.decomposition(character) if not decomposed: return character
codes: List[str] = decomposed.split(" ")
return chr(int(codes[0], 16))
@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)def unicode_range(character: str) -> Optional[str]: """ Retrieve the Unicode range official name from a single character. """ character_ord: int = ord(character)
for range_name, ord_range in UNICODE_RANGES_COMBINED.items(): if character_ord in ord_range: return range_name
return None
@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)def is_latin(character: str) -> bool: try: description: str = unicodedata.name(character) except ValueError: return False return "LATIN" in description
@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)def is_punctuation(character: str) -> bool: character_category: str = unicodedata.category(character)
if "P" in character_category: return True
character_range: Optional[str] = unicode_range(character)
if character_range is None: return False
return "Punctuation" in character_range
@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)def is_symbol(character: str) -> bool: character_category: str = unicodedata.category(character)
if "S" in character_category or "N" in character_category: return True
character_range: Optional[str] = unicode_range(character)
if character_range is None: return False
return "Forms" in character_range and character_category != "Lo"
@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)def is_emoticon(character: str) -> bool: character_range: Optional[str] = unicode_range(character)
if character_range is None: return False
return "Emoticons" in character_range or "Pictographs" in character_range
@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)def is_separator(character: str) -> bool: if character.isspace() or character in {"|", "+", "<", ">"}: return True
character_category: str = unicodedata.category(character)
return "Z" in character_category or character_category in {"Po", "Pd", "Pc"}
@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)def is_case_variable(character: str) -> bool: return character.islower() != character.isupper()
@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)def is_cjk(character: str) -> bool: try: character_name = unicodedata.name(character) except ValueError: return False
return "CJK" in character_name
@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)def is_hiragana(character: str) -> bool: try: character_name = unicodedata.name(character) except ValueError: return False
return "HIRAGANA" in character_name
@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)def is_katakana(character: str) -> bool: try: character_name = unicodedata.name(character) except ValueError: return False
return "KATAKANA" in character_name
@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)def is_hangul(character: str) -> bool: try: character_name = unicodedata.name(character) except ValueError: return False
return "HANGUL" in character_name
@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)def is_thai(character: str) -> bool: try: character_name = unicodedata.name(character) except ValueError: return False
return "THAI" in character_name
@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)def is_arabic(character: str) -> bool: try: character_name = unicodedata.name(character) except ValueError: return False
return "ARABIC" in character_name
@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)def is_arabic_isolated_form(character: str) -> bool: try: character_name = unicodedata.name(character) except ValueError: return False
return "ARABIC" in character_name and "ISOLATED FORM" in character_name
@lru_cache(maxsize=len(UNICODE_RANGES_COMBINED))def is_unicode_range_secondary(range_name: str) -> bool: return any(keyword in range_name for keyword in UNICODE_SECONDARY_RANGE_KEYWORD)
@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION)def is_unprintable(character: str) -> bool: return ( character.isspace() is False # includes \n \t \r \v and character.isprintable() is False and character != "\x1A" # Why? Its the ASCII substitute character. and character != "\ufeff" # bug discovered in Python, # Zero Width No-Break Space located in Arabic Presentation Forms-B, Unicode 1.1 not acknowledged as space. )
def any_specified_encoding(sequence: bytes, search_zone: int = 8192) -> Optional[str]: """ Extract using ASCII-only decoder any specified encoding in the first n-bytes. """ if not isinstance(sequence, bytes): raise TypeError
seq_len: int = len(sequence)
results: List[str] = findall( RE_POSSIBLE_ENCODING_INDICATION, sequence[: min(seq_len, search_zone)].decode("ascii", errors="ignore"), )
if len(results) == 0: return None
for specified_encoding in results: specified_encoding = specified_encoding.lower().replace("-", "_")
encoding_alias: str encoding_iana: str
for encoding_alias, encoding_iana in aliases.items(): if encoding_alias == specified_encoding: return encoding_iana if encoding_iana == specified_encoding: return encoding_iana
return None
@lru_cache(maxsize=128)def is_multi_byte_encoding(name: str) -> bool: """ Verify is a specific encoding is a multi byte one based on it IANA name """ return name in { "utf_8", "utf_8_sig", "utf_16", "utf_16_be", "utf_16_le", "utf_32", "utf_32_le", "utf_32_be", "utf_7", } or issubclass( importlib.import_module("encodings.{}".format(name)).IncrementalDecoder, MultibyteIncrementalDecoder, )
def identify_sig_or_bom(sequence: bytes) -> Tuple[Optional[str], bytes]: """ Identify and extract SIG/BOM in given sequence. """
for iana_encoding in ENCODING_MARKS: marks: Union[bytes, List[bytes]] = ENCODING_MARKS[iana_encoding]
if isinstance(marks, bytes): marks = [marks]
for mark in marks: if sequence.startswith(mark): return iana_encoding, mark
return None, b""
def should_strip_sig_or_bom(iana_encoding: str) -> bool: return iana_encoding not in {"utf_16", "utf_32"}
def iana_name(cp_name: str, strict: bool = True) -> str: cp_name = cp_name.lower().replace("-", "_")
encoding_alias: str encoding_iana: str
for encoding_alias, encoding_iana in aliases.items(): if cp_name in [encoding_alias, encoding_iana]: return encoding_iana
if strict: raise ValueError("Unable to retrieve IANA for '{}'".format(cp_name))
return cp_name
def range_scan(decoded_sequence: str) -> List[str]: ranges: Set[str] = set()
for character in decoded_sequence: character_range: Optional[str] = unicode_range(character)
if character_range is None: continue
ranges.add(character_range)
return list(ranges)
def cp_similarity(iana_name_a: str, iana_name_b: str) -> float: if is_multi_byte_encoding(iana_name_a) or is_multi_byte_encoding(iana_name_b): return 0.0
decoder_a = importlib.import_module( "encodings.{}".format(iana_name_a) ).IncrementalDecoder decoder_b = importlib.import_module( "encodings.{}".format(iana_name_b) ).IncrementalDecoder
id_a: IncrementalDecoder = decoder_a(errors="ignore") id_b: IncrementalDecoder = decoder_b(errors="ignore")
character_match_count: int = 0
for i in range(255): to_be_decoded: bytes = bytes([i]) if id_a.decode(to_be_decoded) == id_b.decode(to_be_decoded): character_match_count += 1
return character_match_count / 254
def is_cp_similar(iana_name_a: str, iana_name_b: str) -> bool: """ Determine if two code page are at least 80% similar. IANA_SUPPORTED_SIMILAR dict was generated using the function cp_similarity. """ return ( iana_name_a in IANA_SUPPORTED_SIMILAR and iana_name_b in IANA_SUPPORTED_SIMILAR[iana_name_a] )
def set_logging_handler( name: str = "charset_normalizer", level: int = logging.INFO, format_string: str = "%(asctime)s | %(levelname)s | %(message)s",) -> None: logger = logging.getLogger(name) logger.setLevel(level)
handler = logging.StreamHandler() handler.setFormatter(logging.Formatter(format_string)) logger.addHandler(handler)
def cut_sequence_chunks( sequences: bytes, encoding_iana: str, offsets: range, chunk_size: int, bom_or_sig_available: bool, strip_sig_or_bom: bool, sig_payload: bytes, is_multi_byte_decoder: bool, decoded_payload: Optional[str] = None,) -> Generator[str, None, None]: if decoded_payload and is_multi_byte_decoder is False: for i in offsets: chunk = decoded_payload[i : i + chunk_size] if not chunk: break yield chunk else: for i in offsets: chunk_end = i + chunk_size if chunk_end > len(sequences) + 8: continue
cut_sequence = sequences[i : i + chunk_size]
if bom_or_sig_available and strip_sig_or_bom is False: cut_sequence = sig_payload + cut_sequence
chunk = cut_sequence.decode( encoding_iana, errors="ignore" if is_multi_byte_decoder else "strict", )
# multi-byte bad cutting detector and adjustment # not the cleanest way to perform that fix but clever enough for now. if is_multi_byte_decoder and i > 0: chunk_partial_size_chk: int = min(chunk_size, 16)
if ( decoded_payload and chunk[:chunk_partial_size_chk] not in decoded_payload ): for j in range(i, i - 4, -1): cut_sequence = sequences[j:chunk_end]
if bom_or_sig_available and strip_sig_or_bom is False: cut_sequence = sig_payload + cut_sequence
chunk = cut_sequence.decode(encoding_iana, errors="ignore")
if chunk[:chunk_partial_size_chk] in decoded_payload: break
yield chunk123456"""Expose version"""
__version__ = "3.3.2"VERSION = __version__.split(".")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we ascontributors and maintainers pledge to making participation in our project andour community a harassment-free experience for everyone, regardless of age, bodysize, disability, ethnicity, sex characteristics, gender identity and expression,level of experience, education, socio-economic status, nationality, personalappearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environmentinclude:
* Using welcoming and inclusive language* Being respectful of differing viewpoints and experiences* Gracefully accepting constructive criticism* Focusing on what is best for the community* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances* Trolling, insulting/derogatory comments, and personal or political attacks* Public or private harassment* Publishing others' private information, such as a physical or electronic address, without explicit permission* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptablebehavior and are expected to take appropriate and fair corrective action inresponse to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, orreject comments, commits, code, wiki edits, issues, and other contributionsthat are not aligned to this Code of Conduct, or to ban temporarily orpermanently any contributor for other behaviors that they deem inappropriate,threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaceswhen an individual is representing the project or its community. Examples ofrepresenting a project or community include using an official project e-mailaddress, posting via an official social media account, or acting as an appointedrepresentative at an online or offline event. Representation of a project may befurther defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may bereported by contacting the project team at ahmed.tahri@cloudnursery.dev. Allcomplaints will be reviewed and investigated and will result in a response thatis deemed necessary and appropriate to the circumstances. The project team isobligated to maintain confidentiality with regard to the reporter of an incident.Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in goodfaith may face temporary or permanent repercussions as determined by othermembers of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, seehttps://www.contributor-covenant.org/faq12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273# Contribution Guidelines
If you’re reading this, you’re probably interested in contributing to Charset Normalizer. Thank you very much! Open source projects live-and-die based on the support they receive from others, and the fact that you’re even considering contributing to this project is very generous of you.
## Questions
The GitHub issue tracker is for *bug reports* and *feature requests*. Questions are allowed only when no answer are provided in docs.
## Good Bug Reports
Please be aware of the following things when filing bug reports:
1. Avoid raising duplicate issues. *Please* use the GitHub issue search feature to check whether your bug report or feature request has been mentioned in the past. Duplicate bug reports and feature requests are a huge maintenance burden on the limited resources of the project. If it is clear from your report that you would have struggled to find the original, that's ok, but if searching for a selection of words in your issue title would have found the duplicate then the issue will likely be closed extremely abruptly.2. When filing bug reports about exceptions or tracebacks, please include the *complete* traceback. Partial tracebacks, or just the exception text, are not helpful. Issues that do not contain complete tracebacks may be closed without warning.3. Make sure you provide a suitable amount of information to work with. This means you should provide:
- Guidance on **how to reproduce the issue**. Ideally, this should be a *small* code sample that can be run immediately by the maintainers. Failing that, let us know what you're doing, how often it happens, what environment you're using, etc. Be thorough: it prevents us needing to ask further questions. - Tell us **what you expected to happen**. When we run your example code, what are we expecting to happen? What does "success" look like for your code? - Tell us **what actually happens**. It's not helpful for you to say "it doesn't work" or "it fails". Tell us *how* it fails: do you get an exception? A None answer? How was the actual result different from your expected result? - Tell us **what version of Charset Normalizer you're using**, and **how you installed it**. Different versions of Charset Normalizer behave differently and have different bugs.
If you do not provide all of these things, it will take us much longer to fix your problem. If we ask you to clarify these, and you never respond, we will close your issue without fixing it.
## What PR are we accepting?
Mostly anything, from cosmetic to the detection-mechanism improvement at the solo condition that you do not breakthe backward-compatibility.
## What PR may be doomed?
- Add support for a Rust encoding unsupported charset/encoding> If you looked carefully at the project, you would see that it aims to be generic whenever possible. So adding a specific prober is out of the question.
- Of course, if the CI/CD are failing> Getting the discussion started often mean doing the minimum effort to get it Green! (Be reassured, maintainers will look into it, given a reasonable amount of time)
- Submitting a PR without any description OR viable commit description> This is obvious, maintainers need to understand as fast as possible what are you trying to submit without putting too much effort.
## How to run tests locally?
It is essential that you run, prior to any submissions the mandatory checks.Run:* `cargo fmt` to check and auto-fix formatting, * `cargo clippy` to linter your code,* `cargo test` to run all tests.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795# This file is automatically @generated by Cargo.# It is not intended for manual editing.version = 3
[[package]]name = "ahash"version = "0.8.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2c99f64d1e06488f620f932677e24bc6e2897582980441ae90a671415bd7ec2f"dependencies = [ "cfg-if", "getrandom", "once_cell", "version_check",]
[[package]]name = "aho-corasick"version = "1.0.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0c378d78423fdad8089616f827526ee33c19f2fddbd5de1629152c9593ba4783"dependencies = [ "memchr",]
[[package]]name = "allocator-api2"version = "0.2.16"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5"
[[package]]name = "anstream"version = "0.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b1f58811cfac344940f1a400b6e6231ce35171f614f26439e80f8c1465c5cc0c"dependencies = [ "anstyle", "anstyle-parse", "anstyle-query", "anstyle-wincon", "colorchoice", "utf8parse",]
[[package]]name = "anstyle"version = "1.0.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "15c4c2c83f81532e5845a733998b6971faca23490340a418e9b72a3ec9de12ea"
[[package]]name = "anstyle-parse"version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "938874ff5980b03a87c5524b3ae5b59cf99b1d6bc836848df7bc5ada9643c333"dependencies = [ "utf8parse",]
[[package]]name = "anstyle-query"version = "1.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5ca11d4be1bab0c8bc8734a9aa7bf4ee8316d462a08c6ac5052f888fef5b494b"dependencies = [ "windows-sys 0.48.0",]
[[package]]name = "anstyle-wincon"version = "2.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "58f54d10c6dfa51283a066ceab3ec1ab78d13fae00aa49243a45e4571fb79dfd"dependencies = [ "anstyle", "windows-sys 0.48.0",]
[[package]]name = "assert_cmd"version = "2.0.12"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "88903cb14723e4d4003335bb7f8a14f27691649105346a0f0957466c096adfe6"dependencies = [ "anstyle", "bstr", "doc-comment", "predicates", "predicates-core", "predicates-tree", "wait-timeout",]
[[package]]name = "atty"version = "0.2.14"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"dependencies = [ "hermit-abi 0.1.19", "libc", "winapi",]
[[package]]name = "autocfg"version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
[[package]]name = "bitflags"version = "1.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]name = "bitflags"version = "2.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b4682ae6287fcf752ecaabbfcc7b6f9b72aa33933dc23a554d853aea8eea8635"
[[package]]name = "bstr"version = "1.6.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4c2f7349907b712260e64b0afe2f84692af14a454be26187d9df565c7f69266a"dependencies = [ "memchr", "regex-automata", "serde",]
[[package]]name = "bumpalo"version = "3.13.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a3e2c3daef883ecc1b5d58c15adae93470a91d425f3532ba1695849656af3fc1"
[[package]]name = "cached"version = "0.46.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8cead8ece0da6b744b2ad8ef9c58a4cdc7ef2921e60a6ddfb9eaaa86839b5fc5"dependencies = [ "ahash", "cached_proc_macro", "cached_proc_macro_types", "hashbrown", "instant", "once_cell", "thiserror",]
[[package]]name = "cached_proc_macro"version = "0.18.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7da8245dd5f576a41c3b76247b54c15b0e43139ceeb4f732033e15be7c005176"dependencies = [ "darling", "proc-macro2", "quote", "syn 1.0.109",]
[[package]]name = "cached_proc_macro_types"version = "0.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3a4f925191b4367301851c6d99b09890311d74b0d43f274c0b34c86d308a3663"
[[package]]name = "cast"version = "0.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
[[package]]name = "cc"version = "1.0.83"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0"dependencies = [ "libc",]
[[package]]name = "cfg-if"version = "1.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]name = "chardet"version = "0.2.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1a48563284b67c003ba0fb7243c87fab68885e1532c605704228a80238512e31"
[[package]]name = "chardetng"version = "0.1.17"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "14b8f0b65b7b08ae3c8187e8d77174de20cb6777864c6b832d8ad365999cf1ea"dependencies = [ "cfg-if", "encoding_rs", "memchr",]
[[package]]name = "charset-normalizer-rs"version = "1.0.6"dependencies = [ "ahash", "assert_cmd", "bitflags 2.4.0", "cached", "chardet", "chardetng", "clap 4.4.2", "counter", "criterion", "dialoguer", "encoding", "env_logger", "icu_normalizer", "icu_properties", "log", "once_cell", "ordered-float", "predicates", "regex", "serde", "serde_json", "strsim", "unicode_names2",]
[[package]]name = "clap"version = "2.34.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c"dependencies = [ "bitflags 1.3.2", "textwrap", "unicode-width",]
[[package]]name = "clap"version = "4.4.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6a13b88d2c62ff462f88e4a121f17a82c1af05693a2f192b5c38d14de73c19f6"dependencies = [ "clap_builder", "clap_derive",]
[[package]]name = "clap_builder"version = "4.4.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2bb9faaa7c2ef94b2743a21f5a29e6f0010dff4caa69ac8e9d6cf8b6fa74da08"dependencies = [ "anstream", "anstyle", "clap_lex", "strsim",]
[[package]]name = "clap_derive"version = "4.4.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0862016ff20d69b84ef8247369fabf5c008a7417002411897d40ee1f4532b873"dependencies = [ "heck", "proc-macro2", "quote", "syn 2.0.31",]
[[package]]name = "clap_lex"version = "0.5.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cd7cc57abe963c6d3b9d8be5b06ba7c8957a930305ca90304f24ef040aa6f961"
[[package]]name = "colorchoice"version = "1.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7"
[[package]]name = "console"version = "0.15.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c926e00cc70edefdc64d3a5ff31cc65bb97a3460097762bd23afb4d8145fccf8"dependencies = [ "encode_unicode", "lazy_static", "libc", "unicode-width", "windows-sys 0.45.0",]
[[package]]name = "counter"version = "0.5.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2d458e66999348f56fd3ffcfbb7f7951542075ca8359687c703de6500c1ddccd"dependencies = [ "num-traits",]
[[package]]name = "criterion"version = "0.3.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b01d6de93b2b6c65e17c634a26653a29d107b3c98c607c765bf38d041531cd8f"dependencies = [ "atty", "cast", "clap 2.34.0", "criterion-plot", "csv", "itertools", "lazy_static", "num-traits", "oorandom", "plotters", "rayon", "regex", "serde", "serde_cbor", "serde_derive", "serde_json", "tinytemplate", "walkdir",]
[[package]]name = "criterion-plot"version = "0.4.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2673cc8207403546f45f5fd319a974b1e6983ad1a3ee7e6041650013be041876"dependencies = [ "cast", "itertools",]
[[package]]name = "crossbeam-channel"version = "0.5.8"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a33c2bf77f2df06183c3aa30d1e96c0695a313d4f9c453cc3762a6db39f99200"dependencies = [ "cfg-if", "crossbeam-utils",]
[[package]]name = "crossbeam-deque"version = "0.8.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ce6fd6f855243022dcecf8702fef0c297d4338e226845fe067f6341ad9fa0cef"dependencies = [ "cfg-if", "crossbeam-epoch", "crossbeam-utils",]
[[package]]name = "crossbeam-epoch"version = "0.9.15"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ae211234986c545741a7dc064309f67ee1e5ad243d0e48335adc0484d960bcc7"dependencies = [ "autocfg", "cfg-if", "crossbeam-utils", "memoffset", "scopeguard",]
[[package]]name = "crossbeam-utils"version = "0.8.16"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5a22b2d63d4d1dc0b7f1b6b2747dd0088008a9be28b6ddf0b1e7d335e3037294"dependencies = [ "cfg-if",]
[[package]]name = "csv"version = "1.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "626ae34994d3d8d668f4269922248239db4ae42d538b14c398b74a52208e8086"dependencies = [ "csv-core", "itoa", "ryu", "serde",]
[[package]]name = "csv-core"version = "0.1.10"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2b2466559f260f48ad25fe6317b3c8dac77b5bdb5763ac7d9d6103530663bc90"dependencies = [ "memchr",]
[[package]]name = "darling"version = "0.14.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7b750cb3417fd1b327431a470f388520309479ab0bf5e323505daf0290cd3850"dependencies = [ "darling_core", "darling_macro",]
[[package]]name = "darling_core"version = "0.14.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "109c1ca6e6b7f82cc233a97004ea8ed7ca123a9af07a8230878fcfda9b158bf0"dependencies = [ "fnv", "ident_case", "proc-macro2", "quote", "strsim", "syn 1.0.109",]
[[package]]name = "darling_macro"version = "0.14.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a4aab4dbc9f7611d8b55048a3a16d2d010c2c8334e46304b40ac1cc14bf3b48e"dependencies = [ "darling_core", "quote", "syn 1.0.109",]
[[package]]name = "dialoguer"version = "0.10.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "59c6f2989294b9a498d3ad5491a79c6deb604617378e1cdc4bfc1c1361fe2f87"dependencies = [ "console", "shell-words", "tempfile", "zeroize",]
[[package]]name = "difflib"version = "0.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8"
[[package]]name = "displaydoc"version = "0.2.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "487585f4d0c6655fe74905e2504d8ad6908e4db67f744eb140876906c2f3175d"dependencies = [ "proc-macro2", "quote", "syn 2.0.31",]
[[package]]name = "doc-comment"version = "0.3.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fea41bba32d969b513997752735605054bc0dfa92b4c56bf1189f2e174be7a10"
[[package]]name = "either"version = "1.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07"
[[package]]name = "encode_unicode"version = "0.3.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f"
[[package]]name = "encoding"version = "0.2.33"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6b0d943856b990d12d3b55b359144ff341533e516d94098b1d3fc1ac666d36ec"dependencies = [ "encoding-index-japanese", "encoding-index-korean", "encoding-index-simpchinese", "encoding-index-singlebyte", "encoding-index-tradchinese",]
[[package]]name = "encoding-index-japanese"version = "1.20141219.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "04e8b2ff42e9a05335dbf8b5c6f7567e5591d0d916ccef4e0b1710d32a0d0c91"dependencies = [ "encoding_index_tests",]
[[package]]name = "encoding-index-korean"version = "1.20141219.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4dc33fb8e6bcba213fe2f14275f0963fd16f0a02c878e3095ecfdf5bee529d81"dependencies = [ "encoding_index_tests",]
[[package]]name = "encoding-index-simpchinese"version = "1.20141219.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d87a7194909b9118fc707194baa434a4e3b0fb6a5a757c73c3adb07aa25031f7"dependencies = [ "encoding_index_tests",]
[[package]]name = "encoding-index-singlebyte"version = "1.20141219.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3351d5acffb224af9ca265f435b859c7c01537c0849754d3db3fdf2bfe2ae84a"dependencies = [ "encoding_index_tests",]
[[package]]name = "encoding-index-tradchinese"version = "1.20141219.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fd0e20d5688ce3cab59eb3ef3a2083a5c77bf496cb798dc6fcdb75f323890c18"dependencies = [ "encoding_index_tests",]
[[package]]name = "encoding_index_tests"version = "0.1.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a246d82be1c9d791c5dfde9a2bd045fc3cbba3fa2b11ad558f27d01712f00569"
[[package]]name = "encoding_rs"version = "0.8.33"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7268b386296a025e474d5140678f75d6de9493ae55a5d709eeb9dd08149945e1"dependencies = [ "cfg-if",]
[[package]]name = "env_logger"version = "0.10.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "85cdab6a89accf66733ad5a1693a4dcced6aeff64602b634530dd73c1f3ee9f0"dependencies = [ "humantime", "is-terminal", "log", "regex", "termcolor",]
[[package]]name = "errno"version = "0.3.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "136526188508e25c6fef639d7927dfb3e0e3084488bf202267829cf7fc23dbdd"dependencies = [ "errno-dragonfly", "libc", "windows-sys 0.48.0",]
[[package]]name = "errno-dragonfly"version = "0.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf"dependencies = [ "cc", "libc",]
[[package]]name = "fastrand"version = "2.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6999dc1837253364c2ebb0704ba97994bd874e8f195d665c50b7548f6ea92764"
[[package]]name = "float-cmp"version = "0.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"dependencies = [ "num-traits",]
[[package]]name = "fnv"version = "1.0.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]name = "getopts"version = "0.2.21"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "14dbbfd5c71d70241ecf9e6f13737f7b5ce823821063188d7e46c41d371eebd5"dependencies = [ "unicode-width",]
[[package]]name = "getrandom"version = "0.2.10"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "be4136b2a15dd319360be1c07d9933517ccf0be8f16bf62a3bee4f0d618df427"dependencies = [ "cfg-if", "libc", "wasi",]
[[package]]name = "half"version = "1.8.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "eabb4a44450da02c90444cf74558da904edde8fb4e9035a9a6a4e15445af0bd7"
[[package]]name = "hashbrown"version = "0.14.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2c6201b9ff9fd90a5a3bac2e56a830d0caa509576f0e503818ee82c181b3437a"dependencies = [ "ahash", "allocator-api2",]
[[package]]name = "heck"version = "0.4.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
[[package]]name = "hermit-abi"version = "0.1.19"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33"dependencies = [ "libc",]
[[package]]name = "hermit-abi"version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "443144c8cdadd93ebf52ddb4056d257f5b52c04d3c804e657d19eb73fc33668b"
[[package]]name = "humantime"version = "2.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
[[package]]name = "icu_collections"version = "1.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3907b2246e8dd5a29ead8a965e7c0c8a90e9b928e614a4279257d45c5e553e91"dependencies = [ "displaydoc", "yoke", "zerofrom", "zerovec",]
[[package]]name = "icu_locid"version = "1.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f284eb342dc49d3e9d9f3b188489d76b5d22dfb1d1a5e0d1941811253bac625c"dependencies = [ "displaydoc", "litemap", "tinystr", "writeable", "zerovec",]
[[package]]name = "icu_locid_transform"version = "1.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6551daf80882d8e68eee186cc19e132d8bde1b1f059a79b93384a5ca0e8fc5e7"dependencies = [ "displaydoc", "icu_locid", "icu_locid_transform_data", "icu_provider", "tinystr", "zerovec",]
[[package]]name = "icu_locid_transform_data"version = "1.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2a741eba5431f75eb2f1f9022d3cffabcadda6771e54fb4e77c8ba8653e4da44"
[[package]]name = "icu_normalizer"version = "1.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "080fc33a720d50a7342b0c58df010fbcfb842d6f78ef81555f8b1ac6bba57d3c"dependencies = [ "displaydoc", "icu_collections", "icu_normalizer_data", "icu_properties", "icu_provider", "smallvec", "utf16_iter", "utf8_iter", "write16", "zerovec",]
[[package]]name = "icu_normalizer_data"version = "1.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6f8d22f74066c2e6442db2a9aa14950278e86719e811e304e48bae03094b369d"
[[package]]name = "icu_properties"version = "1.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3477ae70f8ca8dc08ff7574b5398ed0a2f2e4e6b66bdff2558a92ed67e262be1"dependencies = [ "displaydoc", "icu_collections", "icu_locid_transform", "icu_properties_data", "icu_provider", "tinystr", "zerovec",]
[[package]]name = "icu_properties_data"version = "1.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7c8bb3b67a8347e94d580434369e5c7ee89999b9309d04b7cfc88dfaa0f31b59"
[[package]]name = "icu_provider"version = "1.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "68acdef80034b5e35d8524e9817479d389a4f9774f3f0cbe1bf3884d80fd5934"dependencies = [ "displaydoc", "icu_locid", "icu_provider_macros", "stable_deref_trait", "tinystr", "writeable", "yoke", "zerofrom", "zerovec",]
[[package]]name = "icu_provider_macros"version = "1.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2060258edfcfe32ca7058849bf0f146cb5c59aadbedf480333c0d0002f97bc99"dependencies = [ "proc-macro2", "quote", "syn 2.0.31",]
[[package]]name = "ident_case"version = "1.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
[[package]]name = "instant"version = "0.1.12"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c"dependencies = [ "cfg-if",]
[[package]]name = "is-terminal"version = "0.4.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cb0889898416213fab133e1d33a0e5858a48177452750691bde3666d0fdbaf8b"dependencies = [ "hermit-abi 0.3.2", "rustix", "windows-sys 0.48.0",]
[[package]]name = "itertools"version = "0.10.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473"dependencies = [ "either",]
[[package]]name = "itoa"version = "1.0.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38"
[[package]]name = "js-sys"version = "0.3.64"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c5f195fe497f702db0f318b07fdd68edb16955aed830df8363d837542f8f935a"dependencies = [ "wasm-bindgen",]
[[package]]name = "lazy_static"version = "1.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]name = "libc"version = "0.2.147"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3"
[[package]]name = "linux-raw-sys"version = "0.4.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1a9bad9f94746442c783ca431b22403b519cd7fbeed0533fdd6328b2f2212128"
[[package]]name = "litemap"version = "0.7.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "77a1a2647d5b7134127971a6de0d533c49de2159167e7f259c427195f87168a1"
[[package]]name = "log"version = "0.4.20"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f"
[[package]]name = "memchr"version = "2.6.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8f232d6ef707e1956a43342693d2a31e72989554d58299d7a88738cc95b0d35c"
[[package]]name = "memoffset"version = "0.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5a634b1c61a95585bd15607c6ab0c4e5b226e695ff2800ba0cdccddf208c406c"dependencies = [ "autocfg",]
[[package]]name = "normalize-line-endings"version = "0.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be"
[[package]]name = "num-traits"version = "0.2.16"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f30b0abd723be7e2ffca1272140fac1a2f084c77ec3e123c192b66af1ee9e6c2"dependencies = [ "autocfg",]
[[package]]name = "num_cpus"version = "1.16.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43"dependencies = [ "hermit-abi 0.3.2", "libc",]
[[package]]name = "once_cell"version = "1.18.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
[[package]]name = "oorandom"version = "11.1.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575"
[[package]]name = "ordered-float"version = "3.9.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2a54938017eacd63036332b4ae5c8a49fc8c0c1d6d629893057e4f13609edd06"dependencies = [ "num-traits",]
[[package]]name = "phf"version = "0.11.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ade2d8b8f33c7333b51bcf0428d37e217e9f32192ae4772156f65063b8ce03dc"dependencies = [ "phf_shared",]
[[package]]name = "phf_codegen"version = "0.11.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e8d39688d359e6b34654d328e262234662d16cc0f60ec8dcbe5e718709342a5a"dependencies = [ "phf_generator", "phf_shared",]
[[package]]name = "phf_generator"version = "0.11.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "48e4cc64c2ad9ebe670cb8fd69dd50ae301650392e81c05f9bfcb2d5bdbc24b0"dependencies = [ "phf_shared", "rand",]
[[package]]name = "phf_shared"version = "0.11.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "90fcb95eef784c2ac79119d1dd819e162b5da872ce6f3c3abe1e8ca1c082f72b"dependencies = [ "siphasher",]
[[package]]name = "plotters"version = "0.3.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d2c224ba00d7cadd4d5c660deaf2098e5e80e07846537c51f9cfa4be50c1fd45"dependencies = [ "num-traits", "plotters-backend", "plotters-svg", "wasm-bindgen", "web-sys",]
[[package]]name = "plotters-backend"version = "0.3.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9e76628b4d3a7581389a35d5b6e2139607ad7c75b17aed325f210aa91f4a9609"
[[package]]name = "plotters-svg"version = "0.3.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "38f6d39893cca0701371e3c27294f09797214b86f1fb951b89ade8ec04e2abab"dependencies = [ "plotters-backend",]
[[package]]name = "ppv-lite86"version = "0.2.17"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"
[[package]]name = "predicates"version = "3.0.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "09963355b9f467184c04017ced4a2ba2d75cbcb4e7462690d388233253d4b1a9"dependencies = [ "anstyle", "difflib", "float-cmp", "itertools", "normalize-line-endings", "predicates-core", "regex",]
[[package]]name = "predicates-core"version = "1.0.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b794032607612e7abeb4db69adb4e33590fa6cf1149e95fd7cb00e634b92f174"
[[package]]name = "predicates-tree"version = "1.0.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "368ba315fb8c5052ab692e68a0eefec6ec57b23a36959c14496f0b0df2c0cecf"dependencies = [ "predicates-core", "termtree",]
[[package]]name = "proc-macro2"version = "1.0.66"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "18fb31db3f9bddb2ea821cde30a9f70117e3f119938b5ee630b7403aa6e2ead9"dependencies = [ "unicode-ident",]
[[package]]name = "quote"version = "1.0.33"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae"dependencies = [ "proc-macro2",]
[[package]]name = "rand"version = "0.8.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"dependencies = [ "libc", "rand_chacha", "rand_core",]
[[package]]name = "rand_chacha"version = "0.3.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"dependencies = [ "ppv-lite86", "rand_core",]
[[package]]name = "rand_core"version = "0.6.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"dependencies = [ "getrandom",]
[[package]]name = "rayon"version = "1.7.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1d2df5196e37bcc87abebc0053e20787d73847bb33134a69841207dd0a47f03b"dependencies = [ "either", "rayon-core",]
[[package]]name = "rayon-core"version = "1.11.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4b8f95bd6966f5c87776639160a66bd8ab9895d9d4ab01ddba9fc60661aebe8d"dependencies = [ "crossbeam-channel", "crossbeam-deque", "crossbeam-utils", "num_cpus",]
[[package]]name = "redox_syscall"version = "0.3.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29"dependencies = [ "bitflags 1.3.2",]
[[package]]name = "regex"version = "1.9.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "697061221ea1b4a94a624f67d0ae2bfe4e22b8a17b6a192afb11046542cc8c47"dependencies = [ "aho-corasick", "memchr", "regex-automata", "regex-syntax",]
[[package]]name = "regex-automata"version = "0.3.8"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c2f401f4955220693b56f8ec66ee9c78abffd8d1c4f23dc41a23839eb88f0795"dependencies = [ "aho-corasick", "memchr", "regex-syntax",]
[[package]]name = "regex-syntax"version = "0.7.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "dbb5fb1acd8a1a18b3dd5be62d25485eb770e05afb408a9627d14d451bae12da"
[[package]]name = "rustix"version = "0.38.12"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "bdf14a7a466ce88b5eac3da815b53aefc208ce7e74d1c263aabb04d88c4abeb1"dependencies = [ "bitflags 2.4.0", "errno", "libc", "linux-raw-sys", "windows-sys 0.48.0",]
[[package]]name = "ryu"version = "1.0.15"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741"
[[package]]name = "same-file"version = "1.0.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"dependencies = [ "winapi-util",]
[[package]]name = "scopeguard"version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]name = "serde"version = "1.0.188"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cf9e0fcba69a370eed61bcf2b728575f726b50b55cba78064753d708ddc7549e"dependencies = [ "serde_derive",]
[[package]]name = "serde_cbor"version = "0.11.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2bef2ebfde456fb76bbcf9f59315333decc4fda0b2b44b420243c11e0f5ec1f5"dependencies = [ "half", "serde",]
[[package]]name = "serde_derive"version = "1.0.188"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2"dependencies = [ "proc-macro2", "quote", "syn 2.0.31",]
[[package]]name = "serde_json"version = "1.0.107"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6b420ce6e3d8bd882e9b243c6eed35dbc9a6110c9769e74b584e0d68d1f20c65"dependencies = [ "itoa", "ryu", "serde",]
[[package]]name = "shell-words"version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "24188a676b6ae68c3b2cb3a01be17fbf7240ce009799bb56d5b1409051e78fde"
[[package]]name = "siphasher"version = "0.3.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d"
[[package]]name = "smallvec"version = "1.11.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "942b4a808e05215192e39f4ab80813e599068285906cc91aa64f923db842bd5a"
[[package]]name = "stable_deref_trait"version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"
[[package]]name = "strsim"version = "0.10.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
[[package]]name = "syn"version = "1.0.109"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"dependencies = [ "proc-macro2", "quote", "unicode-ident",]
[[package]]name = "syn"version = "2.0.31"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "718fa2415bcb8d8bd775917a1bf12a7931b6dfa890753378538118181e0cb398"dependencies = [ "proc-macro2", "quote", "unicode-ident",]
[[package]]name = "synstructure"version = "0.13.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "285ba80e733fac80aa4270fbcdf83772a79b80aa35c97075320abfee4a915b06"dependencies = [ "proc-macro2", "quote", "syn 2.0.31", "unicode-xid",]
[[package]]name = "tempfile"version = "3.8.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cb94d2f3cc536af71caac6b6fcebf65860b347e7ce0cc9ebe8f70d3e521054ef"dependencies = [ "cfg-if", "fastrand", "redox_syscall", "rustix", "windows-sys 0.48.0",]
[[package]]name = "termcolor"version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "be55cf8942feac5c765c2c993422806843c9a9a45d4d5c407ad6dd2ea95eb9b6"dependencies = [ "winapi-util",]
[[package]]name = "termtree"version = "0.4.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3369f5ac52d5eb6ab48c6b4ffdc8efbcad6b89c765749064ba298f2c68a16a76"
[[package]]name = "textwrap"version = "0.11.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060"dependencies = [ "unicode-width",]
[[package]]name = "thiserror"version = "1.0.49"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1177e8c6d7ede7afde3585fd2513e611227efd6481bd78d2e82ba1ce16557ed4"dependencies = [ "thiserror-impl",]
[[package]]name = "thiserror-impl"version = "1.0.49"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "10712f02019e9288794769fba95cd6847df9874d49d871d062172f9dd41bc4cc"dependencies = [ "proc-macro2", "quote", "syn 2.0.31",]
[[package]]name = "time"version = "0.3.20"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cd0cbfecb4d19b5ea75bb31ad904eb5b9fa13f21079c3b92017ebdf4999a5890"dependencies = [ "serde", "time-core",]
[[package]]name = "time-core"version = "0.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2e153e1f1acaef8acc537e68b44906d2db6436e2b35ac2c6b42640fff91f00fd"
[[package]]name = "tinystr"version = "0.7.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d5d0e245e80bdc9b4e5356fc45a72184abbc3861992603f515270e9340f5a219"dependencies = [ "displaydoc", "zerovec",]
[[package]]name = "tinytemplate"version = "1.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc"dependencies = [ "serde", "serde_json",]
[[package]]name = "unicode-ident"version = "1.0.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "301abaae475aa91687eb82514b328ab47a211a533026cb25fc3e519b86adfc3c"
[[package]]name = "unicode-width"version = "0.1.10"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b"
[[package]]name = "unicode-xid"version = "0.2.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f962df74c8c05a667b5ee8bcf162993134c104e96440b663c8daa176dc772d8c"
[[package]]name = "unicode_names2"version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "38b2c0942619ae1797f999a0ce7efc6c09592ad30e68e16cdbfdcd48a98c3579"dependencies = [ "phf", "unicode_names2_generator",]
[[package]]name = "unicode_names2_generator"version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4d0d66ab60be9799a70f8eb227ea43da7dcc47561dd9102cbadacfe0930113f7"dependencies = [ "getopts", "log", "phf_codegen", "rand", "time",]
[[package]]name = "utf16_iter"version = "1.0.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "52df8b7fb78e7910d776fccf2e42ceaf3604d55e8e7eb2dbd183cb1441d8a692"
[[package]]name = "utf8_iter"version = "1.0.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "64a8922555b9500e3d865caed19330172cd67cbf82203f1a3311d8c305cc9f33"
[[package]]name = "utf8parse"version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a"
[[package]]name = "version_check"version = "0.9.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
[[package]]name = "wait-timeout"version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9f200f5b12eb75f8c1ed65abd4b2db8a6e1b138a20de009dacee265a2498f3f6"dependencies = [ "libc",]
[[package]]name = "walkdir"version = "2.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d71d857dc86794ca4c280d616f7da00d2dbfd8cd788846559a6813e6aa4b54ee"dependencies = [ "same-file", "winapi-util",]
[[package]]name = "wasi"version = "0.11.0+wasi-snapshot-preview1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]name = "wasm-bindgen"version = "0.2.87"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7706a72ab36d8cb1f80ffbf0e071533974a60d0a308d01a5d0375bf60499a342"dependencies = [ "cfg-if", "wasm-bindgen-macro",]
[[package]]name = "wasm-bindgen-backend"version = "0.2.87"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5ef2b6d3c510e9625e5fe6f509ab07d66a760f0885d858736483c32ed7809abd"dependencies = [ "bumpalo", "log", "once_cell", "proc-macro2", "quote", "syn 2.0.31", "wasm-bindgen-shared",]
[[package]]name = "wasm-bindgen-macro"version = "0.2.87"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "dee495e55982a3bd48105a7b947fd2a9b4a8ae3010041b9e0faab3f9cd028f1d"dependencies = [ "quote", "wasm-bindgen-macro-support",]
[[package]]name = "wasm-bindgen-macro-support"version = "0.2.87"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b"dependencies = [ "proc-macro2", "quote", "syn 2.0.31", "wasm-bindgen-backend", "wasm-bindgen-shared",]
[[package]]name = "wasm-bindgen-shared"version = "0.2.87"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1"
[[package]]name = "web-sys"version = "0.3.64"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9b85cbef8c220a6abc02aefd892dfc0fc23afb1c6a426316ec33253a3877249b"dependencies = [ "js-sys", "wasm-bindgen",]
[[package]]name = "winapi"version = "0.3.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu",]
[[package]]name = "winapi-i686-pc-windows-gnu"version = "0.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]name = "winapi-util"version = "0.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178"dependencies = [ "winapi",]
[[package]]name = "winapi-x86_64-pc-windows-gnu"version = "0.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]name = "windows-sys"version = "0.45.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"dependencies = [ "windows-targets 0.42.2",]
[[package]]name = "windows-sys"version = "0.48.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"dependencies = [ "windows-targets 0.48.5",]
[[package]]name = "windows-targets"version = "0.42.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"dependencies = [ "windows_aarch64_gnullvm 0.42.2", "windows_aarch64_msvc 0.42.2", "windows_i686_gnu 0.42.2", "windows_i686_msvc 0.42.2", "windows_x86_64_gnu 0.42.2", "windows_x86_64_gnullvm 0.42.2", "windows_x86_64_msvc 0.42.2",]
[[package]]name = "windows-targets"version = "0.48.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"dependencies = [ "windows_aarch64_gnullvm 0.48.5", "windows_aarch64_msvc 0.48.5", "windows_i686_gnu 0.48.5", "windows_i686_msvc 0.48.5", "windows_x86_64_gnu 0.48.5", "windows_x86_64_gnullvm 0.48.5", "windows_x86_64_msvc 0.48.5",]
[[package]]name = "windows_aarch64_gnullvm"version = "0.42.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"
[[package]]name = "windows_aarch64_gnullvm"version = "0.48.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
[[package]]name = "windows_aarch64_msvc"version = "0.42.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"
[[package]]name = "windows_aarch64_msvc"version = "0.48.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
[[package]]name = "windows_i686_gnu"version = "0.42.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"
[[package]]name = "windows_i686_gnu"version = "0.48.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
[[package]]name = "windows_i686_msvc"version = "0.42.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"
[[package]]name = "windows_i686_msvc"version = "0.48.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
[[package]]name = "windows_x86_64_gnu"version = "0.42.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"
[[package]]name = "windows_x86_64_gnu"version = "0.48.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
[[package]]name = "windows_x86_64_gnullvm"version = "0.42.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"
[[package]]name = "windows_x86_64_gnullvm"version = "0.48.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
[[package]]name = "windows_x86_64_msvc"version = "0.42.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"
[[package]]name = "windows_x86_64_msvc"version = "0.48.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
[[package]]name = "write16"version = "1.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936"
[[package]]name = "writeable"version = "0.5.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c0af0c3d13faebf8dda0b5256fa7096a2d5ccb662f7b9f54a40fe201077ab1c2"
[[package]]name = "yoke"version = "0.7.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "61e38c508604d6bbbd292dadb3c02559aa7fff6b654a078a36217cad871636e4"dependencies = [ "serde", "stable_deref_trait", "yoke-derive", "zerofrom",]
[[package]]name = "yoke-derive"version = "0.7.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d5e19fb6ed40002bab5403ffa37e53e0e56f914a4450c8765f533018db1db35f"dependencies = [ "proc-macro2", "quote", "syn 2.0.31", "synstructure",]
[[package]]name = "zerofrom"version = "0.1.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "655b0814c5c0b19ade497851070c640773304939a6c0fd5f5fb43da0696d05b7"dependencies = [ "zerofrom-derive",]
[[package]]name = "zerofrom-derive"version = "0.1.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e6a647510471d372f2e6c2e6b7219e44d8c574d24fdc11c610a61455782f18c3"dependencies = [ "proc-macro2", "quote", "syn 2.0.31", "synstructure",]
[[package]]name = "zeroize"version = "1.6.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2a0956f1ba7c7909bfb66c2e9e4124ab6f6482560f6628b5aaeba39207c9aad9"
[[package]]name = "zerovec"version = "0.10.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1194130c5b155bf8ae50ab16c86ab758cd695cf9ad176d2f870b744cbdbb572e"dependencies = [ "yoke", "zerofrom", "zerovec-derive",]
[[package]]name = "zerovec-derive"version = "0.10.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "acabf549809064225ff8878baedc4ce3732ac3b07e7c7ce6e5c2ccdbc485c324"dependencies = [ "proc-macro2", "quote", "syn 2.0.31",]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970[package]name = "charset-normalizer-rs"version = "1.0.6"authors = ["Nikolay Yarovoy <nikolay.yarovoy@gmail.com>"]edition = "2021"description = "Truly universal encoding detector in pure Rust - port of Python version"license-file = "LICENSE"documentation = "https://docs.rs/charset-normalizer-rs"readme = "README.md"repository = "https://github.com/nickspring/charset-normalizer-rs"keywords = ["encoding", "charset", "detector", "conversion", "normalizer"]categories = ["encoding", "internationalization", "localization"]exclude = [ "/src/tests/data/**", "/CONTRIBUTING.md", "/CODE_OF_CONDUCT.md", "/.github/**", ".gitattributes"]
[dependencies]ahash = "0.8.3"bitflags = "2.4.0"cached = "0.46.0"chardet = { version = "0.2.4", optional = true }chardetng = { version = "0.1.17", optional = true }clap = { version = "4.4.2", features = ["derive"] }counter = "0.5.7"dialoguer = "0.10.4"encoding = "0.2.33"env_logger = "0.10.0"icu_normalizer = "1.3.2"icu_properties = "1.3.2"log = "0.4.20"once_cell = "1.18.0"ordered-float = "3.9.1"regex = "1.9.3"serde = { version = "1.0.188", features = ["derive"] }serde_json = "1.0.107"strsim = "0.10.0"unicode_names2 = "1.1.0"
[dev-dependencies]assert_cmd = "2.0.12"criterion = "0.3"predicates = "3.0.3"
[[bench]]name = "large_payload"harness = false
[[bench]]name = "large_datasets"harness = false
[features]performance = ["chardet", "chardetng"]
[[bin]]name = "performance"path = "src/performance.rs"required-features = ["performance"]
[[bin]]name = "normalizer"path = "src/normalizer.rs"
[profile.release]opt-level = 3lto = "fat"12345678910111213141516171819202122MIT License
Copyright (c) 2023 YAROVOY Nikolay (Rust version).Copyright (c) 2019 TAHRI Ahmed R. (author of original Python version)
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199# Charset Normalizer[![charset-normalizer-rs on docs.rs][docsrs-image]][docsrs][![charset-normalizer-rs on crates.io][crates-image]][crates]
[docsrs-image]: https://docs.rs/charset-normalizer-rs/badge.svg[docsrs]: https://docs.rs/charset-normalizer-rs[crates-image]: https://img.shields.io/crates/v/charset-normalizer-rs.svg[crates]: https://crates.io/crates/charset-normalizer-rs/
A library that helps you read text from an unknown charset encoding.<br /> Motivated by original Python version of `charset-normalizer`,I'm trying to resolve the issue by taking a new approach.All IANA character set names for which the Rust `encoding` library provides codecs are supported.
This project is port of original Pyhon version of [Charset Normalizer](https://github.com/Ousret/charset_normalizer).The biggest difference between Python and Rust versions - number of supported encodings as each langauge has own encoding / decoding library.In Rust version only encoding from [WhatWG standard](https://encoding.spec.whatwg.org) are supported. Python version supports more encodings, but a lot of them are old almost unused ones.
## ⚡ Performance
This package offer better performance than Python version (4 times faster, than MYPYC version of charset-normalizer, 8 times faster than usual Python version).In comparison with `chardet` and `chardetng` packages it has approximately the same speed but more accurate. Here are some numbers.
| Package | Accuracy | Mean per file (ms) | File per sec (est) ||---------------------------------------------------------------------------------------------|:----------:|:------------------:|:------------------:|| [chardet](https://crates.io/crates/chardet) | 82.6 % | 3 ms | 333 file/sec || [chardetng](https://crates.io/crates/chardetng) | 90.7 % | 1.6 ms | 625 file/sec || charset-normalizer-rs | **97.1 %** | **1.5 ms** | 666 file/sec || [charset-normalizer](https://github.com/Ousret/charset_normalizer) (Python + MYPYC version) | **98 %** | **8 ms** | 125 file/sec |
| Package | 99th percentile | 95th percentile | 50th percentile ||---------------------------------------------------------------------------------------------|:---------------:|:---------------:|:---------------:|| [chardet](https://crates.io/crates/chardet) | 8 ms | 2 ms | 0.2 ms || [chardetng](https://crates.io/crates/chardetng) | 14 ms | 5 ms | 0.5 ms || charset-normalizer-rs | 12 ms | 5 ms | 0.7 ms || [charset-normalizer](https://github.com/Ousret/charset_normalizer) (Python + MYPYC version) | 94 ms | 37 ms | 3 ms |
Stats are generated using 400+ files using default parameters. These results might change at any time. The dataset can be updated to include more files. The actual delays heavily depends on your CPU capabilities. The factors should remain the same. Rust version dataset has been reduced as number of supported encodings is lower than in Python version.
There is a still possibility to speed up library, so I'll appreciate any contributions.
## ✨ Installation
Library installation:
```consolecargo add charset-normalizer-rs```
Binary CLI tool installation:```consolecargo install charset-normalizer-rs```
## 🚀 Basic Usage
### CLIThis package comes with a CLI, which supposes to be compatible with Python version CLI tool.
```consolenormalizer -hUsage: normalizer [OPTIONS] <FILES>...
Arguments: <FILES>... File(s) to be analysed
Options: -v, --verbose Display complementary information about file if any. Stdout will contain logs about the detection process -a, --with-alternative Output complementary possibilities if any. Top-level JSON WILL be a list -n, --normalize Permit to normalize input file. If not set, program does not write anything -m, --minimal Only output the charset detected to STDOUT. Disabling JSON output -r, --replace Replace file when trying to normalize it instead of creating a new one -f, --force Replace file without asking if you are sure, use this flag with caution -t, --threshold <THRESHOLD> Define a custom maximum amount of chaos allowed in decoded content. 0. <= chaos <= 1 [default: 0.2] -h, --help Print help -V, --version Print version```
```bashnormalizer ./data/sample.1.fr.srt```
🎉 The CLI produces easily usable stdout result in JSON format (should be the same as in Python version).
```json{ "path": "/home/default/projects/charset_normalizer/data/sample.1.fr.srt", "encoding": "cp1252", "encoding_aliases": [ "1252", "windows_1252" ], "alternative_encodings": [ "cp1254", "cp1256", "cp1258", "iso8859_14", "iso8859_15", "iso8859_16", "iso8859_3", "iso8859_9", "latin_1", "mbcs" ], "language": "French", "alphabets": [ "Basic Latin", "Latin-1 Supplement" ], "has_sig_or_bom": false, "chaos": 0.149, "coherence": 97.152, "unicode_path": null, "is_preferred": true}```
### Rust
Library offers two main methods. First one is `from_bytes`, which processes text using bytes as input parameter:```rustuse charset_normalizer_rs::from_bytes;
fn test_from_bytes() { let result = from_bytes(&vec![0x84, 0x31, 0x95, 0x33], None); let best_guess = result.get_best(); assert_eq!( best_guess.unwrap().encoding(), "gb18030", );}test_from_bytes();```
`from_path` processes text using filename as input parameter:```rustuse std::path::PathBuf;use charset_normalizer_rs::from_path;
fn test_from_path() { let result = from_path(&PathBuf::from("src/tests/data/samples/sample-chinese.txt"), None).unwrap(); let best_guess = result.get_best(); assert_eq!( best_guess.unwrap().encoding(), "big5", );}test_from_path();```
## 😇 Why
When I started using Chardet (Python version), I noticed that it was not suited to my expectations, and I wanted to propose areliable alternative using a completely different method. Also! I never back down on a good challenge!
I **don't care** about the **originating charset** encoding, because **two different tables** canproduce **two identical rendered string.**What I want is to get readable text, the best I can.
In a way, **I'm brute forcing text decoding.** How cool is that? 😎
## 🍰 How
- Discard all charset encoding table that could not fit the binary content. - Measure noise, or the mess once opened (by chunks) with a corresponding charset encoding. - Extract matches with the lowest mess detected. - Additionally, we measure coherence / probe for a language.
**Wait a minute**, what is noise/mess and coherence according to **YOU?**
*Noise :* I opened hundred of text files, **written by humans**, with the wrong encoding table. **I observed**, then**I established** some ground rules about **what is obvious** when **it seems like** a mess. I know that my interpretation of what is noise is probably incomplete, feel free to contribute in order to improve or rewrite it.
*Coherence :* For each language there is on earth, we have computed ranked letter appearance occurrences (the best we can). So I thoughtthat intel is worth something here. So I use those records against decoded text to check if I can detect intelligent design.
## ⚡ Known limitations
- Language detection is unreliable when text contains two or more languages sharing identical letters. (eg. HTML (english tags) + Turkish content (Sharing Latin characters)) - Every charset detector heavily depends on sufficient content. In common cases, do not bother run detection on very tiny content.
## 👤 Contributing
Contributions, issues and feature requests are very much welcome.<br />Feel free to check [issues page](https://github.com/nickspring/charset-normalizer-rs/issues) if you want to contribute.
## 📝 License
Copyright © [Nikolay Yarovoy @nickspring](https://github.com/nickspring) - porting to Rust. <br />Copyright © [Ahmed TAHRI @Ousret](https://github.com/Ousret) - original Python version and some parts of this document.<br />This project is [MIT](https://github.com/nickspring/charset-normalizer-rs/blob/master/LICENSE) licensed.
Characters frequencies used in this project © 2012 [Denny Vrandečić](http://simia.net/letters/)
12345678910111213141516171819202122232425262728293031use charset_normalizer_rs::from_path;use charset_normalizer_rs::utils::get_large_test_datasets;use criterion::BenchmarkId;use criterion::{black_box, criterion_group, criterion_main, Criterion};use std::path::PathBuf;
fn bench_foo(paths: &[String]) { for path in paths { let _ = from_path(&PathBuf::from(path), None); }}
pub fn large_datasets(c: &mut Criterion) { let paths: Vec<String> = get_large_test_datasets() .unwrap() .iter() .map(|v| v.0.clone()) .collect();
let mut group = c.benchmark_group("sample-size-example"); group.significance_level(0.1).sample_size(10); group.bench_with_input(BenchmarkId::new("large_datasets", ""), &paths, |b, s| { b.iter(|| { bench_foo(s); black_box(()) }); });}
criterion_group!(benches, large_datasets);criterion_main!(benches);123456789101112131415161718use charset_normalizer_rs::consts::TOO_BIG_SEQUENCE;use charset_normalizer_rs::from_bytes;use criterion::BenchmarkId;use criterion::{black_box, criterion_group, criterion_main, Criterion};
pub fn large_payload(c: &mut Criterion) { let mut payload = b"hello simple ascii " .repeat(TOO_BIG_SEQUENCE) .as_slice() .to_vec(); payload.extend("我没有埋怨,磋砣的只是一些时间。 磋砣的只是一些时间。".as_bytes()); c.bench_with_input(BenchmarkId::new("large_payload", ""), &payload, |b, s| { b.iter(|| black_box(from_bytes(s, None))); });}
criterion_group!(benches, large_payload);criterion_main!(benches);12[toolchain]channel = "1.77.1"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566use crate::entity::Language;use ahash::HashMap;
use once_cell::sync::Lazy;use std::iter::FromIterator;
pub(crate) static LANGUAGES: Lazy<[(Language, &'static str, bool, bool); 41]> = Lazy::new(|| { [ // language, alphabet, have_accents, pure_latin (Language::English, "eationsrhldcmufpgwbyvkjxzq", false, true, ), (Language::English, "eationsrhldcumfpgwybvkxjzq", false, true, ), (Language::German, "enirstadhulgocmbfkwzpvüäöj", true, true, ), (Language::French, "easnitrluodcpmévgfbhqàxèyj", true, true, ), (Language::Dutch, "enairtodslghvmukcpbwjzfyxë", true, true, ), (Language::Italian, "eiaonltrscdupmgvfbzhqèàkyò", true, true, ), (Language::Polish, "aioenrzwsctkydpmuljłgbhąęó", true, true, ), (Language::Spanish, "eaonsrildtcumpbgvfyóhqíjzá", true, true, ), (Language::Russian, "оаеинстрвлкмдпугяызбйьчхжц", false, false, ), (Language::Japanese, "人一大亅丁丨竹笑口日今二彳行十土丶寸寺時乙丿乂气気冂巾亠市目儿見八小凵県月彐門間木東山出本中刀分耳又取最言田心思刂前京尹事生厶云会未来白冫楽灬馬尸尺駅明耂者了阝都高卜占厂广店子申奄亻俺上方冖学衣艮食自", false, false, ), (Language::Japanese, "ーンス・ルトリイアラックドシレジタフロカテマィグバムプオコデニウメサビナブャエュチキズダパミェョハセベガモツネボソノァヴワポペピケゴギザホゲォヤヒユヨヘゼヌゥゾヶヂヲヅヵヱヰヮヽ゠ヾヷヿヸヹヺ", false, false, ), (Language::Japanese, "のにるたとはしいをでてがなれからさっりすあもこまうくよきんめおけそつだやえどわちみせじばへびずろほげむべひょゆぶごゃねふぐぎぼゅづざぞぬぜぱぽぷぴぃぁぇぺゞぢぉぅゐゝゑ゛゜ゎゔ゚ゟ゙ゕゖ", false, false, ), (Language::Portuguese, "aeosirdntmuclpgvbfhãqéçází", true, true, ), (Language::Swedish, "eanrtsildomkgvhfupäcböåyjx", true, true, ), (Language::Chinese, "的一是不了在人有我他这个们中来上大为和国地到以说时要就出会可也你对生能而子那得于着下自之年过发后作里用道行所然家种事成方多经么去法学如都同现当没动面起看定天分还进好小部其些主样理心她本前开但因只从想实", false, false, ), (Language::Ukrainian, "оаніирвтесклудмпзяьбгйчхцї", false, false, ), (Language::Norwegian, "erntasioldgkmvfpubhåyjøcæw", false, true, ), (Language::Finnish, "aintesloukämrvjhpydögcbfwz", true, true, ), (Language::Vietnamese, "nhticgaoumlràđsevpbyưdákộế", true, true, ), (Language::Czech, "oeantsilvrkdumpíchzáyjběéř", true, true, ), (Language::Hungarian, "eatlsnkriozáégmbyvdhupjöfc", true, true, ), (Language::Korean, "이다에의는로하을가고지서한은기으년대사시를리도인스일", false, false, ), (Language::Indonesian, "aneirtusdkmlgpbohyjcwfvzxq", false, true, ), (Language::Turkish, "aeinrlıkdtsmyuobüşvgzhcpçğ", true, true, ), (Language::Romanian, "eiarntulocsdpmăfvîgbșțzhâj", true, true, ), (Language::Farsi, "ایردنهومتبسلکشزفگعخقجآپحطص", false, false, ), (Language::Arabic, "اليمونرتبةعدسفهكقأحجشطصىخإ", false, false, ), (Language::Danish, "erntaisdlogmkfvubhpåyøæcjw", false, true, ), (Language::Serbian, "аиоенрсуткјвдмплгзбaieonцш", false, false, ), (Language::Lithuanian, "iasoretnukmlpvdjgėbyųšžcąį", false, true, ), (Language::Slovene, "eaionrsltjvkdpmuzbghčcšžfy", false, true, ), (Language::Slovak, "oaenirvtslkdmpuchjbzáyýíčé", true, true, ), (Language::Hebrew, "יוהלרבתמאשנעםדקחפסכגטצןזך", false, false, ), (Language::Bulgarian, "аиоентрсвлкдпмзгяъубчцйжщх", false, false, ), (Language::Croatian, "aioenrjstuklvdmpgzbcčhšžćf", true, true, ), (Language::Hindi, "करसनतमहपयलवजदगबशटअएथभडचधषइ", false, false, ), (Language::Estonian, "aiestlunokrdmvgpjhäbõüfcöy", true, true, ), (Language::Thai, "านรอกเงมยลวดทสตะปบคหแจพชขใ", false, false, ), (Language::Greek, "ατοιενρσκηπςυμλίόάγέδήωχθύ", false, false, ), (Language::Tamil, "கதபடரமலனவறயளசநஇணஅஆழஙஎஉஒஸ", false, false, ), (Language::Kazakh, "аыентрлідсмқкобиуғжңзшйпгө", false, false, ),]});pub(crate) static LANGUAGE_SUPPORTED_COUNT: Lazy<usize> = Lazy::new(|| LANGUAGES.len()); // 41
pub(crate) static ENCODING_TO_LANGUAGE: Lazy<HashMap<&'static str, Language>> = Lazy::new(|| { HashMap::from_iter([ ("euc-kr", Language::Korean), ("big5", Language::Chinese), ("hz", Language::Chinese), ("gbk", Language::Chinese), ("gb18030", Language::Chinese), ("euc-jp", Language::Japanese), ("iso-2022-jp", Language::Japanese), ("shift_jis", Language::Japanese), ])});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252#![allow(unused_variables)]use crate::assets::{ENCODING_TO_LANGUAGE, LANGUAGES, LANGUAGE_SUPPORTED_COUNT};use crate::consts::TOO_SMALL_SEQUENCE;use crate::entity::{CoherenceMatch, CoherenceMatches, Language};use crate::utils::{ get_language_data, is_accentuated, is_multi_byte_encoding, is_suspiciously_successive_range, is_unicode_range_secondary, unicode_range,};use ahash::{HashMap, HashMapExt, HashSet};use cached::proc_macro::cached;use counter::Counter;use encoding::label::encoding_from_whatwg_label;use encoding::DecoderTrap;use ordered_float::OrderedFloat;use strsim::jaro;
//// Coherence detection module//
// Return associated unicode ranges in a single byte code page.pub(crate) fn encoding_unicode_range(iana_name: &str) -> Result<Vec<&str>, String> { if is_multi_byte_encoding(iana_name) { return Err("Function not supported on multi-byte code page".to_string()); } let encoder = encoding_from_whatwg_label(iana_name) .ok_or("No decoder found for this encoding".to_string())?;
let byte_range = 0x40..0xFF; // utf8 range. range.len()==191 let mut result: HashMap<&str, u8> = HashMap::with_capacity(byte_range.len());
byte_range.for_each(|i| { if let Some(range) = encoder .decode(&[i], DecoderTrap::Ignore) .ok() .and_then(|chunk| chunk.chars().next()) .and_then(unicode_range) .filter(|&range| !is_unicode_range_secondary(range)) { *result.entry(range).or_insert(0) += 1; } }); let character_count: u8 = result.values().sum(); let threshold = 0.15; let mut result: Vec<&str> = result .iter() .filter(|(_, &value)| (value as f32 / character_count as f32) >= threshold) .map(|(&name, _)| name) .collect(); result.sort_unstable(); Ok(result)}
// Return inferred languages used with a unicode range.pub(crate) fn unicode_range_languages(primary_range: &str) -> Vec<&'static Language> { LANGUAGES .iter() .filter_map(|(language, characters, _, _)| { characters .chars() .find(|char| unicode_range(*char).unwrap_or_default() == primary_range) .map(|_| language) }) .collect::<Vec<&Language>>()}
// Single-byte encoding language association.// Some code page are heavily linked to particular language(s).// This function does the correspondence.#[cached(size = 128)]pub(crate) fn encoding_languages(iana_name: String) -> Vec<&'static Language> { match encoding_unicode_range(&iana_name) .unwrap_or_default() .iter() .find(|&&range| !range.contains("Latin")) { Some(&range) => unicode_range_languages(range), None => vec![&Language::Unknown], }}
// Multi-byte encoding language association. Some code page are heavily linked to particular language(s).// This function does the correspondence.pub(crate) fn mb_encoding_languages(iana_name: &str) -> Vec<&'static Language> { ENCODING_TO_LANGUAGE .get(iana_name) .map_or(vec![], |found| vec![found])}
// Return associated languages associated to given characters#[allow(clippy::ptr_arg)]pub(crate) fn alphabet_languages( characters: &[char], ignore_non_latin: bool,) -> Vec<&'static Language> { let mut languages: Vec<(&Language, f32)> = Vec::with_capacity(*LANGUAGE_SUPPORTED_COUNT); let source_characters_set: HashSet<char> = characters.iter().copied().collect(); let source_has_accents = source_characters_set .iter() .any(|&char| is_accentuated(char));
for (language, language_characters, target_have_accents, target_pure_latin) in LANGUAGES.iter() { if (ignore_non_latin && !target_pure_latin) || (!target_have_accents && source_has_accents) { continue; }
let language_characters_set: HashSet<char> = language_characters.chars().collect(); let intersection: HashSet<char> = language_characters_set .intersection(&source_characters_set) .copied() .collect();
let ratio: f32 = intersection.len() as f32 / language_characters_set.len() as f32; if ratio >= 0.2 { languages.push((language, ratio)); } } // reverse sort languages.sort_unstable_by(|&a, &b| b.1.partial_cmp(&a.1).unwrap()); languages.iter().map(|&lang| lang.0).collect()}
// Given a decoded text sequence, return a list of str. Unicode range / alphabet separation.// Ex. a text containing English/Latin with a bit a Hebrew will return two items in the resulting list;// One containing the latin letters and the other hebrew.pub(crate) fn alpha_unicode_split(decoded_sequence: &str) -> Vec<String> { let mut layers: HashMap<&str, String> = HashMap::new();
for ch in decoded_sequence.chars().filter(|c| c.is_alphabetic()) { if let Some(character_range) = unicode_range(ch) { let layer_key: &str = layers .keys() .find(|key| !is_suspiciously_successive_range(Some(key), Some(character_range))) .copied() .unwrap_or(character_range); let layer = layers.entry(layer_key).or_default(); layer.extend(ch.to_lowercase()); } } layers.into_values().collect()}
// Determine if a ordered characters list (by occurrence from most appearance to rarest) match a particular language.// The result is a ratio between 0. (absolutely no correspondence) and 1. (near perfect fit).// Beware that is function is not strict on the match in order to ease the detection. (Meaning close match is 1.)// Remark: ordered_characters is string here, with chars ordered by popularity.// Original function in Python was more complicated and slowerpub(crate) fn characters_popularity_compare( language: &Language, ordered_characters: &str,) -> Result<f32, String> { let language_data = get_language_data(language)?; Ok(jaro(ordered_characters, language_data.0) as f32)}
// We shall NOT return more than one "English" in CoherenceMatches because it is an alternative// of "English" (the same for Japan language). This function only keeps the best match.pub(crate) fn filter_alt_coherence_matches(results: &CoherenceMatches) -> CoherenceMatches { let mut index: HashMap<&Language, f32> = HashMap::with_capacity(results.len()); for result in results { let score = index.entry(result.language).or_default(); *score = result.score.max(*score); } index .into_iter() .map(|(language, score)| CoherenceMatch { language, score }) .collect()}
// This function merge results previously given by the function coherence_ratio.// The return type is the same as coherence_ratio.pub(crate) fn merge_coherence_ratios(results: &Vec<CoherenceMatches>) -> CoherenceMatches { let mut index: HashMap<&Language, Vec<f32>> = HashMap::with_capacity(results.len()); results .iter() .flatten() .for_each(|result| index.entry(result.language).or_default().push(result.score));
let mut merge: Vec<CoherenceMatch> = index .iter() .map(|(&lang, scores)| CoherenceMatch { language: lang, score: scores.iter().sum::<f32>() / (scores.len() as f32), }) .collect();
merge.sort_unstable_by(|a, b| b.score.partial_cmp(&a.score).unwrap()); merge}
// The main function. Detect ANY language that can be identified in given sequence.// The sequence will be analysed by layers.// A layer = Character extraction by alphabets/ranges.#[cached(size = 2048)]pub(crate) fn coherence_ratio( decoded_sequence: String, threshold: Option<OrderedFloat<f32>>, include_languages: Option<Vec<&'static Language>>,) -> Result<CoherenceMatches, String> { let threshold = f32::from(threshold.unwrap_or(OrderedFloat(0.1))); let mut include_languages: Vec<&Language> = include_languages.unwrap_or_default(); let ignore_non_latin = include_languages == vec![&Language::Unknown]; if ignore_non_latin { include_languages.clear(); }
let mut results: CoherenceMatches = vec![]; let mut sufficient_match_count: u64 = 0;
for layer in alpha_unicode_split(&decoded_sequence) { if layer.chars().count() <= TOO_SMALL_SEQUENCE { continue; } let most_common = layer.chars().collect::<Counter<_>>().most_common_ordered(); let popular_character_ordered: Vec<char> = most_common.iter().map(|(ch, _)| *ch).collect();
let languages = if include_languages.is_empty() { alphabet_languages(&popular_character_ordered, ignore_non_latin) } else { include_languages.clone() };
let popular_character_ordered_as_string: String = popular_character_ordered.iter().collect();
// Convert the String into a &str for language in languages { let ratio: f32 = characters_popularity_compare(language, &popular_character_ordered_as_string)?;
match ratio { r if r < threshold => continue, r if r >= 0.8 => sufficient_match_count += 1, _ => {} }
results.push(CoherenceMatch { language, score: ratio, });
if sufficient_match_count >= 3 { break; } } } results = filter_alt_coherence_matches(&results); results.sort_unstable_by(|a, b| b.score.partial_cmp(&a.score).unwrap()); Ok(results)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752use ahash::{HashMap, HashSet};use core::ops::RangeInclusive;use encoding::all::encodings;use once_cell::sync::Lazy;use regex::Regex;
pub static TOO_BIG_SEQUENCE: usize = 1_000_000; // 10E6pub(crate) static MAX_PROCESSED_BYTES: usize = 500_000;pub(crate) static TOO_SMALL_SEQUENCE: usize = 32;pub(crate) static UTF8_MAXIMAL_ALLOCATION: usize = 1_112_064;pub(crate) static COMMON_SAFE_ASCII_CHARACTERS: &'static str = "<>=:/&;{}[],|\"-";
// Contain for each eligible encoding a list of/item bytes SIG/BOMpub(crate) static ENCODING_MARKS: Lazy<HashMap<&'static str, &'static [u8]>> = Lazy::new(|| { HashMap::from_iter([ ("utf-8", b"\xef\xbb\xbf".as_slice()), ("gb18030", b"\x84\x31\x95\x33".as_slice()), ("utf-16le", b"\xff\xfe".as_slice()), ("utf-16be", b"\xfe\xff".as_slice()), ])});
pub(crate) static UNICODE_RANGES_COMBINED: Lazy<[(&'static str, RangeInclusive<u32>); 279]> = Lazy::new(|| { [ ("Control character", 0..=31), ("Basic Latin", 32..=127), ("Latin-1 Supplement", 128..=255), ("Latin Extended-A", 256..=383), ("Latin Extended-B", 384..=591), ("IPA Extensions", 592..=687), ("Spacing Modifier Letters", 688..=767), ("Combining Diacritical Marks", 768..=879), ("Greek and Coptic", 880..=1023), ("Cyrillic", 1024..=1279), ("Cyrillic Supplement", 1280..=1327), ("Armenian", 1328..=1423), ("Hebrew", 1424..=1535), ("Arabic", 1536..=1791), ("Syriac", 1792..=1871), ("Arabic Supplement", 1872..=1919), ("Thaana", 1920..=1983), ("NKo", 1984..=2047), ("Samaritan", 2048..=2111), ("Mandaic", 2112..=2143), ("Syriac Supplement", 2144..=2159), ("Arabic Extended-A", 2208..=2303), ("Devanagari", 2304..=2431), ("Bengali", 2432..=2559), ("Gurmukhi", 2560..=2687), ("Gujarati", 2688..=2815), ("Oriya", 2816..=2943), ("Tamil", 2944..=3071), ("Telugu", 3072..=3199), ("Kannada", 3200..=3327), ("Malayalam", 3328..=3455), ("Sinhala", 3456..=3583), ("Thai", 3584..=3711), ("Lao", 3712..=3839), ("Tibetan", 3840..=4095), ("Myanmar", 4096..=4255), ("Georgian", 4256..=4351), ("Hangul Jamo", 4352..=4607), ("Ethiopic", 4608..=4991), ("Ethiopic Supplement", 4992..=5023), ("Cherokee", 5024..=5119), ("Unified Canadian Aboriginal Syllabics", 5120..=5759), ("Ogham", 5760..=5791), ("Runic", 5792..=5887), ("Tagalog", 5888..=5919), ("Hanunoo", 5920..=5951), ("Buhid", 5952..=5983), ("Tagbanwa", 5984..=6015), ("Khmer", 6016..=6143), ("Mongolian", 6144..=6319), ( "Unified Canadian Aboriginal Syllabics Extended", 6320..=6399, ), ("Limbu", 6400..=6479), ("Tai Le", 6480..=6527), ("New Tai Lue", 6528..=6623), ("Khmer Symbols", 6624..=6655), ("Buginese", 6656..=6687), ("Tai Tham", 6688..=6831), ("Combining Diacritical Marks Extended", 6832..=6911), ("Balinese", 6912..=7039), ("Sundanese", 7040..=7103), ("Batak", 7104..=7167), ("Lepcha", 7168..=7247), ("Ol Chiki", 7248..=7295), ("Cyrillic Extended C", 7296..=7311), ("Sundanese Supplement", 7360..=7375), ("Vedic Extensions", 7376..=7423), ("Phonetic Extensions", 7424..=7551), ("Phonetic Extensions Supplement", 7552..=7615), ("Combining Diacritical Marks Supplement", 7616..=7679), ("Latin Extended Additional", 7680..=7935), ("Greek Extended", 7936..=8191), ("General Punctuation", 8192..=8303), ("Superscripts and Subscripts", 8304..=8351), ("Currency Symbols", 8352..=8399), ("Combining Diacritical Marks for Symbols", 8400..=8447), ("Letterlike Symbols", 8448..=8527), ("Number Forms", 8528..=8591), ("Arrows", 8592..=8703), ("Mathematical Operators", 8704..=8959), ("Miscellaneous Technical", 8960..=9215), ("Control Pictures", 9216..=9279), ("Optical Character Recognition", 9280..=9311), ("Enclosed Alphanumerics", 9312..=9471), ("Box Drawing", 9472..=9599), ("Block Elements", 9600..=9631), ("Geometric Shapes", 9632..=9727), ("Miscellaneous Symbols", 9728..=9983), ("Dingbats", 9984..=10175), ("Miscellaneous Mathematical Symbols-A", 10176..=10223), ("Supplemental Arrows-A", 10224..=10239), ("Braille Patterns", 10240..=10495), ("Supplemental Arrows-B", 10496..=10623), ("Miscellaneous Mathematical Symbols-B", 10624..=10751), ("Supplemental Mathematical Operators", 10752..=11007), ("Miscellaneous Symbols and Arrows", 11008..=11263), ("Glagolitic", 11264..=11359), ("Latin Extended-C", 11360..=11391), ("Coptic", 11392..=11519), ("Georgian Supplement", 11520..=11567), ("Tifinagh", 11568..=11647), ("Ethiopic Extended", 11648..=11743), ("Cyrillic Extended-A", 11744..=11775), ("Supplemental Punctuation", 11776..=11903), ("CJK Radicals Supplement", 11904..=12031), ("Kangxi Radicals", 12032..=12255), ("Ideographic Description Characters", 12272..=12287), ("CJK Symbols and Punctuation", 12288..=12351), ("Hiragana", 12352..=12447), ("Katakana", 12448..=12543), ("Bopomofo", 12544..=12591), ("Hangul Compatibility Jamo", 12592..=12687), ("Kanbun", 12688..=12703), ("Bopomofo Extended", 12704..=12735), ("CJK Strokes", 12736..=12783), ("Katakana Phonetic Extensions", 12784..=12799), ("Enclosed CJK Letters and Months", 12800..=13055), ("CJK Compatibility", 13056..=13311), ("CJK Unified Ideographs Extension A", 13312..=19903), ("Yijing Hexagram Symbols", 19904..=19967), ("CJK Unified Ideographs", 19968..=40959), ("Yi Syllables", 40960..=42127), ("Yi Radicals", 42128..=42191), ("Lisu", 42192..=42239), ("Vai", 42240..=42559), ("Cyrillic Extended-B", 42560..=42655), ("Bamum", 42656..=42751), ("Modifier Tone Letters", 42752..=42783), ("Latin Extended-D", 42784..=43007), ("Syloti Nagri", 43008..=43055), ("Common Indic Number Forms", 43056..=43071), ("Phags-pa", 43072..=43135), ("Saurashtra", 43136..=43231), ("Devanagari Extended", 43232..=43263), ("Kayah Li", 43264..=43311), ("Rejang", 43312..=43359), ("Hangul Jamo Extended-A", 43360..=43391), ("Javanese", 43392..=43487), ("Myanmar Extended-B", 43488..=43519), ("Cham", 43520..=43615), ("Myanmar Extended-A", 43616..=43647), ("Tai Viet", 43648..=43743), ("Meetei Mayek Extensions", 43744..=43775), ("Ethiopic Extended-A", 43776..=43823), ("Latin Extended-E", 43824..=43887), ("Cherokee Supplement", 43888..=43967), ("Meetei Mayek", 43968..=44031), ("Hangul Syllables", 44032..=55215), ("Hangul Jamo Extended-B", 55216..=55295), ("High Surrogates", 55296..=56191), ("High Private Use Surrogates", 56192..=56319), ("Low Surrogates", 56320..=57343), ("Private Use Area", 57344..=63743), ("CJK Compatibility Ideographs", 63744..=64255), ("Alphabetic Presentation Forms", 64256..=64335), ("Arabic Presentation Forms-A", 64336..=65023), ("Variation Selectors", 65024..=65039), ("Vertical Forms", 65040..=65055), ("Combining Half Marks", 65056..=65071), ("CJK Compatibility Forms", 65072..=65103), ("Small Form Variants", 65104..=65135), ("Arabic Presentation Forms-B", 65136..=65279), ("Halfwidth and Fullwidth Forms", 65280..=65519), ("Specials", 65520..=65535), ("Linear B Syllabary", 65536..=65663), ("Linear B Ideograms", 65664..=65791), ("Aegean Numbers", 65792..=65855), ("Ancient Greek Numbers", 65856..=65935), ("Ancient Symbols", 65936..=65999), ("Phaistos Disc", 66000..=66047), ("Lycian", 66176..=66207), ("Carian", 66208..=66271), ("Coptic Epact Numbers", 66272..=66303), ("Old Italic", 66304..=66351), ("Gothic", 66352..=66383), ("Old Permic", 66384..=66431), ("Ugaritic", 66432..=66463), ("Old Persian", 66464..=66527), ("Deseret", 66560..=66639), ("Shavian", 66640..=66687), ("Osmanya", 66688..=66735), ("Osage", 66736..=66815), ("Elbasan", 66816..=66863), ("Caucasian Albanian", 66864..=66927), ("Linear A", 67072..=67455), ("Cypriot Syllabary", 67584..=67647), ("Imperial Aramaic", 67648..=67679), ("Palmyrene", 67680..=67711), ("Nabataean", 67712..=67759), ("Hatran", 67808..=67839), ("Phoenician", 67840..=67871), ("Lydian", 67872..=67903), ("Meroitic Hieroglyphs", 67968..=67999), ("Meroitic Cursive", 68000..=68095), ("Kharoshthi", 68096..=68191), ("Old South Arabian", 68192..=68223), ("Old North Arabian", 68224..=68255), ("Manichaean", 68288..=68351), ("Avestan", 68352..=68415), ("Inscriptional Parthian", 68416..=68447), ("Inscriptional Pahlavi", 68448..=68479), ("Psalter Pahlavi", 68480..=68527), ("Old Turkic", 68608..=68687), ("Old Hungarian", 68736..=68863), ("Rumi Numeral Symbols", 69216..=69247), ("Brahmi", 69632..=69759), ("Kaithi", 69760..=69839), ("Sora Sompeng", 69840..=69887), ("Chakma", 69888..=69967), ("Mahajani", 69968..=70015), ("Sharada", 70016..=70111), ("Sinhala Archaic Numbers", 70112..=70143), ("Khojki", 70144..=70223), ("Multani", 70272..=70319), ("Khudawadi", 70320..=70399), ("Grantha", 70400..=70527), ("Newa", 70656..=70783), ("Tirhuta", 70784..=70879), ("Siddham", 71040..=71167), ("Modi", 71168..=71263), ("Mongolian Supplement", 71264..=71295), ("Takri", 71296..=71375), ("Ahom", 71424..=71487), ("Warang Citi", 71840..=71935), ("Zanabazar Square", 72192..=72271), ("Soyombo", 72272..=72367), ("Pau Cin Hau", 72384..=72447), ("Bhaiksuki", 72704..=72815), ("Marchen", 72816..=72895), ("Masaram Gondi", 72960..=73055), ("Cuneiform", 73728..=74751), ("Cuneiform Numbers and Punctuation", 74752..=74879), ("Early Dynastic Cuneiform", 74880..=75087), ("Egyptian Hieroglyphs", 77824..=78895), ("Anatolian Hieroglyphs", 82944..=83583), ("Bamum Supplement", 92160..=92735), ("Mro", 92736..=92783), ("Bassa Vah", 92880..=92927), ("Pahawh Hmong", 92928..=93071), ("Miao", 93952..=94111), ("Ideographic Symbols and Punctuation", 94176..=94207), ("Tangut", 94208..=100_351), ("Tangut Components", 100_352..=101_119), ("Kana Supplement", 110_592..=110_847), ("Kana Extended-A", 110_848..=110_895), ("Nushu", 110_960..=111_359), ("Duployan", 113_664..=113_823), ("Shorthand Format Controls", 113_824..=113_839), ("Byzantine Musical Symbols", 118_784..=119_039), ("Musical Symbols", 119_040..=119_295), ("Ancient Greek Musical Notation", 119_296..=119_375), ("Tai Xuan Jing Symbols", 119_552..=119_647), ("Counting Rod Numerals", 119_648..=119_679), ("Mathematical Alphanumeric Symbols", 119_808..=120_831), ("Sutton SignWriting", 120_832..=121_519), ("Glagolitic Supplement", 122_880..=122_927), ("Mende Kikakui", 124_928..=125_151), ("Adlam", 125_184..=125_279), ("Arabic Mathematical Alphabetic Symbols", 126_464..=126_719), ("Mahjong Tiles", 126_976..=127_023), ("Domino Tiles", 127_024..=127_135), ("Playing Cards", 127_136..=127_231), ("Enclosed Alphanumeric Supplement", 127_232..=127_487), ("Enclosed Ideographic Supplement", 127_488..=127_743), ("Miscellaneous Symbols and Pictographs", 127_744..=128_511), ("Emoticons range(Emoji)", 128_512..=128_591), ("Ornamental Dingbats", 128_592..=128_639), ("Transport and Map Symbols", 128_640..=128_767), ("Alchemical Symbols", 128_768..=128_895), ("Geometric Shapes Extended", 128_896..=129_023), ("Supplemental Arrows-C", 129_024..=129_279), ("Supplemental Symbols and Pictographs", 129_280..=129_535), ("CJK Unified Ideographs Extension B", 131_072..=173_791), ("CJK Unified Ideographs Extension C", 173_824..=177_983), ("CJK Unified Ideographs Extension D", 177_984..=178_207), ("CJK Unified Ideographs Extension E", 178_208..=183_983), ("CJK Unified Ideographs Extension F", 183_984..=191_471), ("CJK Compatibility Ideographs Supplement", 194_560..=195_103), ("Tags", 917_504..=917_631), ("Variation Selectors Supplement", 917_760..=917_999), ] });
pub(crate) static UNICODE_SECONDARY_RANGE_KEYWORD: Lazy<HashSet<&'static str>> = Lazy::new(|| { HashSet::from_iter([ "Extended", "Extensions", "Modifier", "Marks", "Punctuation", "Symbols", "Forms", "Operators", "Miscellaneous", "Drawing", "Block", "Shapes", "Supplemental", "Supplement", "Tags", ])});
pub(crate) static RE_POSSIBLE_ENCODING_INDICATION: Lazy<Regex> = Lazy::new(|| { Regex::new( r#"(?:(?:encoding)|(?:charset)|(?:coding))(?:[\:= ]{1,10})(?:["']?)([a-zA-Z0-9\-_]+)(?:["']?)"#).unwrap()});
pub static IANA_SUPPORTED: Lazy<Vec<&'static str>> = Lazy::new(|| { encodings() .iter() .filter(|&enc| !["error", "encoder-only-utf-8", "pua-mapped-binary"].contains(&enc.name())) .map(|&enc| enc.whatwg_name().unwrap_or(enc.name())) .collect()});
pub static IANA_SUPPORTED_COUNT: Lazy<usize> = Lazy::new(|| IANA_SUPPORTED.len());
// chardet encoding names (in lowercase!)pub static CHARDET_CORRESPONDENCE: Lazy<HashMap<&'static str, &'static str>> = Lazy::new(|| { HashMap::from_iter([ ("tis-620", "windows-874"), ("utf-16", "utf-16le"), ("maccyrillic", "x-mac-cyrillic"), ("gb2312", "gbk"), ("cp949", "euc-kr"), ])});
// aliases (labels) are from https://encoding.spec.whatwg.org/#concept-encoding-get -> as is + lowercasedpub static IANA_SUPPORTED_ALIASES: Lazy<HashMap<&'static str, Vec<&'static str>>> = Lazy::new(|| { HashMap::from_iter([ ( "utf-8", vec![ "unicode-1-1-utf-8", "unicode11utf8", "unicode20utf8", "utf-8", "utf8", "x-unicode20utf8", ], ), ("ibm866", vec!["866", "cp866", "csibm866", "ibm866"]), ( "iso-8859-2", vec![ "csisolatin2", "iso-8859-2", "iso-ir-101", "iso8859-2", "iso88592", "iso_8859-2", "iso_8859-2:1987", "l2", "latin2", ], ), ( "iso-8859-3", vec![ "csisolatin3", "iso-8859-3", "iso-ir-109", "iso8859-3", "iso88593", "iso_8859-3", "iso_8859-3:1988", "l3", "latin3", ], ), ( "iso-8859-4", vec![ "csisolatin4", "iso-8859-4", "iso-ir-110", "iso8859-4", "iso88594", "iso_8859-4", "iso_8859-4:1988", "l4", "latin4", ], ), ( "iso-8859-5", vec![ "csisolatincyrillic", "cyrillic", "iso-8859-5", "iso-ir-144", "iso8859-5", "iso88595", "iso_8859-5", "iso_8859-5:1988", ], ), ( "iso-8859-6", vec![ "arabic", "asmo-708", "csiso88596e", "csiso88596i", "csisolatinarabic", "ecma-114", "iso-8859-6", "iso-8859-6-e", "iso-8859-6-i", "iso-ir-127", "iso8859-6", "iso88596", "iso_8859-6", "iso_8859-6:1987", ], ), ( "iso-8859-7", vec![ "csisolatingreek", "ecma-118", "elot_928", "greek", "greek8", "iso-8859-7", "iso-ir-126", "iso8859-7", "iso88597", "iso_8859-7", "iso_8859-7:1987", "sun_eu_greek", ], ), ( "iso-8859-8", vec![ "csiso88598e", "csisolatinhebrew", "hebrew", "iso-8859-8", "iso-8859-8-e", "iso-ir-138", "iso8859-8", "iso88598", "iso_8859-8", "iso_8859-8:1988", "visual", ], ), ( "iso-8859-8-i", vec!["csiso88598i", "iso-8859-8-i", "logical"], ), ( "iso-8859-10", vec![ "csisolatin6", "iso-8859-10", "iso-ir-157", "iso8859-10", "iso885910", "l6", "latin6", ], ), ( "iso-8859-13", vec!["iso-8859-13", "iso8859-13", "iso885913"], ), ( "iso-8859-14", vec!["iso-8859-14", "iso8859-14", "iso885914"], ), ( "iso-8859-15", vec![ "csisolatin9", "iso-8859-15", "iso8859-15", "iso885915", "iso_8859-15", "l9", ], ), ("iso-8859-16", vec!["iso-8859-16"]), ("koi8-r", vec!["cskoi8r", "koi", "koi8", "koi8-r", "koi8_r"]), ("koi8-u", vec!["koi8-ru", "koi8-u"]), ( "macintosh", vec!["csmacintosh", "mac", "macintosh", "x-mac-roman"], ), ( "windows-874", vec![ "dos-874", "iso-8859-11", "iso8859-11", "iso885911", "tis-620", "windows-874", ], ), ("windows-1250", vec!["cp1250", "windows-1250", "x-cp1250"]), ("windows-1251", vec!["cp1251", "windows-1251", "x-cp1251"]), ( "windows-1252", vec![ "ansi_x3.4-1968", "ascii", "cp1252", "cp819", "csisolatin1", "ibm819", "iso-8859-1", "iso-ir-100", "iso8859-1", "iso88591", "iso_8859-1", "iso_8859-1:1987", "l1", "latin1", "us-ascii", "windows-1252", "x-cp1252", ], ), ("windows-1253", vec!["cp1253", "windows-1253", "x-cp1253"]), ( "windows-1254", vec![ "cp1254", "csisolatin5", "iso-8859-9", "iso-ir-148", "iso8859-9", "iso88599", "iso_8859-9", "iso_8859-9:1989", "l5", "latin5", "windows-1254", "x-cp1254", ], ), ("windows-1255", vec!["cp1255", "windows-1255", "x-cp1255"]), ("windows-1256", vec!["cp1256", "windows-1256", "x-cp1256"]), ("windows-1257", vec!["cp1257", "windows-1257", "x-cp1257"]), ("windows-1258", vec!["cp1258", "windows-1258", "x-cp1258"]), ("x-mac-cyrillic", vec!["x-mac-cyrillic", "x-mac-ukrainian"]), ( "gbk", vec![ "chinese", "csgb2312", "csiso58gb231280", "gb2312", "gb_2312", "gb_2312-80", "gbk", "iso-ir-58", "x-gbk", ], ), ("gb18030", vec!["gb18030"]), ( "big5", vec!["big5", "big5-hkscs", "cn-big5", "csbig5", "x-x-big5"], ), ("euc-jp", vec!["cseucpkdfmtjapanese", "euc-jp", "x-euc-jp"]), ("iso-2022-jp", vec!["csiso2022jp", "iso-2022-jp"]), ( "shift_jis", vec![ "csshiftjis", "ms932", "ms_kanji", "shift-jis", "shift_jis", "sjis", "windows-31j", "x-sjis", ], ), ( "euc-kr", vec![ "cseuckr", "csksc56011987", "euc-kr", "iso-ir-149", "korean", "ks_c_5601-1987", "ks_c_5601-1989", "ksc5601", "ksc_5601", "windows-949", ], ), ( "replacement", vec![ "csiso2022kr", "hz-gb-2312", "iso-2022-cn", "iso-2022-cn-ext", "iso-2022-kr", "replacement", ], ), ("utf-16be", vec!["unicodefffe", "utf-16be"]), ( "utf-16le", vec![ "csunicode", "iso-10646-ucs-2", "ucs-2", "unicode", "unicodefeff", "utf-16", "utf-16le", ], ), ("x-user-defined", vec!["x-user-defined"]), ]) });
pub static IANA_SUPPORTED_SIMILAR: Lazy<HashMap<&'static str, Vec<&'static str>>> = Lazy::new(|| { HashMap::from_iter([ ("windows-1252", vec!["iso-8859-15", "windows-1254"]), ("windows-1253", vec!["iso-8859-7"]), ("windows-1254", vec!["iso-8859-15", "windows-1252"]), ("windows-1257", vec!["iso-8859-13"]), ( "iso-8859-10", vec![ "iso-8859-14", "iso-8859-15", "iso-8859-4", "windows-1254", "windows-1252", ], ), ("iso-8859-13", vec!["windows-1257"]), ( "iso-8859-14", vec![ "iso-8859-10", "iso-8859-15", "iso-8859-16", "iso-8859-3", "windows-1254", "windows-1252", ], ), ( "iso-8859-15", vec![ "windows-1252", "windows-1254", "iso-8859-10", "iso-8859-14", "iso-8859-16", "iso-8859-3", ], ), ( "iso-8859-16", vec![ "iso-8859-14", "iso-8859-15", "iso-8859-2", "iso-8859-3", "windows-1254", "windows-1252", ], ), ("iso-8859-2", vec!["iso-8859-16", "iso-8859-4"]), ( "iso-8859-3", vec![ "iso-8859-14", "iso-8859-15", "iso-8859-16", "windows-1254", "windows-1252", ], ), ( "iso-8859-4", vec!["iso-8859-10", "iso-8859-2", "windows-1254", "windows-1252"], ), ("iso-8859-7", vec!["windows-1253"]), ( "windows-1254", vec![ "windows-1252", "windows-1258", "iso-8859-10", "iso-8859-14", "iso-8859-15", "iso-8859-16", "iso-8859-3", "iso-8859-4", ], ), ( "windows-1252", vec![ "windows-1254", "windows-1258", "iso-8859-10", "iso-8859-14", "iso-8859-15", "iso-8859-16", "iso-8859-3", "iso-8859-4", ], ), ]) });123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518#![allow(unused_variables)]
use crate::cd::{encoding_languages, mb_encoding_languages};use crate::consts::{IANA_SUPPORTED_ALIASES, TOO_BIG_SEQUENCE};use crate::utils::{decode, iana_name, is_multi_byte_encoding, range_scan};use clap::Parser;use encoding::DecoderTrap;use ordered_float::OrderedFloat;use serde::Serialize;use std::cmp::Ordering;use std::fmt;use std::fmt::{Debug, Display, Formatter};use std::hash::Hash;use std::ops::Index;use std::path::PathBuf;use std::time::Duration;
/////////////////////////////////////////////////////////////////////////////////////// Languages/////////////////////////////////////////////////////////////////////////////////////
#[derive(Debug, PartialEq, Eq, Hash)]pub enum Language { English, German, French, Dutch, Italian, Polish, Spanish, Russian, Japanese, Portuguese, Swedish, Chinese, Ukrainian, Norwegian, Finnish, Vietnamese, Czech, Hungarian, Korean, Indonesian, Turkish, Romanian, Farsi, Arabic, Danish, Serbian, Lithuanian, Slovene, Slovak, Hebrew, Bulgarian, Croatian, Hindi, Estonian, Thai, Greek, Tamil, Kazakh, Unknown,}
impl Display for Language { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{:?}", self) }}
/////////////////////////////////////////////////////////////////////////////////////// CoherenceMatch & CoherenceMatches/////////////////////////////////////////////////////////////////////////////////////
#[derive(Debug, PartialEq, Clone)]pub struct CoherenceMatch { pub language: &'static Language, pub score: f32,}
pub type CoherenceMatches = Vec<CoherenceMatch>;
/////////////////////////////////////////////////////////////////////////////////////// CharsetMatch/////////////////////////////////////////////////////////////////////////////////////
#[derive(Clone)]pub struct CharsetMatch { payload: Vec<u8>, encoding: String,
mean_mess_ratio: f32, coherence_matches: CoherenceMatches,
has_sig_or_bom: bool,
submatch: Vec<CharsetMatch>, decoded_payload: Option<String>,}
impl Display for CharsetMatch { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{:?} ({})", self.payload, self.encoding) }}
impl Debug for CharsetMatch { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{:?} ({})", self.payload, self.encoding) }}
impl Default for CharsetMatch { fn default() -> Self { CharsetMatch { payload: vec![], encoding: "utf-8".to_string(), mean_mess_ratio: 0.0, coherence_matches: vec![], has_sig_or_bom: false, submatch: vec![], decoded_payload: None, } }}
impl PartialEq<Self> for CharsetMatch { fn eq(&self, other: &Self) -> bool { self.encoding == other.encoding && self.decoded_payload == other.decoded_payload }}
impl PartialOrd<Self> for CharsetMatch { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { let mess_difference = (self.mean_mess_ratio - other.mean_mess_ratio).abs(); let coherence_a = self.coherence(); let coherence_b = other.coherence(); let coherence_difference = (coherence_a - coherence_b).abs();
// Below 1% difference --> Use Coherence if mess_difference < 0.01 { if coherence_difference > 0.02 { return coherence_b.partial_cmp(&coherence_a); } let multibyte_usage_a = self.multi_byte_usage(); let multibyte_usage_b = other.multi_byte_usage(); let multibyte_usage_delta = (multibyte_usage_a - multibyte_usage_b).abs(); if multibyte_usage_delta > f32::EPSILON { return multibyte_usage_b.partial_cmp(&multibyte_usage_a); } } self.mean_mess_ratio.partial_cmp(&other.mean_mess_ratio) }}
impl CharsetMatch { // Init function pub fn new( payload: &[u8], encoding: &str, mean_mess_ratio: f32, has_sig_or_bom: bool, coherence_matches: &CoherenceMatches, decoded_payload: Option<&str>, ) -> Self { CharsetMatch { payload: Vec::from(payload), encoding: String::from(encoding), mean_mess_ratio, coherence_matches: coherence_matches.clone(), has_sig_or_bom, submatch: vec![], decoded_payload: decoded_payload.map(String::from).or_else(|| { decode(payload, encoding, DecoderTrap::Strict, false, true) .ok() .map(|res| res.strip_prefix('\u{feff}').unwrap_or(&res).to_string()) }), } }
// Add submatch pub fn add_submatch(&mut self, submatch: &CharsetMatch) { self.submatch.push(submatch.clone()); //self.decoded_payload = None; }
// Get encoding aliases according to https://encoding.spec.whatwg.org/encodings.json pub fn encoding_aliases(&self) -> Vec<&'static str> { IANA_SUPPORTED_ALIASES .get(self.encoding.as_str()) .cloned() .expect("Problem with static HashMap IANA_SUPPORTED_ALIASES") } // byte_order_mark pub fn bom(&self) -> bool { self.has_sig_or_bom } pub fn encoding(&self) -> &str { &self.encoding } pub fn chaos(&self) -> f32 { self.mean_mess_ratio } // Most probable language found in decoded sequence. If none were detected or inferred, the property will return // Language::Unknown pub fn most_probably_language(&self) -> &'static Language { self.coherence_matches.first().map_or_else( // Default case: Trying to infer the language based on the given encoding || { if self.suitable_encodings().contains(&String::from("ascii")) { &Language::English } else { let languages = if is_multi_byte_encoding(&self.encoding) { mb_encoding_languages(&self.encoding) } else { encoding_languages(self.encoding.clone()) }; languages.first().copied().unwrap_or(&Language::Unknown) } }, |lang| lang.language, ) } // Return the complete list of possible languages found in decoded sequence. // Usually not really useful. Returned list may be empty even if 'language' property return something != 'Unknown'. pub fn languages(&self) -> Vec<&'static Language> { self.coherence_matches .iter() .map(|cm| cm.language) .collect() } // Has submatch pub fn has_submatch(&self) -> bool { !self.submatch.is_empty() } // Return submatch list pub fn submatch(&self) -> &Vec<CharsetMatch> { &self.submatch } // Multibyte usage ratio pub fn multi_byte_usage(&self) -> f32 { let decoded_chars = self.decoded_payload().unwrap_or_default().chars().count() as f32; let payload_len = self.payload.len() as f32;
1.0 - (decoded_chars / payload_len) } // Original untouched bytes pub fn raw(&self) -> &Vec<u8> { &self.payload } // Return chaos in percents with rounding pub fn chaos_percents(&self) -> f32 { self.chaos() * 100.0 } // Return coherence in percents with rounding pub fn coherence_percents(&self) -> f32 { self.coherence() * 100.0 } // Most relevant language coherence pub fn coherence(&self) -> f32 { self.coherence_matches .first() .map(|lang| lang.score) .unwrap_or_default() }
// To recalc decoded_payload field pub fn decoded_payload(&self) -> Option<&str> { self.decoded_payload.as_deref() }
// The complete list of encodings that output the exact SAME str result and therefore could be the originating // encoding. This list does include the encoding available in property 'encoding'. pub fn suitable_encodings(&self) -> Vec<String> { std::iter::once(self.encoding.clone()) .chain(self.submatch.iter().map(|s| s.encoding.clone())) .collect() } // Returns sorted list of unicode ranges (if exists) pub fn unicode_ranges(&self) -> Vec<String> { let mut ranges: Vec<String> = range_scan(self.decoded_payload().unwrap_or_default()) .iter() .cloned() .collect(); ranges.sort_unstable(); ranges }}
/////////////////////////////////////////////////////////////////////////////////////// CharsetMatches// Container with every CharsetMatch items ordered by default from most probable// to the less one./////////////////////////////////////////////////////////////////////////////////////
#[derive(Debug, Default)]pub struct CharsetMatches { items: Vec<CharsetMatch>,}
pub struct CharsetMatchesIterMut<'a> { items: std::slice::IterMut<'a, CharsetMatch>,}
pub struct CharsetMatchesIter<'a> { items: std::slice::Iter<'a, CharsetMatch>,}
impl CharsetMatches { // Initialization method pub fn new(items: Option<Vec<CharsetMatch>>) -> Self { let mut items = items.unwrap_or_default(); CharsetMatches::resort(&mut items); CharsetMatches { items } } pub fn from_single(item: CharsetMatch) -> Self { CharsetMatches { items: vec![item] } } // Insert a single match. Will be inserted accordingly to preserve sort. // Can be inserted as a submatch. pub fn append(&mut self, item: CharsetMatch) { // We should disable the submatch factoring when the input file is too heavy // (conserve RAM usage) if item.payload.len() <= TOO_BIG_SEQUENCE { for m in &mut self.items { if m.decoded_payload() == item.decoded_payload() && (m.mean_mess_ratio - item.mean_mess_ratio).abs() < f32::EPSILON { m.add_submatch(&item); return; } } } self.items.push(item); CharsetMatches::resort(&mut self.items); } // Simply return the first match. Strict equivalent to matches[0]. pub fn get_best(&self) -> Option<&CharsetMatch> { self.items.first() } // Retrieve a single item either by its position or encoding name (alias may be used here). pub fn get_by_encoding(&self, encoding: &str) -> Option<&CharsetMatch> { let encoding = iana_name(encoding)?; self.items .iter() .find(|&i| i.suitable_encodings().contains(&encoding.to_string())) } // Resort items by relevancy (for internal use) fn resort(items: &mut [CharsetMatch]) { items.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap()); } // iterator pub fn iter_mut(&mut self) -> CharsetMatchesIterMut { CharsetMatchesIterMut { items: self.items.iter_mut(), } } pub fn iter(&self) -> CharsetMatchesIter { CharsetMatchesIter { items: self.items.iter(), } } // len pub fn len(&self) -> usize { self.items.len() } // is empty? pub fn is_empty(&self) -> bool { self.items.is_empty() }}
impl Index<usize> for CharsetMatches { type Output = CharsetMatch; fn index(&self, index: usize) -> &Self::Output { &self.items[index] }}
impl<'a> Iterator for CharsetMatchesIterMut<'a> { type Item = &'a mut CharsetMatch;
fn next(&mut self) -> Option<Self::Item> { self.items.next() }}
impl<'a> Iterator for CharsetMatchesIter<'a> { type Item = &'a CharsetMatch;
fn next(&mut self) -> Option<Self::Item> { self.items.next() }}
#[derive(Clone)]pub struct NormalizerSettings { /// How many steps (chunks) should be used from file pub steps: usize, /// Each chunk size pub chunk_size: usize, /// Mess ration threshold pub threshold: OrderedFloat<f32>, /// Specify probing encodings exactly pub include_encodings: Vec<String>, /// Exclude these encodings from probing pub exclude_encodings: Vec<String>, /// Allow try to find charset in the text pub preemptive_behaviour: bool, /// Language detector threshold pub language_threshold: OrderedFloat<f32>, /// Allow fallback to ASCII / UTF-8 pub enable_fallback: bool,}
impl Default for NormalizerSettings { fn default() -> Self { NormalizerSettings { steps: 5, chunk_size: 512, threshold: OrderedFloat(0.2), include_encodings: vec![], exclude_encodings: vec![], preemptive_behaviour: true, language_threshold: OrderedFloat(0.1), enable_fallback: true, } }}
/////////////////////////////////////////////////////////////////////////////////////// Performance binary application/////////////////////////////////////////////////////////////////////////////////////
#[derive(Parser, Debug)]#[command(name = "Performance check for charset-normalizer-rs vs chardet vs chardetng")]#[command(author, version, about, long_about = None)]pub struct PerformanceArgs { /// Apply artificial size increase to challenge the detection mechanism further #[arg(short, long, default_value_t = 1)] pub size_increase: u8,}
// Struct to save result of each test in performance apppub struct PerformanceResult { /// Performance test duration pub duration: Duration, /// Is result accurate? pub correct: bool,}
/////////////////////////////////////////////////////////////////////////////////////// Normalizer CLI application/////////////////////////////////////////////////////////////////////////////////////
#[derive(Parser, Debug)]#[command( name = "The Real First Universal Charset Detector. Discover originating encoding used on text file. Normalize text to unicode.")]#[command(author, version, about, long_about = None)]pub struct CLINormalizerArgs { /// File(s) to be analysed #[arg(required = true, action = clap::ArgAction::Append)] pub files: Vec<PathBuf>,
/// Display complementary information about file if any. Stdout will contain logs about the detection process. #[arg(short = 'v', long = "verbose", default_value_t = false)] pub verbose: bool,
/// Output complementary possibilities if any. Top-level JSON WILL be a list. #[arg(short = 'a', long = "with-alternative", default_value_t = false)] pub alternatives: bool,
/// Permit to normalize input file. If not set, program does not write anything. #[arg(short, long, default_value_t = false)] pub normalize: bool,
/// Only output the charset detected to STDOUT. Disabling JSON output. #[arg(short, long, default_value_t = false)] pub minimal: bool,
/// Replace file when trying to normalize it instead of creating a new one. #[arg(short, long, default_value_t = false)] pub replace: bool,
/// Replace file without asking if you are sure, use this flag with caution. #[arg(short, long, default_value_t = false)] pub force: bool,
/// Define a custom maximum amount of chaos allowed in decoded content. 0. <= chaos <= 1. #[arg(short, long, default_value_t = 0.2)] pub threshold: f32,}
#[derive(Default, Debug, Serialize)]pub struct CLINormalizerResult { /// Path to analysed file pub path: PathBuf, /// Guessed encoding pub encoding: Option<String>, /// Possible aliases of guessed encoding pub encoding_aliases: Vec<String>, /// Alternative possible encodings pub alternative_encodings: Vec<String>, /// Most probably language pub language: String, /// Found alphabets pub alphabets: Vec<String>, /// Does it has SIG or BOM mark? pub has_sig_or_bom: bool, /// Chaos (mess) level pub chaos: String, /// Coherence (language detection) level pub coherence: String, /// Path to decoded data pub unicode_path: Option<PathBuf>, pub is_preferred: bool,}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597//! charset-normalizer-rs//! ======================//!//! The Real First Universal Charset Detector, Rust version.//! Motivated by original Python version of `charset-normalizer`,//!//! This library helps read text from an unknown charset encoding.//! All IANA character set names for which the Rust `encoding` library provides codecs are supported.//!//! This project is port of original Pyhon version of [Charset Normalizer](https://github.com/Ousret/charset_normalizer).//! The biggest difference between Python and Rust versions - number of supported encodings as each langauge has own encoding / decoding library.//! In Rust version only encoding from [WhatWG standard](https://encoding.spec.whatwg.org) are supported.//! Python version supports more encodings, but a lot of them are old almost unused ones.//!//! # Performance://!//! This library in comparison to Python version is more faster (2-3 times faster, than MYPYC version of charset-normalizer, 4-6 times faster, than usual Python version).//! All measurements are approximated.//!//! # Library://!//! Library offers two main methods://!//! * `from_bytes` processes text using bytes as input parameter//! * `from_path` processes text using filename as input parameter//!//! ## Examples://!//! ```rust//! use charset_normalizer_rs::from_bytes;//!//! fn test_from_bytes() {//! let result = from_bytes(&vec![0x84, 0x31, 0x95, 0x33], None);//! let best_guess = result.get_best();//! assert_eq!(//! best_guess.unwrap().encoding(),//! "gb18030",//! );//! }//! test_from_bytes();//! ```//!//! ```rust//! use std::path::Path;//! use charset_normalizer_rs::from_path;//!//! fn test_from_path() {//! let result = from_path(Path::new("src/tests/data/samples/sample-chinese.txt"), None).unwrap();//! let best_guess = result.get_best();//! assert_eq!(//! best_guess.unwrap().encoding(),//! "big5",//! );//! }//! test_from_path();//! ```//!//! # CLI tool://!//! Binary CLI tool is included within this package. It has similar to Python version input parameters and output data.//!//! ## Installation://!//! ```shell//! cargo install charset-normalizer-rs//! ```//!//! ## Usage://!//! ```shell//! normalizer -h//!//! usage: normalizer [-h] [-v] [-a] [-n] [-m] [-r] [-f] [-t THRESHOLD] [--version] files [files ...]//!//! The Real First Universal Charset Detector. Discover originating encoding used on text file. Normalize text to unicode.//!//! positional arguments://! files File(s) to be analysed//!//! options://! -h, --help show this help message and exit//! -v, --verbose Display complementary information about file if any. Stdout will contain logs about the detection process.//! -a, --with-alternative//! Output complementary possibilities if any. Top-level JSON WILL be a list.//! -n, --normalize Permit to normalize input file. If not set, program does not write anything.//! -m, --minimal Only output the charset detected to STDOUT. Disabling JSON output.//! -r, --replace Replace file when trying to normalize it instead of creating a new one.//! -f, --force Replace file without asking if you are sure, use this flag with caution.//! -t THRESHOLD, --threshold THRESHOLD//! Define a custom maximum amount of chaos allowed in decoded content. 0. <= chaos <= 1.//! --version Show version information and exit.//! ```//!//! ## Example://!//! ```shell//! normalizer src/tests/data/samples/sample-chinese.txt//! ```//!//! This will produce such JSON output://!//! ```json//! {//! "path": ".../src/tests/data/samples/sample-chinese.txt",//! "encoding": "big5",//! "encoding_aliases": [//! "big5_tw",//! "csbig5",//! "x_mac_trad_chinese"//! ],//! "alternative_encodings": [//! "big5hkscs",//! "cp950"//! ],//! "language": "Chinese",//! "alphabets": [//! "Basic Latin",//! "CJK Compatibility Forms",//! "CJK Symbols and Punctuation",//! "CJK Unified Ideographs",//! "Control character",//! "Halfwidth and Fullwidth Forms"//! ],//! "has_sig_or_bom": false,//! "chaos": 0.0,//! "coherence": 12.21,//! "unicode_path": null,//! "is_preferred": true//! }//! ```use crate::cd::{ coherence_ratio, encoding_languages, mb_encoding_languages, merge_coherence_ratios,};use crate::consts::{IANA_SUPPORTED, MAX_PROCESSED_BYTES, TOO_BIG_SEQUENCE, TOO_SMALL_SEQUENCE};use crate::entity::{CharsetMatch, CharsetMatches, CoherenceMatches, NormalizerSettings};use crate::md::mess_ratio;use crate::utils::{ any_specified_encoding, decode, iana_name, identify_sig_or_bom, is_cp_similar, is_invalid_chunk, is_multi_byte_encoding,};use encoding::DecoderTrap;use log::{debug, trace};use std::collections::VecDeque;use std::fs::File;use std::io::Read;use std::path::Path;
pub mod assets;// TODO: Revisit float conversions when we want to push for accuracy#[allow(clippy::cast_lossless, clippy::cast_precision_loss)]mod cd;pub mod consts;pub mod entity;mod md;mod tests;pub mod utils;
// Given a raw bytes sequence, return the best possibles charset usable to render str objects.// If there is no results, it is a strong indicator that the source is binary/not text.// By default, the process will extract 5 blocks of 512o each to assess the mess and coherence of a given sequence.// And will give up a particular code page after 20% of measured mess. Those criteria are customizable at will.//// The preemptive behavior DOES NOT replace the traditional detection workflow, it prioritize a particular code page// but never take it for granted. Can improve the performance.//// You may want to focus your attention to some code page or/and not others, use cp_isolation and cp_exclusion for that// purpose.//// This function will strip the SIG in the payload/sequence every time except on UTF-16, UTF-32.// By default the library does not setup any handler other than the NullHandler, if you choose to set the 'explain'// toggle to True it will alter the logger configuration to add a StreamHandler that is suitable for debugging.// Custom logging format and handler can be set manually.pub fn from_bytes(bytes: &[u8], settings: Option<NormalizerSettings>) -> CharsetMatches { // init settings with default values if it's None and recheck include_encodings and // exclude_encodings settings let mut settings = settings.unwrap_or_default(); if !settings.include_encodings.is_empty() { settings.include_encodings = settings .include_encodings .iter() .map(|e| iana_name(e).unwrap().to_string()) .collect(); trace!( "include_encodings is set. Use this flag for debugging purpose. \ Limited list of encoding allowed : {}.", settings.include_encodings.join(", ") ); } if !settings.exclude_encodings.is_empty() { settings.exclude_encodings = settings .exclude_encodings .iter() .map(|e| iana_name(e).unwrap().to_string()) .collect(); trace!( "exclude_encodings is set. Use this flag for debugging purpose. \ Limited list of encoding allowed : {}.", settings.exclude_encodings.join(", ") ); }
// check for empty let bytes_length = bytes.len(); if bytes_length == 0 { debug!("Encoding detection on empty bytes, assuming utf_8 intention."); return CharsetMatches::from_single(CharsetMatch::default()); }
// check min length if bytes_length <= (settings.chunk_size * settings.steps) { trace!( "override steps ({}) and chunk_size ({}) as content does not \ fit ({} byte(s) given) parameters.", settings.steps, settings.chunk_size, bytes_length, ); settings.steps = 1; settings.chunk_size = bytes_length; }
if settings.steps > 1 && bytes_length / settings.steps < settings.chunk_size { settings.chunk_size = bytes_length / settings.steps; }
// too small length if bytes_length < TOO_SMALL_SEQUENCE { trace!( "Trying to detect encoding from a tiny portion of ({}) byte(s).", bytes_length ); }
// too big length let is_too_large_sequence = bytes_length > TOO_BIG_SEQUENCE; if is_too_large_sequence { trace!( "Using lazy str decoding because the payload is quite large, ({}) byte(s).", bytes_length ); }
// start to build prioritized encodings array let mut prioritized_encodings: Vec<&str> = vec![];
// search for encoding in the content let mut specified_encoding: String = String::new(); if settings.preemptive_behaviour { if let Some(enc) = any_specified_encoding(bytes, 4096) { trace!( "Detected declarative mark in sequence. Priority +1 given for {}.", &enc ); specified_encoding = enc.to_string(); prioritized_encodings.push(&specified_encoding); } }
// check bom & sig let (sig_encoding, sig_payload) = identify_sig_or_bom(bytes); if let (Some(sig_enc), Some(sig_pay)) = (&sig_encoding, sig_payload) { trace!( "Detected a SIG or BOM mark on first {} byte(s). Priority +1 given for {}.", sig_pay.len(), sig_enc, ); prioritized_encodings.push(sig_enc); }
// add ascii & utf-8 prioritized_encodings.extend(&["ascii", "utf-8"]);
// generate array of encodings for probing with prioritizing let mut iana_encodings: VecDeque<&str> = VecDeque::from(IANA_SUPPORTED.clone()); for pe in prioritized_encodings.iter().rev() { if let Some(index) = iana_encodings.iter().position(|x| x == pe) { let value = iana_encodings.remove(index).unwrap(); iana_encodings.push_front(value); } }
// Main processing loop variables let mut tested_but_hard_failure: Vec<&str> = vec![]; let mut tested_but_soft_failure: Vec<&str> = vec![]; let mut fallback_ascii: Option<CharsetMatch> = None; let mut fallback_u8: Option<CharsetMatch> = None; let mut fallback_specified: Option<CharsetMatch> = None; let mut results: CharsetMatches = CharsetMatches::default();
// Iterate and probe our encodings 'iana_encodings_loop: for encoding_iana in iana_encodings { if (!settings.include_encodings.is_empty() && !settings .include_encodings .contains(&encoding_iana.to_string())) || settings .exclude_encodings .contains(&encoding_iana.to_string()) { continue; } let bom_or_sig_available: bool = sig_encoding.as_deref() == Some(encoding_iana); // let strip_sig_or_bom = true // unlike python version this is always true in rust let is_multi_byte_decoder: bool = is_multi_byte_encoding(encoding_iana);
// utf-16le & utf-16be cannot be identified without BOM if !bom_or_sig_available && ["utf-16le", "utf-16be"].contains(&encoding_iana) { trace!( "Encoding {} won't be tested as-is because it require a BOM. Will try some sub-encoder LE/BE", encoding_iana, ); continue; }
// fast pre-check let start_idx = match bom_or_sig_available { true => sig_payload.unwrap().len(), false => 0, }; let end_idx = match is_too_large_sequence && !is_multi_byte_decoder { true => MAX_PROCESSED_BYTES, false => bytes_length, }; let decoded_payload: Option<String> = if let Ok(payload) = decode( &bytes[start_idx..end_idx], encoding_iana, DecoderTrap::Strict, is_too_large_sequence && !is_multi_byte_decoder, false, ) { (!is_too_large_sequence || is_multi_byte_decoder).then_some(payload) } else { trace!( "Code page {} does not fit given bytes sequence at ALL.", encoding_iana, ); tested_but_hard_failure.push(encoding_iana); continue 'iana_encodings_loop; };
// soft failed pre-check // important thing! it occurs sometimes fail detection for encoding_soft_failed in &tested_but_soft_failure { if is_cp_similar(encoding_iana, encoding_soft_failed) { trace!("{} is deemed too similar to code page {} and was consider unsuited already. Continuing!", encoding_iana, encoding_soft_failed, ); continue 'iana_encodings_loop; } }
// lets split input by chunks and try to parse them let max_chunk_gave_up = 2.max(settings.steps / 4); let mut early_stop_count: usize = 0; let mut lazy_str_hard_failure = false; let mut md_ratios: Vec<f32> = vec![];
// detect target languages let target_languages = if is_multi_byte_decoder { mb_encoding_languages(encoding_iana) } else { encoding_languages(encoding_iana.to_string()) }; trace!( "{} should target any language(s) of {:?}", encoding_iana, target_languages, );
// main loop over chunks in our input // we go over bytes or chars - it depends on previous code let seq_len = match &decoded_payload { Some(payload) => payload.chars().count(), None => bytes_length, }; let starting_offset = match (bom_or_sig_available, &decoded_payload) { (true, None) => start_idx, _ => 0, }; let offsets = (starting_offset..seq_len).step_by((seq_len / settings.steps).max(1));
// Chunks Loop // Iterate over chunks of bytes or chars let mut md_chunks: Vec<String> = vec![]; 'chunks_loop: for offset in offsets { let decoded_chunk_result = match &decoded_payload { // Chars processing Some(payload) => Ok(payload .chars() .skip(offset) .take(settings.chunk_size) .collect()), // Bytes processing None => decode( &bytes[offset..(offset + settings.chunk_size).min(seq_len)], encoding_iana, DecoderTrap::Strict, false, false, ), };
if is_invalid_chunk(&decoded_chunk_result, encoding_iana) { trace!( "LazyStr Loading: After MD chunk decode, code page {} \ does not fit given bytes sequence at ALL. {}", encoding_iana, match decoded_chunk_result { Ok(_) => String::from("non-ascii"), Err(message) => message.to_string(), }, ); early_stop_count = max_chunk_gave_up; lazy_str_hard_failure = true; break 'chunks_loop; } let decoded_chunk = decoded_chunk_result.unwrap();
// MD ratios calc md_chunks.push(decoded_chunk.clone()); md_ratios.push(mess_ratio(decoded_chunk, Some(settings.threshold))); if md_ratios.last().unwrap() >= &settings.threshold { early_stop_count += 1; } if early_stop_count >= max_chunk_gave_up { break 'chunks_loop; } }
// We might want to check the remainder of sequence // Only if initial MD tests passes if !lazy_str_hard_failure && is_too_large_sequence && !is_multi_byte_decoder { let decoded_chunk_result = decode( &bytes[MAX_PROCESSED_BYTES..], encoding_iana, DecoderTrap::Strict, false, false, ); if is_invalid_chunk(&decoded_chunk_result, encoding_iana) { trace!( "LazyStr Loading: After final lookup, code page {} does not fit \ given bytes sequence at ALL. {}", encoding_iana, decoded_chunk_result.unwrap_err().to_string(), ); tested_but_hard_failure.push(encoding_iana); continue 'iana_encodings_loop; } }
// process mean mess ratio let mean_mess_ratio = match md_ratios.is_empty() { true => 0.0, false => md_ratios.iter().sum::<f32>() / (md_ratios.len() as f32), };
if mean_mess_ratio >= *settings.threshold || early_stop_count >= max_chunk_gave_up { tested_but_soft_failure.push(encoding_iana); trace!( "{} was excluded because of initial chaos probing. \ Gave up {} time(s). Computed mean chaos is {} %.", encoding_iana, early_stop_count, mean_mess_ratio * 100.0, ); // Preparing those fallbacks in case we got nothing. if settings.enable_fallback && !lazy_str_hard_failure && prioritized_encodings.contains(&encoding_iana) { let fallback_entry = Some(CharsetMatch::new( bytes, encoding_iana, f32::from(settings.threshold), false, &vec![], decoded_payload.as_deref(), ));
match encoding_iana { e if e == specified_encoding => fallback_specified = fallback_entry, "ascii" => fallback_ascii = fallback_entry, _ => fallback_u8 = fallback_entry, } } continue 'iana_encodings_loop; } trace!( "{} passed initial chaos probing. Mean measured chaos is {} %", encoding_iana, mean_mess_ratio * 100.0, );
// CD rations calc // We shall skip the CD when its about ASCII // Most of the time its not relevant to run "language-detection" on it. let mut cd_ratios: Vec<CoherenceMatches> = vec![]; if encoding_iana != "ascii" { cd_ratios.extend(md_chunks.iter().filter_map(|chunk| { coherence_ratio( chunk.clone(), Some(settings.language_threshold), Some(target_languages.clone()), ) .ok() })); }
// process cd ratios let cd_ratios_merged = merge_coherence_ratios(&cd_ratios); if !cd_ratios_merged.is_empty() { trace!( "We detected language {:?} using {}", cd_ratios_merged, encoding_iana ); }
// process results results.append(CharsetMatch::new( bytes, encoding_iana, mean_mess_ratio, bom_or_sig_available, &cd_ratios_merged, decoded_payload.as_deref(), ));
if (mean_mess_ratio < 0.1 && prioritized_encodings.contains(&encoding_iana)) || encoding_iana == sig_encoding.clone().unwrap_or_default() { debug!( "Encoding detection: {} is most likely the one.", encoding_iana ); return CharsetMatches::from_single( results.get_by_encoding(encoding_iana).unwrap().clone(), ); } }
// fallbacks if results.is_empty() { let fb = match (&fallback_specified, &fallback_u8, &fallback_ascii) { (Some(specified), _, _) => Some(specified), (None, Some(u8_fallback), None) => Some(u8_fallback), (None, Some(u8_fallback), Some(ascii)) if u8_fallback.decoded_payload() != ascii.decoded_payload() => { Some(u8_fallback) } (None, _, Some(ascii)) => Some(ascii), _ => None, }; if let Some(fb_to_pass) = fb { debug!( "Encoding detection: will be used as a fallback match {}", fb_to_pass.encoding() ); results.append(fb_to_pass.clone()); }; }
// final logger information if results.is_empty() { debug!("Encoding detection: Unable to determine any suitable charset."); } else { debug!( "Encoding detection: Found {} as plausible (best-candidate) for content. \ With {} alternatives.", results.get_best().unwrap().encoding(), results.len() - 1, ); } results}
// Same thing than the function from_bytes but with one extra step.// Opening and reading given file path in binary mode.// Can return Error.pub fn from_path( path: &Path, settings: Option<NormalizerSettings>,) -> Result<CharsetMatches, String> { // read file let mut file = File::open(path).map_err(|e| format!("Error opening file: {e}"))?; let file_size = file.metadata().map(|m| m.len()).unwrap_or_default();
let mut buffer = Vec::with_capacity(file_size as usize); file.read_to_end(&mut buffer) .map_err(|e| format!("Error reading from file: {e}"))?;
// calculate Ok(from_bytes(&buffer, settings))}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182use cached::proc_macro::cached;use log::{log_enabled, trace};use ordered_float::OrderedFloat;
pub(crate) mod plugins;pub(crate) mod structs;
use plugins::{ ArchaicUpperLowerPlugin, CjkInvalidStopPlugin, MessDetectorPlugin, SuperWeirdWordPlugin, SuspiciousDuplicateAccentPlugin, SuspiciousRangePlugin, TooManyAccentuatedPlugin, TooManySymbolOrPunctuationPlugin, UnprintablePlugin,};use structs::MessDetectorChar;
//// Mess detection module//
// Compute a mess ratio given a decoded bytes sequence. The maximum threshold does stop the computation earlier.#[cached(size = 2048)]pub(crate) fn mess_ratio( decoded_sequence: String, maximum_threshold: Option<OrderedFloat<f32>>,) -> f32 { let maximum_threshold = f32::from(maximum_threshold.unwrap_or(OrderedFloat(0.2))); let mut detectors: Vec<Box<dyn MessDetectorPlugin>> = vec![ Box::<TooManySymbolOrPunctuationPlugin>::default(), Box::<TooManyAccentuatedPlugin>::default(), Box::<UnprintablePlugin>::default(), Box::<SuspiciousRangePlugin>::default(), Box::<SuspiciousDuplicateAccentPlugin>::default(), Box::<SuperWeirdWordPlugin>::default(), Box::<CjkInvalidStopPlugin>::default(), Box::<ArchaicUpperLowerPlugin>::default(), ];
let mut mean_mess_ratio: Option<f32> = None; let early_calc_period: usize = match decoded_sequence.chars().count() { ..=510 => 32, 511..=1023 => 64, _ => 128, }; // Traverse through chars and detectors for (index, ch) in decoded_sequence .chars() .chain(std::iter::once('\n')) .enumerate() { let mess_char = MessDetectorChar::new(ch); detectors .iter_mut() .filter(|detector| detector.eligible(&mess_char)) .for_each(|detector| detector.feed(&mess_char));
if index % early_calc_period == early_calc_period - 1 { let early_mess_ratio: f32 = detectors.iter().map(|x| x.ratio()).sum(); if early_mess_ratio >= maximum_threshold { mean_mess_ratio = Some(early_mess_ratio); break; } } } let return_ratio = mean_mess_ratio.unwrap_or(detectors.iter().map(|x| x.ratio()).sum());
if log_enabled!(log::Level::Trace) { trace!( "Mess-detector extended-analysis start: early_calc_period={}, mean_mess_ratio={}, maximum_threshold={} \ {}", early_calc_period, return_ratio, maximum_threshold, detectors .iter() .filter(|d| d.ratio() > 0.0) .map(|d| format!("{} produces ratio: {}", d.name(), d.ratio())) .collect::<Vec<String>>() .join("===") ); }
return_ratio}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448use crate::{ md::structs::{MessDetectorChar, MessDetectorCharFlags}, utils::{is_suspiciously_successive_range, remove_accent},};
// Base abstract trait used for mess detection plugins.// All detectors MUST extend and implement given methods.pub(super) trait MessDetectorPlugin { // Name of plugin fn name(&self) -> &str { std::any::type_name::<Self>().split("::").last().unwrap() }
// Determine if given character should be fed in fn eligible(&self, character: &MessDetectorChar) -> bool;
// The main routine to be executed upon character. // Insert the logic in witch the text would be considered chaotic. fn feed(&mut self, character: &MessDetectorChar);
// Compute the chaos ratio based on what your feed() has seen. // Must NOT be lower than 0.; No restriction gt 0. fn ratio(&self) -> f32;}
//// TooManySymbolOrPunctuationPlugin implementation//#[derive(Default)]pub(super) struct TooManySymbolOrPunctuationPlugin { punctuation_count: u64, symbol_count: u64, character_count: u64, last_printable_char: Option<MessDetectorChar>,}
impl MessDetectorPlugin for TooManySymbolOrPunctuationPlugin { fn eligible(&self, character: &MessDetectorChar) -> bool { !character.is(MessDetectorCharFlags::UNPRINTABLE) } fn feed(&mut self, character: &MessDetectorChar) { self.character_count += 1; if (self.last_printable_char.is_none() || *character != self.last_printable_char.unwrap()) && !character.is(MessDetectorCharFlags::COMMON_SAFE) { if character.is(MessDetectorCharFlags::PUNCTUATION) { self.punctuation_count += 1; } else if !character.is(MessDetectorCharFlags::NUMERIC) && character.is(MessDetectorCharFlags::SYMBOL) && !character.is(MessDetectorCharFlags::EMOTICON) { self.symbol_count += 2; } } self.last_printable_char = Some(*character); } fn ratio(&self) -> f32 { if self.character_count == 0 { return 0.0; } let ratio_of_punctuation = (self.punctuation_count + self.symbol_count) as f32 / (self.character_count as f32); if ratio_of_punctuation >= 0.3 { ratio_of_punctuation } else { 0.0 } }}
//// TooManyAccentuatedPlugin implementation//
#[derive(Default)]pub(super) struct TooManyAccentuatedPlugin { character_count: u64, accentuated_count: u64,}
impl MessDetectorPlugin for TooManyAccentuatedPlugin { fn eligible(&self, character: &MessDetectorChar) -> bool { character.is(MessDetectorCharFlags::ALPHABETIC) } fn feed(&mut self, character: &MessDetectorChar) { self.character_count += 1; if character.is(MessDetectorCharFlags::ACCENTUATED) { self.accentuated_count += 1; } } fn ratio(&self) -> f32 { (self.character_count >= 8) .then_some(self.accentuated_count as f32 / self.character_count as f32) .filter(|&ratio| ratio >= 0.35) .unwrap_or(0.0) }}
//// UnprintablePlugin implementation//
#[derive(Default)]pub(super) struct UnprintablePlugin { character_count: u64, unprintable_count: u64,}
impl MessDetectorPlugin for UnprintablePlugin { fn eligible(&self, _character: &MessDetectorChar) -> bool { true } fn feed(&mut self, character: &MessDetectorChar) { if character.is(MessDetectorCharFlags::UNPRINTABLE) { self.unprintable_count += 1; } self.character_count += 1; } fn ratio(&self) -> f32 { if self.character_count == 0 { return 0.0; } (self.unprintable_count as f32 * 8.0) / self.character_count as f32 }}
//// SuspiciousDuplicateAccentPlugin implementation//#[derive(Default)]pub(super) struct SuspiciousDuplicateAccentPlugin { character_count: u64, successive_count: u64, last_latin_character: Option<MessDetectorChar>,}
impl MessDetectorPlugin for SuspiciousDuplicateAccentPlugin { fn eligible(&self, character: &MessDetectorChar) -> bool { character.is(MessDetectorCharFlags::ALPHABETIC) && character.is(MessDetectorCharFlags::LATIN) } fn feed(&mut self, character: &MessDetectorChar) { self.character_count += 1; if self.last_latin_character.is_some() && character.is(MessDetectorCharFlags::ACCENTUATED) && self .last_latin_character .unwrap() .is(MessDetectorCharFlags::ACCENTUATED) { if character.is(MessDetectorCharFlags::UPPERCASE) && self .last_latin_character .unwrap() .is(MessDetectorCharFlags::UPPERCASE) { self.successive_count += 1; }
// Worse if its the same char duplicated with different accent. if remove_accent(character.character) == remove_accent(self.last_latin_character.unwrap().character) { self.successive_count += 1; } } self.last_latin_character = Some(*character); } fn ratio(&self) -> f32 { if self.character_count == 0 { return 0.0; } (self.successive_count as f32 * 2.0) / self.character_count as f32 }}
//// SuspiciousRangePlugin implementation//#[derive(Default)]pub(super) struct SuspiciousRangePlugin { character_count: u64, suspicious_successive_range_count: u64, last_printable_char: Option<MessDetectorChar>,}
impl MessDetectorPlugin for SuspiciousRangePlugin { fn eligible(&self, character: &MessDetectorChar) -> bool { !character.is(MessDetectorCharFlags::UNPRINTABLE) } fn feed(&mut self, character: &MessDetectorChar) { self.character_count += 1;
if character.is(MessDetectorCharFlags::WHITESPACE) || character.is(MessDetectorCharFlags::PUNCTUATION) || character.is(MessDetectorCharFlags::COMMON_SAFE) { self.last_printable_char = None; return; }
if self.last_printable_char.is_none() { self.last_printable_char = Some(*character); return; }
if is_suspiciously_successive_range( self.last_printable_char.unwrap().unicode_range, character.unicode_range, ) { self.suspicious_successive_range_count += 1; }
self.last_printable_char = Some(*character); } fn ratio(&self) -> f32 { (self.character_count > 0) .then_some( ((self.suspicious_successive_range_count as f32) * 2.0) / self.character_count as f32, ) .filter(|&ratio| ratio >= 0.1) .unwrap_or(0.0) }}
//// SuperWeirdWordPlugin implementation//
#[derive(Default)]pub(super) struct SuperWeirdWordPlugin { character_count: u64, word_count: u64, bad_word_count: u64, foreign_long_count: u64, is_current_word_bad: bool, foreign_long_watch: bool, bad_character_count: u64, buffer_accent_count: u64, buffer: Vec<MessDetectorChar>,}
impl MessDetectorPlugin for SuperWeirdWordPlugin { fn eligible(&self, _character: &MessDetectorChar) -> bool { true } fn feed(&mut self, character: &MessDetectorChar) { if character.is(MessDetectorCharFlags::ASCII_ALPHABETIC) { self.buffer.push(*character); if character.is(MessDetectorCharFlags::ACCENTUATED) { self.buffer_accent_count += 1; } self.foreign_long_watch |= (!character.is(MessDetectorCharFlags::LATIN) || character.is(MessDetectorCharFlags::ACCENTUATED)) && !character.is(MessDetectorCharFlags::CJK) && !character.is(MessDetectorCharFlags::HANGUL) && !character.is(MessDetectorCharFlags::KATAKANA) && !character.is(MessDetectorCharFlags::HIRAGANA) && !character.is(MessDetectorCharFlags::THAI); return; } if self.buffer.is_empty() { return; }
if character.is(MessDetectorCharFlags::WHITESPACE) || character.is(MessDetectorCharFlags::PUNCTUATION) || character.is(MessDetectorCharFlags::SEPARATOR) { self.word_count += 1; let buffer_length = self.buffer.len(); self.character_count += buffer_length as u64;
if buffer_length >= 4 { if (self.buffer_accent_count as f32 / buffer_length as f32) > 0.34 { self.is_current_word_bad = true; }
// Word/Buffer ending with an upper case accentuated letter are so rare, // that we will consider them all as suspicious. Same weight as foreign_long suspicious. let last_char = self.buffer.last().unwrap(); if last_char.is(MessDetectorCharFlags::ACCENTUATED) && last_char.is(MessDetectorCharFlags::UPPERCASE) { self.foreign_long_count += 1; self.is_current_word_bad = true; } } if buffer_length >= 24 && self.foreign_long_watch { let uppercase_count = self .buffer .iter() .filter(|&c| c.is(MessDetectorCharFlags::UPPERCASE)) .count(); let mut probable_camel_cased: bool = false;
if uppercase_count > 0 && (uppercase_count as f32 / buffer_length as f32) <= 0.3 { probable_camel_cased = true; }
if !probable_camel_cased { self.foreign_long_count += 1; self.is_current_word_bad = true; } }
if self.is_current_word_bad { self.bad_word_count += 1; self.bad_character_count += self.buffer.len() as u64; self.is_current_word_bad = false; }
self.foreign_long_watch = false; self.buffer.clear(); self.buffer_accent_count = 0; } else if !character.is(MessDetectorCharFlags::WEIRD_SAFE) && !character.is(MessDetectorCharFlags::ASCII_DIGIT) && character.is(MessDetectorCharFlags::SYMBOL) { self.is_current_word_bad = true; self.buffer.push(*character); } } fn ratio(&self) -> f32 { if self.word_count <= 10 && self.foreign_long_count == 0 { return 0.0; } self.bad_character_count as f32 / self.character_count as f32 }}
//// CjkInvalidStopPlugin implementation//// GB(Chinese) based encoding often render the stop incorrectly when the content does not fit and// can be easily detected. Searching for the overuse of '丅' and '丄'.#[derive(Default)]pub(super) struct CjkInvalidStopPlugin { wrong_stop_count: u64, cjk_character_count: u64,}
impl MessDetectorPlugin for CjkInvalidStopPlugin { fn eligible(&self, _: &MessDetectorChar) -> bool { true } fn feed(&mut self, character: &MessDetectorChar) { if "丅丄".contains(character.character) { self.wrong_stop_count += 1; return; } if character.is(MessDetectorCharFlags::CJK) { self.cjk_character_count += 1; } } fn ratio(&self) -> f32 { if self.cjk_character_count < 16 { return 0.0; } self.wrong_stop_count as f32 / self.cjk_character_count as f32 }}
//// ArchaicUpperLowerPlugin implementation//
pub(super) struct ArchaicUpperLowerPlugin { buf: bool, current_ascii_only: bool, character_count_since_last_sep: u64, successive_upper_lower_count: u64, successive_upper_lower_count_final: u64, character_count: u64, last_alpha_seen: Option<MessDetectorChar>,}
impl Default for ArchaicUpperLowerPlugin { fn default() -> Self { ArchaicUpperLowerPlugin { buf: false, current_ascii_only: true, character_count_since_last_sep: 0, successive_upper_lower_count: 0, successive_upper_lower_count_final: 0, character_count: 0, last_alpha_seen: None, } }}
impl MessDetectorPlugin for ArchaicUpperLowerPlugin { fn eligible(&self, _: &MessDetectorChar) -> bool { true } fn feed(&mut self, character: &MessDetectorChar) { if !(character.is(MessDetectorCharFlags::ALPHABETIC) && character.is(MessDetectorCharFlags::CASE_VARIABLE)) && self.character_count_since_last_sep > 0 { if self.character_count_since_last_sep <= 64 && !character.is(MessDetectorCharFlags::ASCII_DIGIT) && !self.current_ascii_only { self.successive_upper_lower_count_final += self.successive_upper_lower_count; }
self.successive_upper_lower_count = 0; self.character_count_since_last_sep = 0; self.last_alpha_seen = None; self.buf = false; self.character_count += 1; self.current_ascii_only = true;
return; }
self.current_ascii_only &= character.is(MessDetectorCharFlags::ASCII);
if let Some(tmp_last_alpha) = self.last_alpha_seen { if (character.is(MessDetectorCharFlags::UPPERCASE) && tmp_last_alpha.is(MessDetectorCharFlags::LOWERCASE)) || (character.is(MessDetectorCharFlags::LOWERCASE) && tmp_last_alpha.is(MessDetectorCharFlags::UPPERCASE)) { if self.buf { self.successive_upper_lower_count += 2; self.buf = false; } else { self.buf = true; } } else { self.buf = false; } }
self.character_count += 1; self.character_count_since_last_sep += 1; self.last_alpha_seen = Some(*character); } fn ratio(&self) -> f32 { if self.character_count == 0 { return 0.0; } self.successive_upper_lower_count_final as f32 / self.character_count as f32 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197use bitflags::bitflags;use cached::proc_macro::cached;use cached::UnboundCache;use icu_properties::{maps, sets, GeneralCategory, GeneralCategoryGroup, Script};
use crate::consts::{COMMON_SAFE_ASCII_CHARACTERS, UTF8_MAXIMAL_ALLOCATION};use crate::utils::{in_range, is_accentuated, unicode_range};
// Mess Plugin Char representation// used to collect additional information about char// and eliminate repeated calculations#[derive(Copy, Clone, PartialEq)]pub struct MessDetectorCharFlags(u32);
bitflags! { impl MessDetectorCharFlags: u32 { const WHITESPACE = 0b0000_0000_0000_0000_0000_0000_0000_0001; const UNPRINTABLE = 0b0000_0000_0000_0000_0000_0000_0000_0010; const SYMBOL = 0b0000_0000_0000_0000_0000_0000_0000_0100; const EMOTICON = 0b0000_0000_0000_0000_0000_0000_0000_1000; const COMMON_SAFE = 0b0000_0000_0000_0000_0000_0000_0001_0000; const WEIRD_SAFE = 0b0000_0000_0000_0000_0000_0000_0010_0000; const PUNCTUATION = 0b0000_0000_0000_0000_0000_0000_0100_0000; const SEPARATOR = 0b0000_0000_0000_0000_0000_0000_1000_0000; const ASCII = 0b0000_0000_0000_0000_0000_0001_0000_0000; const ASCII_ALPHABETIC = 0b0000_0000_0000_0000_0000_0010_0000_0000; const ASCII_GRAPHIC = 0b0000_0000_0000_0000_0000_0100_0000_0000; const ASCII_DIGIT = 0b0000_0000_0000_0000_0000_1000_0000_0000; const LATIN = 0b0000_0000_0000_0000_0001_0000_0000_0000; const ALPHABETIC = 0b0000_0000_0000_0000_0010_0000_0000_0000; const ACCENTUATED = 0b0000_0000_0000_0000_0100_0000_0000_0000; const CJK = 0b0000_0000_0000_0000_1000_0000_0000_0000; const HANGUL = 0b0000_0000_0000_0001_0000_0000_0000_0000; const KATAKANA = 0b0000_0000_0000_0010_0000_0000_0000_0000; const HIRAGANA = 0b0000_0000_0000_0100_0000_0000_0000_0000; const THAI = 0b0000_0000_0000_1000_0000_0000_0000_0000; const CASE_VARIABLE = 0b0000_0000_0001_0000_0000_0000_0000_0000; const LOWERCASE = 0b0000_0000_0010_0000_0000_0000_0000_0000; const UPPERCASE = 0b0000_0000_0100_0000_0000_0000_0000_0000; const NUMERIC = 0b0000_0000_1000_0000_0000_0000_0000_0000; }}
#[derive(Copy, Clone)]pub(crate) struct MessDetectorChar { pub character: char, pub flags: MessDetectorCharFlags, pub unicode_range: Option<&'static str>,}
impl PartialEq for MessDetectorChar { fn eq(&self, other: &Self) -> bool { self.character == other.character }}
impl MessDetectorChar { pub fn new(character: char) -> Self { new_mess_detector_character(character) }
pub fn is(&self, flag: MessDetectorCharFlags) -> bool { self.flags.contains(flag) }}
#[cached( type = "UnboundCache<char, MessDetectorChar>", create = "{ UnboundCache::with_capacity(UTF8_MAXIMAL_ALLOCATION) }", convert = r#"{ character }"#)]fn new_mess_detector_character(character: char) -> MessDetectorChar { let mut flags = MessDetectorCharFlags::empty(); // unicode information let gc = maps::general_category().get(character);
// PLEASE NOTE! In case of idiomatic refactoring // take in account performance. Sometimes match could be used but it // will require calculate all conditions and can decrease performance // in comparison to usual if then else
// ascii probing if character.is_ascii() { flags.insert(MessDetectorCharFlags::ASCII); if character.is_ascii_graphic() { flags.insert(MessDetectorCharFlags::ASCII_GRAPHIC); if character.is_ascii_alphabetic() { flags.insert(MessDetectorCharFlags::ASCII_ALPHABETIC); } else if character.is_ascii_digit() { flags.insert(MessDetectorCharFlags::ASCII_DIGIT); } } }
let range = unicode_range(character);
// whitespace if character.is_whitespace() { flags.insert(MessDetectorCharFlags::WHITESPACE); flags.insert(MessDetectorCharFlags::SEPARATOR); } else { // safe symbols (non-whitespace) if COMMON_SAFE_ASCII_CHARACTERS.contains(character) { flags.insert(MessDetectorCharFlags::COMMON_SAFE); } if "<>-=~|_".contains(character) { flags.insert(MessDetectorCharFlags::WEIRD_SAFE); }
// numeric if flags.contains(MessDetectorCharFlags::ASCII_DIGIT) || character.is_numeric() { flags.insert(MessDetectorCharFlags::NUMERIC); } else if flags.contains(MessDetectorCharFlags::ASCII_ALPHABETIC) || character.is_alphabetic() { // alphabetic flags.insert(MessDetectorCharFlags::ALPHABETIC); if character.is_lowercase() { flags.insert(MessDetectorCharFlags::LOWERCASE); flags.insert(MessDetectorCharFlags::CASE_VARIABLE); } else if character.is_uppercase() { flags.insert(MessDetectorCharFlags::UPPERCASE); flags.insert(MessDetectorCharFlags::CASE_VARIABLE); } } else if !flags.contains(MessDetectorCharFlags::ASCII_GRAPHIC) && !['\x1A', '\u{FEFF}'].contains(&character) && GeneralCategoryGroup::Control.contains(gc) { flags.insert(MessDetectorCharFlags::UNPRINTABLE); }
// emoticon if sets::emoji_component().contains(character) || sets::emoji_modifier().contains(character) || sets::emoji_modifier_base().contains(character) || sets::emoji_presentation().contains(character) // || sets::emoji().contains(character) //tests::md::test_mess_ratio fails { flags.insert(MessDetectorCharFlags::EMOTICON); }
// separator if ['|', '+', '<', '>'].contains(&character) || GeneralCategoryGroup::Separator.contains(gc) || matches!( gc, GeneralCategory::OtherPunctuation | GeneralCategory::DashPunctuation | GeneralCategory::ConnectorPunctuation ) { flags.insert(MessDetectorCharFlags::SEPARATOR); } }
// punctuation if GeneralCategoryGroup::Punctuation.contains(gc) { flags.insert(MessDetectorCharFlags::PUNCTUATION); }
// symbol if GeneralCategoryGroup::Number.contains(gc) || GeneralCategoryGroup::Symbol.contains(gc) || in_range(range, &["Forms"]) { flags.insert(MessDetectorCharFlags::SYMBOL); }
match maps::script().get(character) { Script::Latin => flags.insert(MessDetectorCharFlags::LATIN), // latin Script::Han => flags.insert(MessDetectorCharFlags::CJK), // han implies cjk Script::Hangul => flags.insert(MessDetectorCharFlags::HANGUL), Script::Katakana => flags.insert(MessDetectorCharFlags::KATAKANA), Script::Hiragana => flags.insert(MessDetectorCharFlags::HIRAGANA), Script::Thai => flags.insert(MessDetectorCharFlags::THAI), _ => { // ideographic() includes some characters such as vietnamese that might not be Han // but still be part of the expanded CJK(V) ideographs // if sets::ideographic().contains(character) if sets::unified_ideograph().contains(character) { flags.insert(MessDetectorCharFlags::CJK) } } }
// accentuated if is_accentuated(character) { flags.insert(MessDetectorCharFlags::ACCENTUATED); }
// create new object MessDetectorChar { character, flags, unicode_range: range, }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171use charset_normalizer_rs::entity::{CLINormalizerArgs, CLINormalizerResult, NormalizerSettings};use charset_normalizer_rs::from_path;use clap::Parser;use dialoguer::Confirm;use env_logger::Env;use ordered_float::OrderedFloat;use std::fs::File;use std::io::Write;use std::{fs, process};
fn normalizer(args: &CLINormalizerArgs) -> Result<i32, String> { match (args.replace, args.normalize, args.force, args.threshold) { (true, false, _, _) => return Err("Use --replace in addition to --normalize only.".into()), (false, _, true, _) => return Err("Use --force in addition to --replace only.".into()), (_, _, _, threshold) if !(0.0..=1.0).contains(&threshold) => { return Err("--threshold VALUE should be between 0.0 and 1.0.".into()) } _ => {} }
let mut results: Vec<CLINormalizerResult> = vec![]; let settings = NormalizerSettings { threshold: OrderedFloat(args.threshold), ..Default::default() };
// go through the files for path in &args.files { let full_path = &mut fs::canonicalize(path).map_err(|err| err.to_string())?; let matches = from_path(full_path, Some(settings.clone()))?; match matches.get_best() { None => { results.push(CLINormalizerResult { path: full_path.clone(), language: "Unknown".to_string(), chaos: format!("{:.1}", 1.0), coherence: format!("{:.1}", 0.0), is_preferred: true, ..Default::default() }); eprintln!( "Unable to identify originating encoding for {:?}. {}", full_path, if args.threshold < 1.0 { "Maybe try increasing maximum amount of chaos." } else { "" } ); } Some(best_guess) => { // add main result & alternative results for m in matches.iter() { let normalize_result = CLINormalizerResult { path: full_path.clone(), encoding: Some(m.encoding().to_string()), encoding_aliases: m .encoding_aliases() .iter() .map(|s| (*s).to_string()) .collect(), alternative_encodings: m .suitable_encodings() .iter() .filter(|&e| e != m.encoding()) .cloned() .collect(), language: format!("{}", m.most_probably_language()), alphabets: m.unicode_ranges(), has_sig_or_bom: m.bom(), chaos: format!("{:.1}", m.chaos_percents()), coherence: format!("{:.1}", m.coherence_percents()), unicode_path: None, is_preferred: true, }; if m == best_guess { results.insert(0, normalize_result); } else if args.alternatives { results.push(normalize_result); } else { break; } }
// normalizing if need if args.normalize { if best_guess.encoding().starts_with("utf") { eprintln!( "{:?} file does not need to be normalized, as it already came from unicode.", full_path, ); continue; }
// force or confirm of replacement if !args.replace { let filename = full_path.file_name().unwrap().to_str().unwrap(); let filename = match filename.rsplit_once('.') { None => format!("{}.{}", filename, best_guess.encoding()), Some(split) => { format!("{}.{}.{}", split.0, best_guess.encoding(), split.1) } }; full_path.set_file_name(filename); } else if !args.force && !Confirm::new() .with_prompt(format!( "Are you sure to normalize {:?} by replacing it?", full_path, )) .interact() .unwrap_or(false) { continue; }
// save path to result results[0].unicode_path = Some(full_path.clone());
// replace file contents if let Err(err) = File::create(full_path).and_then(|mut file| { file.write_all(best_guess.decoded_payload().unwrap().as_bytes()) }) { return Err(err.to_string()); } } } } }
// print out results if args.minimal { for path in &args.files { let full_path = fs::canonicalize(path).map_err(|err| err.to_string())?; println!( "{}", results .iter() .filter(|r| r.path == full_path) .map(|r| r.encoding.clone().unwrap_or("undefined".to_string())) .collect::<Vec<_>>() .join(", ") ); } } else { println!( "{}", if results.len() > 1 { serde_json::to_string_pretty(&results).unwrap() } else { serde_json::to_string_pretty(&results[0]).unwrap() } ); } Ok(0)}
pub fn main() { let args = CLINormalizerArgs::parse();
// verbose mode if args.verbose { env_logger::Builder::from_env(Env::default().default_filter_or("trace")).init(); }
// run normalizer match normalizer(&args) { Err(e) => panic!("{e}"), Ok(exit_code) => process::exit(exit_code), }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219use chardetng::EncodingDetector;use charset_normalizer_rs::consts::CHARDET_CORRESPONDENCE;use charset_normalizer_rs::entity::{PerformanceArgs, PerformanceResult};use charset_normalizer_rs::from_bytes;use charset_normalizer_rs::utils::get_large_test_datasets;use clap::Parser;use encoding::label::encoding_from_whatwg_label;use encoding::DecoderTrap;use log::trace;use std::collections::{BTreeMap, HashMap};use std::fs::File;use std::io::Read;use std::process;use std::time::{Duration, Instant};
// Check resultfn check_result( correct_encodings: &Vec<String>, guessed_encoding: &String, buffer: &Vec<u8>,) -> bool { // check by encoding name if correct_encodings.iter().any(|e| guessed_encoding == e) { return true; }
// if correct encoding wasn't found we will try to decode and compare results let whatwg_correct_encoding = correct_encodings .first() .and_then(|enc| encoding_from_whatwg_label(enc)); let whatwg_guessed_encoding = encoding_from_whatwg_label(guessed_encoding); match (whatwg_correct_encoding, whatwg_guessed_encoding) { (Some(correct_encoding), Some(guessed_encoding)) => { let correct_decoded = correct_encoding.decode(buffer.as_slice(), DecoderTrap::Strict); let guessed_decoded = guessed_encoding.decode(buffer.as_slice(), DecoderTrap::Strict); match (correct_decoded, guessed_decoded) { (Ok(correct_result), Ok(guessed_result)) => correct_result == guessed_result, _ => false, } } _ => false, }}
// Calculate percentilefn calc_percentile(results: &Vec<PerformanceResult>, percentile: f64) -> Duration { let mut sorted_data: Vec<Duration> = results.iter().map(|r| r.duration).collect(); sorted_data.sort_unstable(); let index = ((percentile / 100.0) * sorted_data.len() as f64) as usize; sorted_data[index]}
// Calculate mean durationfn calc_stat(results: &Vec<PerformanceResult>) -> (Duration, Duration, f32) { let durations: Vec<Duration> = results.iter().map(|r| r.duration).collect(); if durations.is_empty() { // Handle the case where the input vector is empty (avoid division by zero) (Duration::new(0, 0), Duration::new(0, 0), 0.0) } else { // Calculate the total duration by summing all the durations in the vector let total_duration: Duration = durations.iter().sum();
// Divide the total duration by the number of durations to get the mean let num_durations = durations.len() as u32;
// Accuracy let accuracy = 100.0 * results.iter().filter(|r| r.correct).count() as f32 / num_durations as f32;
(total_duration, total_duration / num_durations, accuracy) }}
// Performance comparisonfn performance_compare(args: &PerformanceArgs) -> i32 { // read datasets from /src/tests/data/largesets let datasets = get_large_test_datasets(); if datasets.is_err() { println!("{}", datasets.unwrap_err()); process::exit(1); } let datasets = datasets.unwrap(); let nof_files = datasets.len(); println!("Found {} datasets for performance tests", nof_files);
// tested functions let mut performance_results: HashMap<&str, Vec<PerformanceResult>> = HashMap::new();
// we need BTreeMap as we need preserve keys order let mut tested_functions: BTreeMap<&str, Box<dyn Fn(&Vec<u8>) -> String>> = BTreeMap::new();
///////////////////////////////////////////////////////////////// // Tested functions (libraries) /////////////////////////////////////////////////////////////////
// charset-normalizer-rs tested_functions.insert( "A) charset-normalizer-rs", Box::new(|bytes: &Vec<u8>| { if let Some(gb) = from_bytes(bytes, None).get_best() { gb.encoding().to_string() } else { String::from("None") } }), );
// chardet tested_functions.insert( "B) chardet", Box::new(|bytes: &Vec<u8>| { let detected = &chardet::detect(bytes).0.to_ascii_lowercase(); let alternative = CHARDET_CORRESPONDENCE.get(&detected.as_str()); if let Some(r) = encoding_from_whatwg_label(&detected) { r.whatwg_name() .unwrap_or(alternative.unwrap_or(&r.name())) .to_string() } else { String::from("None") } }), );
// chardetng tested_functions.insert( "C) chardetng", Box::new(|bytes: &Vec<u8>| { let mut ed = EncodingDetector::new(); ed.feed(bytes, true); let found = ed.guess(None, true).name(); found.to_ascii_lowercase().to_string() }), );
// start tests for (filename, correct_encodings) in &datasets { println!("{}", filename);
// read file contents to buffer let mut file = File::open(filename).expect(&format!("Error opening file {}", filename)); let mut buffer = Vec::new(); file.read_to_end(&mut buffer) .expect(&format!("Error reading from file {}", filename));
// multiply buffer buffer = buffer.repeat(args.size_increase as usize);
// traverse tested functions for (&name, &ref foo) in &tested_functions { if !performance_results.contains_key(name) { performance_results.insert(name, vec![]); } let duration = Instant::now(); let guessed_encoding = foo(&buffer); let duration = duration.elapsed();
// save result performance_results .get_mut(name) .unwrap() .push(PerformanceResult { duration, correct: check_result(correct_encodings, &guessed_encoding, &buffer), }); println!(" --> {}: {:?}", name, duration,);
if !correct_encodings.contains(&guessed_encoding.to_string()) { trace!( "{} WRONG DETECTION: {} not in {:?}\nSee {}", name, guessed_encoding, correct_encodings, filename, ); } } }
// Statistics let mut our_accuracy = 0.0; let mut our_total_time: Duration = Duration::new(0, 0); for (&name, _) in &tested_functions { if let Some(results) = performance_results.get(name) { let (total_duration, mean_duration, accuracy) = calc_stat(results); println!("\n------------------------------"); println!("--> {} Conclusions", name); if name == "A) charset-normalizer-rs" { our_accuracy = accuracy; our_total_time = total_duration.clone(); } else { // compare speed in % println!( " --> Faster than charset-normalizer-rs by {:.1} times", our_total_time.as_secs_f32() / total_duration.as_secs_f32(), ); } println!(" --> Accuracy: {:.1}%", accuracy); println!(" --> Total time: {:?}", total_duration); println!(" --> Avg time: {:?}", mean_duration); for p in [50.0, 95.0, 99.0] { println!(" --> {}th: {:?}", p, calc_percentile(results, p)); } } }
// Correct exit code, if charset-normalizer-rs accuracy lower than 95% if our_accuracy < 97.0 { println!("LOW ACCURACY!!!"); 1 } else { 0 }}
// Main functionpub fn main() { let args = PerformanceArgs::parse(); process::exit(performance_compare(&args));}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195use crate::cd::*;use crate::entity::{CoherenceMatch, CoherenceMatches, Language};
#[test]fn test_encoding_unicode_range() { let err_tests = [ "utf-8", "big5", "utf-16le", // multibyte encodings "non-existing-charset", // non-existing ]; for test in &err_tests { assert!(encoding_unicode_range(test).is_err()); }
let ok_tests = [ ("windows-1251", Ok(vec!["Basic Latin", "Cyrillic"])), ("windows-1255", Ok(vec!["Basic Latin", "Hebrew"])), ]; for test in &ok_tests { assert_eq!(encoding_unicode_range(test.0), test.1); }}
#[test]fn test_unicode_range_languages() { let tests = [ ("Cyrillic", Language::Russian), ("Latin Extended Additional", Language::Vietnamese), ("Greek and Coptic", Language::Greek), ]; for (input, lang) in tests { let languages = unicode_range_languages(input); assert!(languages.contains(&&lang)); }}
#[test]fn test_encoding_languages() { let tests = [ ("utf-8", Language::Unknown), ("windows-1251", Language::Russian), ("windows-1255", Language::Hebrew), ]; for (input, lang) in tests { let languages = encoding_languages(input.to_string()); assert!(languages.contains(&&lang)); }}
#[test]fn test_alphabet_languages() { let tests = [ ("В низинах на восточной стороне полуострова Люнген в основном встречаются слюдяные сланцы, филлиты и доломиты. Низменности на западной стороне в основном состоят из слюдяных сланцев и небольшого количества кварцитов. За исключением ледяных шапок на вершинах Йеккеварри и Балггесварри, на полуострове Люнген преобладают каровые ледники", true, None), ("В низинах на восточной стороне полуострова Люнген в основном встречаются слюдяные сланцы, филлиты и доломиты. Низменности на западной стороне в основном состоят из слюдяных сланцев и небольшого количества кварцитов. За исключением ледяных шапок на вершинах Йеккеварри и Балггесварри, на полуострове Люнген преобладают каровые ледники", false, Some(Language::Russian)), ("Ailem ve Ben Adım Ece ve on iki yaşındayım. Her sabah 7'de uyanırım, kahvaltımı yaparım ve okula giderim. Boş zamanlarımda bahçede kitap okumayı severim. Küçük bir erkek kardeşim var. Kardeşim üç yaşında ve resim yapmayı sever. Evde her gün top oynar ve şarkı söyler. Kardeşim ve ben makarna yemeyi severiz. Bazen mutfakta yemekleri biz hazırlarız.", false, Some(Language::Turkish)), ]; for (input, ignore_non_latin, expected) in tests { let characters: Vec<char> = input.chars().collect(); let languages = alphabet_languages(&characters, ignore_non_latin); if expected.is_none() { assert_eq!(languages.len(), 0); } else { assert!(languages.contains(&&expected.unwrap())); } }}
#[test]fn test_alpha_unicode_split() { let tests = [ ( "Люнгенские Альпы (норв. Lyngsalpene, сев.‑саам. Ittuvárit, квенск. Yykeänvaarat) — горный \ массив на северо-востоке фюльке Тромс-ог-Финнмарк в Норвегии, к востоку от города Тромсё", vec![ "люнгенскиеальпынорвсевсаамквенскгорныймассивнасеверовостокефюлькетромсогфиннмарквнорвегииквостокуотгородатромсё", "lyngsalpeneittuvárityykeänvaarat", ] ), ]; for input in tests { let mut layers = alpha_unicode_split(input.0); let mut expected = input.1.clone(); layers.sort_unstable(); expected.sort_unstable(); assert_eq!(layers, expected); }}
#[test]fn test_characters_popularity_compare() { let tests = [ ("оаніирвтесклудмпзяьбгйчхцї", Language::Russian, 0.8, 0.9), ("оаеинстрвлкмдпугяызбйьчхжц", Language::Russian, 1.0, 1.0), ]; for (seq, lang, mmin, mmax) in &tests { let res = characters_popularity_compare(lang, seq).unwrap(); assert!(res >= (*mmin as f32) && res <= (*mmax as f32)); }}
#[test]fn test_filter_alt_coherence_matches() { let input: CoherenceMatches = vec![ CoherenceMatch { language: &Language::English, score: 7.77, }, CoherenceMatch { language: &Language::English, score: 4.44, }, ]; let expected_output: CoherenceMatches = vec![CoherenceMatch { language: &Language::English, score: 7.77, }]; assert_eq!(filter_alt_coherence_matches(&input), expected_output);}
#[test]fn test_merge_coherence_ratios() { let input: Vec<CoherenceMatches> = vec![ vec![ CoherenceMatch { language: &Language::English, score: 7.77, }, CoherenceMatch { language: &Language::English, score: 4.44, }, ], vec![ CoherenceMatch { language: &Language::Ukrainian, score: 5.0, }, CoherenceMatch { language: &Language::Ukrainian, score: 10.0, }, ], vec![CoherenceMatch { language: &Language::Bulgarian, score: 12.0, }], ]; let mut expected_output: CoherenceMatches = vec![ CoherenceMatch { language: &Language::English, score: 6.105, }, CoherenceMatch { language: &Language::Ukrainian, score: 7.5, }, CoherenceMatch { language: &Language::Bulgarian, score: 12.0, }, ]; let mut output = merge_coherence_ratios(&input); output.sort_unstable_by(|a, b| a.score.partial_cmp(&b.score).unwrap()); expected_output.sort_unstable_by(|a, b| a.score.partial_cmp(&b.score).unwrap()); assert_eq!(output, expected_output);}
#[test]fn test_coherence_ratio() { let tests = [ ( "Bсеки човек има право на образование. Oбразованието трябва да бъде безплатно, поне що се отнася до началното и основното образование.", vec![&Language::Bulgarian], ), ( "Lietuviø kalba – ið baltø prokalbës kilusi lietuviø tautos kalba, kuri Lietuvoje yra valstybinë, o Europos Sàjungoje – viena ið oficialiøjø kalbø. Lietuviðkai kalba apie tris milijonus þmoniø (dauguma jø gyvena Lietuvoje). Drauge su latviø, mirusiomis prûsø, jotvingiø ir kitomis baltø kalbomis, priklauso indoeuropieèiø kalbø ðeimos baltø kalbø grupei. Pirmieji lietuviø kalbos raðytiniai paminklai atsirado vëlokai, apie XVI a., taèiau net dabartinë lietuviø kalba pasiþymi dideliu archajiðkumu (ypaè vardaþodþiø linksniavimo srityje).[3] Fonetiðkai ir morfologiðkai konservatyvi lietuviø kalba þymiai artimesnë baltø prokalbei negu naujoviðkesnë latviø kalba.[4] Lietuviø kalba – archajiðkiausia ið gyvøjø indoeuropieèiø kalbø, iðsaugojusi daugybæ indoeuropieèiø prokalbës ypatybiø.[5] Lietuviø kalba skirstoma á dvi pagrindines tarmes: aukðtaièiø ir þemaièiø. Dabartinë bendrinë lietuviø kalba grindþiama vakarø aukðtaièiø kauniðkiø patarme.", vec![&Language::Estonian], ), ( "In a statement by players' union Futpro, which is representing 33-year-old Hermoso, she is quoted as saying in no case did I seek to raise (lift) the president while they embraced on the podium. The Spanish Football Federation (RFEF) said: The RFEF and Mr President will demonstrate each of the lies that are spread either by someone on behalf of the player or, if applicable, by the player hersel. Bсеки човек има право на образование. Oбразованието трябва да бъде безплатно, поне що се отнася до началното и основното образование.", vec![&Language::Bulgarian, &Language::English], ), ];
for (text, expected_languages) in tests { let result = coherence_ratio(text.to_string(), None, None).unwrap(); for lang in expected_languages { assert!(result.iter().any(|cm| cm.language == lang)); } }}123version https://git-lfs.github.com/spec/v1oid sha256:71944d7430c461f0cd6e7fd10cee7eb72786352a3678fc7bc0ae3d410f72aecesize 1570024123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200# ChangelogAll notable changes to charset-normalizer will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [2.0.11](https://github.com/Ousret/charset_normalizer/compare/2.0.10...2.0.11) (2022-01-30)
### Added- Explicit support for Python 3.11 (PR #164)
### Changed- The logging behavior have been completely reviewed, now using only TRACE and DEBUG levels (PR #163 #165)
## [2.0.10](https://github.com/Ousret/charset_normalizer/compare/2.0.9...2.0.10) (2022-01-04)
### Fixed- Fallback match entries might lead to UnicodeDecodeError for large bytes sequence (PR #154)
### Changed- Skipping the language-detection (CD) on ASCII (PR #155)
## [2.0.9](https://github.com/Ousret/charset_normalizer/compare/2.0.8...2.0.9) (2021-12-03)
### Changed- Moderating the logging impact (since 2.0.8) for specific environments (PR #147)
### Fixed- Wrong logging level applied when setting kwarg `explain` to True (PR #146)
## [2.0.8](https://github.com/Ousret/charset_normalizer/compare/2.0.7...2.0.8) (2021-11-24)### Changed- Improvement over Vietnamese detection (PR #126)- MD improvement on trailing data and long foreign (non-pure latin) data (PR #124)- Efficiency improvements in cd/alphabet_languages from [@adbar](https://github.com/adbar) (PR #122)- call sum() without an intermediary list following PEP 289 recommendations from [@adbar](https://github.com/adbar) (PR #129)- Code style as refactored by Sourcery-AI (PR #131) - Minor adjustment on the MD around european words (PR #133)- Remove and replace SRTs from assets / tests (PR #139)- Initialize the library logger with a `NullHandler` by default from [@nmaynes](https://github.com/nmaynes) (PR #135)- Setting kwarg `explain` to True will add provisionally (bounded to function lifespan) a specific stream handler (PR #135)
### Fixed- Fix large (misleading) sequence giving UnicodeDecodeError (PR #137)- Avoid using too insignificant chunk (PR #137)
### Added- Add and expose function `set_logging_handler` to configure a specific StreamHandler from [@nmaynes](https://github.com/nmaynes) (PR #135)- Add `CHANGELOG.md` entries, format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) (PR #141)
## [2.0.7](https://github.com/Ousret/charset_normalizer/compare/2.0.6...2.0.7) (2021-10-11)### Added- Add support for Kazakh (Cyrillic) language detection (PR #109)
### Changed- Further, improve inferring the language from a given single-byte code page (PR #112)- Vainly trying to leverage PEP263 when PEP3120 is not supported (PR #116)- Refactoring for potential performance improvements in loops from [@adbar](https://github.com/adbar) (PR #113)- Various detection improvement (MD+CD) (PR #117)
### Removed- Remove redundant logging entry about detected language(s) (PR #115)
### Fixed- Fix a minor inconsistency between Python 3.5 and other versions regarding language detection (PR #117 #102)
## [2.0.6](https://github.com/Ousret/charset_normalizer/compare/2.0.5...2.0.6) (2021-09-18)### Fixed- Unforeseen regression with the loss of the backward-compatibility with some older minor of Python 3.5.x (PR #100)- Fix CLI crash when using --minimal output in certain cases (PR #103)
### Changed- Minor improvement to the detection efficiency (less than 1%) (PR #106 #101)
## [2.0.5](https://github.com/Ousret/charset_normalizer/compare/2.0.4...2.0.5) (2021-09-14)### Changed- The project now comply with: flake8, mypy, isort and black to ensure a better overall quality (PR #81)- The BC-support with v1.x was improved, the old staticmethods are restored (PR #82)- The Unicode detection is slightly improved (PR #93)- Add syntax sugar \_\_bool\_\_ for results CharsetMatches list-container (PR #91)
### Removed- The project no longer raise warning on tiny content given for detection, will be simply logged as warning instead (PR #92)
### Fixed- In some rare case, the chunks extractor could cut in the middle of a multi-byte character and could mislead the mess detection (PR #95)- Some rare 'space' characters could trip up the UnprintablePlugin/Mess detection (PR #96)- The MANIFEST.in was not exhaustive (PR #78)
## [2.0.4](https://github.com/Ousret/charset_normalizer/compare/2.0.3...2.0.4) (2021-07-30)### Fixed- The CLI no longer raise an unexpected exception when no encoding has been found (PR #70)- Fix accessing the 'alphabets' property when the payload contains surrogate characters (PR #68)- The logger could mislead (explain=True) on detected languages and the impact of one MBCS match (PR #72)- Submatch factoring could be wrong in rare edge cases (PR #72)- Multiple files given to the CLI were ignored when publishing results to STDOUT. (After the first path) (PR #72)- Fix line endings from CRLF to LF for certain project files (PR #67)
### Changed- Adjust the MD to lower the sensitivity, thus improving the global detection reliability (PR #69 #76)- Allow fallback on specified encoding if any (PR #71)
## [2.0.3](https://github.com/Ousret/charset_normalizer/compare/2.0.2...2.0.3) (2021-07-16)### Changed- Part of the detection mechanism has been improved to be less sensitive, resulting in more accurate detection results. Especially ASCII. (PR #63)- According to the community wishes, the detection will fall back on ASCII or UTF-8 in a last-resort case. (PR #64)
## [2.0.2](https://github.com/Ousret/charset_normalizer/compare/2.0.1...2.0.2) (2021-07-15)### Fixed- Empty/Too small JSON payload miss-detection fixed. Report from [@tseaver](https://github.com/tseaver) (PR #59)
### Changed- Don't inject unicodedata2 into sys.modules from [@akx](https://github.com/akx) (PR #57)
## [2.0.1](https://github.com/Ousret/charset_normalizer/compare/2.0.0...2.0.1) (2021-07-13)### Fixed- Make it work where there isn't a filesystem available, dropping assets frequencies.json. Report from [@sethmlarson](https://github.com/sethmlarson). (PR #55)- Using explain=False permanently disable the verbose output in the current runtime (PR #47)- One log entry (language target preemptive) was not show in logs when using explain=True (PR #47)- Fix undesired exception (ValueError) on getitem of instance CharsetMatches (PR #52)
### Changed- Public function normalize default args values were not aligned with from_bytes (PR #53)
### Added- You may now use charset aliases in cp_isolation and cp_exclusion arguments (PR #47)
## [2.0.0](https://github.com/Ousret/charset_normalizer/compare/1.4.1...2.0.0) (2021-07-02)### Changed- 4x to 5 times faster than the previous 1.4.0 release. At least 2x faster than Chardet.- Accent has been made on UTF-8 detection, should perform rather instantaneous.- The backward compatibility with Chardet has been greatly improved. The legacy detect function returns an identical charset name whenever possible.- The detection mechanism has been slightly improved, now Turkish content is detected correctly (most of the time)- The program has been rewritten to ease the readability and maintainability. (+Using static typing)+- utf_7 detection has been reinstated.
### Removed- This package no longer require anything when used with Python 3.5 (Dropped cached_property)- Removed support for these languages: Catalan, Esperanto, Kazakh, Baque, Volapük, Azeri, Galician, Nynorsk, Macedonian, and Serbocroatian.- The exception hook on UnicodeDecodeError has been removed.
### Deprecated- Methods coherence_non_latin, w_counter, chaos_secondary_pass of the class CharsetMatch are now deprecated and scheduled for removal in v3.0
### Fixed- The CLI output used the relative path of the file(s). Should be absolute.
## [1.4.1](https://github.com/Ousret/charset_normalizer/compare/1.4.0...1.4.1) (2021-05-28)### Fixed- Logger configuration/usage no longer conflict with others (PR #44)
## [1.4.0](https://github.com/Ousret/charset_normalizer/compare/1.3.9...1.4.0) (2021-05-21)### Removed- Using standard logging instead of using the package loguru.- Dropping nose test framework in favor of the maintained pytest.- Choose to not use dragonmapper package to help with gibberish Chinese/CJK text.- Require cached_property only for Python 3.5 due to constraint. Dropping for every other interpreter version.- Stop support for UTF-7 that does not contain a SIG.- Dropping PrettyTable, replaced with pure JSON output in CLI.
### Fixed- BOM marker in a CharsetNormalizerMatch instance could be False in rare cases even if obviously present. Due to the sub-match factoring process.- Not searching properly for the BOM when trying utf32/16 parent codec.
### Changed- Improving the package final size by compressing frequencies.json.- Huge improvement over the larges payload.
### Added- CLI now produces JSON consumable output.- Return ASCII if given sequences fit. Given reasonable confidence.
## [1.3.9](https://github.com/Ousret/charset_normalizer/compare/1.3.8...1.3.9) (2021-05-13)
### Fixed- In some very rare cases, you may end up getting encode/decode errors due to a bad bytes payload (PR #40)
## [1.3.8](https://github.com/Ousret/charset_normalizer/compare/1.3.7...1.3.8) (2021-05-12)
### Fixed- Empty given payload for detection may cause an exception if trying to access the `alphabets` property. (PR #39)
## [1.3.7](https://github.com/Ousret/charset_normalizer/compare/1.3.6...1.3.7) (2021-05-12)
### Fixed- The legacy detect function should return UTF-8-SIG if sig is present in the payload. (PR #38)
## [1.3.6](https://github.com/Ousret/charset_normalizer/compare/1.3.5...1.3.6) (2021-02-09)
### Changed- Amend the previous release to allow prettytable 2.0 (PR #35)
## [1.3.5](https://github.com/Ousret/charset_normalizer/compare/1.3.4...1.3.5) (2021-02-08)
### Fixed- Fix error while using the package with a python pre-release interpreter (PR #33)
### Changed- Dependencies refactoring, constraints revised.
### Added- Add python 3.9 and 3.10 to the supported interpreters12345678910<!DOCTYPE html PUBLIC "-//W3C//DTD html 4.01 Transitional//EN" "http://www.w3c.o rg/TR/1999/REC-html401-19991224/loose.dtd"><html lang=en-US xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml"><head profile=http://www.w3.org/2000/08/w3c-synd/#><title>iso-8859-1</title></head><body><h1 id=logo><img height=48 alt="The World Wide Web Consortium (W3C)" src="/Icons/w3c_main" width=315></h1><h2 id=slogan>Leading the Web to Its Full Potential...</h2></body></html>.gitattributes+2
Dataset_Construction/__pycache__/generation.cpython-312.pycAdded
Dataset_Construction/__pycache__/generation.cpython-38.pycAdded
Dataset_Construction/extract_function.pyAdded+174
Dataset_Construction/generation.pyAdded+4
Dataset_Construction/match_function_throughBm25.pyAdded+104
Dataset_Construction/match_function_throughLLM.pyAdded+70
Dataset_Construction/projects/charset-normalizer/python/__init__.pyAdded+46
Dataset_Construction/projects/charset-normalizer/python/__main__.pyAdded+4
Dataset_Construction/projects/charset-normalizer/python/api.pyAdded+626
Dataset_Construction/projects/charset-normalizer/python/cd.pyAdded+395
Dataset_Construction/projects/charset-normalizer/python/cli/__init__.pyAdded+6
Dataset_Construction/projects/charset-normalizer/python/cli/__main__.pyAdded+296
Dataset_Construction/projects/charset-normalizer/python/constant.pyAdded+1995
Dataset_Construction/projects/charset-normalizer/python/legacy.pyAdded+65
Dataset_Construction/projects/charset-normalizer/python/md.pyAdded+615
Dataset_Construction/projects/charset-normalizer/python/models.pyAdded+338
Dataset_Construction/projects/charset-normalizer/python/py.typedAdded
Dataset_Construction/projects/charset-normalizer/python/utils.pyAdded+421
Dataset_Construction/projects/charset-normalizer/python/version.pyAdded+6
Dataset_Construction/projects/charset-normalizer/rust/CODE_OF_CONDUCT.mdAdded+76
Dataset_Construction/projects/charset-normalizer/rust/CONTRIBUTING.mdAdded+73
Dataset_Construction/projects/charset-normalizer/rust/Cargo.lockAdded+1795
Dataset_Construction/projects/charset-normalizer/rust/Cargo.tomlAdded+70
Dataset_Construction/projects/charset-normalizer/rust/LICENSEAdded+22
Dataset_Construction/projects/charset-normalizer/rust/README.mdAdded+199
Dataset_Construction/projects/charset-normalizer/rust/benches/large_datasets.rsAdded+31
Dataset_Construction/projects/charset-normalizer/rust/benches/large_payload.rsAdded+18
Dataset_Construction/projects/charset-normalizer/rust/rust-toolchain.tomlAdded+2
Dataset_Construction/projects/charset-normalizer/rust/src/assets.rsAdded+66
Dataset_Construction/projects/charset-normalizer/rust/src/cd.rsAdded+252
Dataset_Construction/projects/charset-normalizer/rust/src/consts.rsAdded+752
Dataset_Construction/projects/charset-normalizer/rust/src/entity.rsAdded+518
Dataset_Construction/projects/charset-normalizer/rust/src/lib.rsAdded+597
Dataset_Construction/projects/charset-normalizer/rust/src/md.rsAdded+82
Dataset_Construction/projects/charset-normalizer/rust/src/md/plugins.rsAdded+448
Dataset_Construction/projects/charset-normalizer/rust/src/md/structs.rsAdded+197
Dataset_Construction/projects/charset-normalizer/rust/src/normalizer.rsAdded+171
Dataset_Construction/projects/charset-normalizer/rust/src/performance.rsAdded+219
Dataset_Construction/projects/charset-normalizer/rust/src/tests/cd.rsAdded+195
Dataset_Construction/projects/charset-normalizer/rust/src/tests/data/largesets/None/sample-1.gifAdded

Large File Pointer Details
- SHA256: cf4724b2f736ed1a0ae6bc28f1ead963d9cd2c1fd87b6ef32e7799fc1c5c8bda
- Pointer size: 127 Bytes
- Size of remote file: 43 Bytes
Dataset_Construction/projects/charset-normalizer/rust/src/tests/data/largesets/None/sample-1.jpgAdded

Large File Pointer Details
- SHA256: f3651a46cbba2ff2db5d272b03134cfb6b9c0ae3e887eb674e1306af6731b5a7
- Pointer size: 130 Bytes
- Size of remote file: 32.4 kB
Dataset_Construction/projects/charset-normalizer/rust/src/tests/data/largesets/None/sample-1.mp4Added+3
Dataset_Construction/projects/charset-normalizer/rust/src/tests/data/largesets/None/sample-1.pngAdded

Large File Pointer Details
- SHA256: f0d6bb0ca95cf8f025e3ba36cfd888e518bcd1ffbb822c58e0f84bdb9b39a42c
- Pointer size: 129 Bytes
- Size of remote file: 7.98 kB
Dataset_Construction/projects/charset-normalizer/rust/src/tests/data/largesets/None/sample-1.webpAdded

Large File Pointer Details
- SHA256: b22535f44e5683233a14afa3325edd66ae35037d665a3b4ad1b4cd607066bb5b
- Pointer size: 129 Bytes
- Size of remote file: 2.94 kB
Dataset_Construction/projects/charset-normalizer/rust/src/tests/data/largesets/None/sample-1.xlsxAdded
Dataset_Construction/projects/charset-normalizer/rust/src/tests/data/largesets/None/sample-2.pngAdded

Large File Pointer Details
- SHA256: 1a8352b9372452ab024b5dfd3c74cd8fac2c84e7ff152879f83949c4707fd87e
- Pointer size: 129 Bytes
- Size of remote file: 6.15 kB
Dataset_Construction/projects/charset-normalizer/rust/src/tests/data/largesets/None/sample-3.pngAdded

Large File Pointer Details
- SHA256: fd9758e7a7efd038246df6c3ca2e0d9b1637c1b90f98fa56748ab0d0dbfbd36f
- Pointer size: 130 Bytes
- Size of remote file: 14.7 kB
Dataset_Construction/projects/charset-normalizer/rust/src/tests/data/largesets/ascii/CHANGELOG.mdAdded+200
Dataset_Construction/projects/charset-normalizer/rust/src/tests/data/largesets/ascii/_chromium_iso-8859-1_with_no_encoding_specified.htmlAdded+10