normalizer.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. import argparse
  2. import sys
  3. from json import dumps
  4. from os.path import abspath
  5. from platform import python_version
  6. from typing import List
  7. from charset_normalizer import from_fp
  8. from charset_normalizer.models import CliDetectionResult
  9. from charset_normalizer.version import __version__
  10. def query_yes_no(question: str, default: str = "yes") -> bool:
  11. """Ask a yes/no question via input() and return their answer.
  12. "question" is a string that is presented to the user.
  13. "default" is the presumed answer if the user just hits <Enter>.
  14. It must be "yes" (the default), "no" or None (meaning
  15. an answer is required of the user).
  16. The "answer" return value is True for "yes" or False for "no".
  17. Credit goes to (c) https://stackoverflow.com/questions/3041986/apt-command-line-interface-like-yes-no-input
  18. """
  19. valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False}
  20. if default is None:
  21. prompt = " [y/n] "
  22. elif default == "yes":
  23. prompt = " [Y/n] "
  24. elif default == "no":
  25. prompt = " [y/N] "
  26. else:
  27. raise ValueError("invalid default answer: '%s'" % default)
  28. while True:
  29. sys.stdout.write(question + prompt)
  30. choice = input().lower()
  31. if default is not None and choice == "":
  32. return valid[default]
  33. elif choice in valid:
  34. return valid[choice]
  35. else:
  36. sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n")
  37. def cli_detect(argv: List[str] = None) -> int:
  38. """
  39. CLI assistant using ARGV and ArgumentParser
  40. :param argv:
  41. :return: 0 if everything is fine, anything else equal trouble
  42. """
  43. parser = argparse.ArgumentParser(
  44. description="The Real First Universal Charset Detector. "
  45. "Discover originating encoding used on text file. "
  46. "Normalize text to unicode."
  47. )
  48. parser.add_argument(
  49. "files", type=argparse.FileType("rb"), nargs="+", help="File(s) to be analysed"
  50. )
  51. parser.add_argument(
  52. "-v",
  53. "--verbose",
  54. action="store_true",
  55. default=False,
  56. dest="verbose",
  57. help="Display complementary information about file if any. "
  58. "Stdout will contain logs about the detection process.",
  59. )
  60. parser.add_argument(
  61. "-a",
  62. "--with-alternative",
  63. action="store_true",
  64. default=False,
  65. dest="alternatives",
  66. help="Output complementary possibilities if any. Top-level JSON WILL be a list.",
  67. )
  68. parser.add_argument(
  69. "-n",
  70. "--normalize",
  71. action="store_true",
  72. default=False,
  73. dest="normalize",
  74. help="Permit to normalize input file. If not set, program does not write anything.",
  75. )
  76. parser.add_argument(
  77. "-m",
  78. "--minimal",
  79. action="store_true",
  80. default=False,
  81. dest="minimal",
  82. help="Only output the charset detected to STDOUT. Disabling JSON output.",
  83. )
  84. parser.add_argument(
  85. "-r",
  86. "--replace",
  87. action="store_true",
  88. default=False,
  89. dest="replace",
  90. help="Replace file when trying to normalize it instead of creating a new one.",
  91. )
  92. parser.add_argument(
  93. "-f",
  94. "--force",
  95. action="store_true",
  96. default=False,
  97. dest="force",
  98. help="Replace file without asking if you are sure, use this flag with caution.",
  99. )
  100. parser.add_argument(
  101. "-t",
  102. "--threshold",
  103. action="store",
  104. default=0.1,
  105. type=float,
  106. dest="threshold",
  107. help="Define a custom maximum amount of chaos allowed in decoded content. 0. <= chaos <= 1.",
  108. )
  109. parser.add_argument(
  110. "--version",
  111. action="version",
  112. version="Charset-Normalizer {} - Python {}".format(
  113. __version__, python_version()
  114. ),
  115. help="Show version information and exit.",
  116. )
  117. args = parser.parse_args(argv)
  118. if args.replace is True and args.normalize is False:
  119. print("Use --replace in addition of --normalize only.", file=sys.stderr)
  120. return 1
  121. if args.force is True and args.replace is False:
  122. print("Use --force in addition of --replace only.", file=sys.stderr)
  123. return 1
  124. if args.threshold < 0.0 or args.threshold > 1.0:
  125. print("--threshold VALUE should be between 0. AND 1.", file=sys.stderr)
  126. return 1
  127. x_ = []
  128. for my_file in args.files:
  129. matches = from_fp(my_file, threshold=args.threshold, explain=args.verbose)
  130. best_guess = matches.best()
  131. if best_guess is None:
  132. print(
  133. 'Unable to identify originating encoding for "{}". {}'.format(
  134. my_file.name,
  135. "Maybe try increasing maximum amount of chaos."
  136. if args.threshold < 1.0
  137. else "",
  138. ),
  139. file=sys.stderr,
  140. )
  141. x_.append(
  142. CliDetectionResult(
  143. abspath(my_file.name),
  144. None,
  145. [],
  146. [],
  147. "Unknown",
  148. [],
  149. False,
  150. 1.0,
  151. 0.0,
  152. None,
  153. True,
  154. )
  155. )
  156. else:
  157. x_.append(
  158. CliDetectionResult(
  159. abspath(my_file.name),
  160. best_guess.encoding,
  161. best_guess.encoding_aliases,
  162. [
  163. cp
  164. for cp in best_guess.could_be_from_charset
  165. if cp != best_guess.encoding
  166. ],
  167. best_guess.language,
  168. best_guess.alphabets,
  169. best_guess.bom,
  170. best_guess.percent_chaos,
  171. best_guess.percent_coherence,
  172. None,
  173. True,
  174. )
  175. )
  176. if len(matches) > 1 and args.alternatives:
  177. for el in matches:
  178. if el != best_guess:
  179. x_.append(
  180. CliDetectionResult(
  181. abspath(my_file.name),
  182. el.encoding,
  183. el.encoding_aliases,
  184. [
  185. cp
  186. for cp in el.could_be_from_charset
  187. if cp != el.encoding
  188. ],
  189. el.language,
  190. el.alphabets,
  191. el.bom,
  192. el.percent_chaos,
  193. el.percent_coherence,
  194. None,
  195. False,
  196. )
  197. )
  198. if args.normalize is True:
  199. if best_guess.encoding.startswith("utf") is True:
  200. print(
  201. '"{}" file does not need to be normalized, as it already came from unicode.'.format(
  202. my_file.name
  203. ),
  204. file=sys.stderr,
  205. )
  206. if my_file.closed is False:
  207. my_file.close()
  208. continue
  209. o_ = my_file.name.split(".") # type: List[str]
  210. if args.replace is False:
  211. o_.insert(-1, best_guess.encoding)
  212. if my_file.closed is False:
  213. my_file.close()
  214. elif (
  215. args.force is False
  216. and query_yes_no(
  217. 'Are you sure to normalize "{}" by replacing it ?'.format(
  218. my_file.name
  219. ),
  220. "no",
  221. )
  222. is False
  223. ):
  224. if my_file.closed is False:
  225. my_file.close()
  226. continue
  227. try:
  228. x_[0].unicode_path = abspath("./{}".format(".".join(o_)))
  229. with open(x_[0].unicode_path, "w", encoding="utf-8") as fp:
  230. fp.write(str(best_guess))
  231. except IOError as e:
  232. print(str(e), file=sys.stderr)
  233. if my_file.closed is False:
  234. my_file.close()
  235. return 2
  236. if my_file.closed is False:
  237. my_file.close()
  238. if args.minimal is False:
  239. print(
  240. dumps(
  241. [el.__dict__ for el in x_] if len(x_) > 1 else x_[0].__dict__,
  242. ensure_ascii=True,
  243. indent=4,
  244. )
  245. )
  246. else:
  247. for my_file in args.files:
  248. print(
  249. ", ".join(
  250. [
  251. el.encoding or "undefined"
  252. for el in x_
  253. if el.path == abspath(my_file.name)
  254. ]
  255. )
  256. )
  257. return 0
  258. if __name__ == "__main__":
  259. cli_detect()