Debian Codegraph @

clevercsv/console/commands/detect.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 import json
4 import sys
5 import time
6
7 from typing import Any
8 from typing import Dict
9
10 from wilderness import Command
11
12 from clevercsv.wrappers import detect_dialect
13
14 from ._docs import FLAG_DESCRIPTIONS
15 from ._utils import parse_int
16
17
18 class DetectCommand(Command):
19 _description = "Detect the dialect of a CSV file."
20
21 def __init__(self) -> None:
22 super().__init__(
23 name="detect",
24 title="Detect the dialect of a CSV file",
25 description=self._description,
26 extra_sections={"CleverCSV": "Part of the CleverCSV suite"},
27 )
28
29 def register(self) -> None:
30 self.add_argument("path", help="Path to the CSV file")
31 self.add_argument(
32 "-c",
33 "--consistency",
34 action="store_true",
35 help="Only use the consistency measure for detection.",
36 description=(
37 "By default, the dialect of CSV files is detected using "
38 "atwo-step process. First, a strict set of checks is used to "
39 "see if the file adheres to a very basic format (for example, "
40 "when all cells in the file are integers). If none of these "
41 "checks succeed, the data consistency measure of Van den "
42 "Burg, et al. (2019) is used to detect the dialect. With this "
43 "option, you can force the detection to always use the data "
44 "consistency measure. This can be useful for testing or "
45 "research purposes, for instance."
46 ),
47 )
48 self.add_argument(
49 "-e",
50 "--encoding",
51 help="Set the encoding of the file",
52 description=FLAG_DESCRIPTIONS["encoding"],
53 )
54 self.add_argument(
55 "-n",
56 "--num-chars",
57 help="Number of characters to use for detection",
58 type=int,
59 description=FLAG_DESCRIPTIONS["num-chars"],
60 )
61 group = self.add_mutually_exclusive_group()
62 group.add_argument(
63 "-p",
64 "--plain",
65 action="store_true",
66 help="Print the components of the dialect on separate lines",
67 )
68 group.add_argument(
69 "-j",
70 "--json",
71 action="store_true",
72 help="Print the components of the dialect as a JSON object",
73 description=(
74 "Print the dialect to standard output in the form of a JSON "
75 "object. This object will always have the 'delimiter', "
76 "'quotechar', 'escapechar', and 'strict' keys. If "
77 "--add-runtime is specified, it will also have a 'runtime' "
78 "key."
79 ),
80 )
81 self.add_argument(
82 "--no-skip",
83 action="store_true",
84 help="Don't skip type detection for dialects with a low pattern score",
85 description=(
86 "The data consistency score used for dialect detection "
87 "consists of two components: a pattern score and a type "
88 "score. The type score lies between 0 and 1. When computing "
89 "the data consistency measures for different dialects, we "
90 "skip the computation of the type score if we see that the "
91 "pattern score is lower than the best data consistency score "
92 "we've seen so far. This option can be used to disable this "
93 "behaviour and compute the type score for all dialects. This "
94 "is mainly useful for debugging and testing purposes."
95 ),
96 )
97 self.add_argument(
98 "--add-runtime",
99 action="store_true",
100 help="Add the runtime of the detection to the detection output.",
101 )
102
103 def handle(self) -> int:
104 verbose = self.args.verbose
105 num_chars = parse_int(self.args.num_chars, "num-chars")
106 method = "consistency" if self.args.consistency else "auto"
107 skip = not self.args.no_skip
108
109 t_start = time.time()
110 dialect = detect_dialect(
111 self.args.path,
112 num_chars=num_chars,
113 encoding=self.args.encoding,
114 verbose=verbose,
115 method=method,
116 skip=skip,
117 )
118 runtime = time.time() - t_start
119
120 if dialect is None:
121 print("Error: Dialect detection failed.", file=sys.stderr)
122 return 1
123
124 if self.args.plain:
125 print(f"delimiter = {dialect.delimiter}".strip())
126 print(f"quotechar = {dialect.quotechar}".strip())
127 print(f"escapechar = {dialect.escapechar}".strip())
128 if self.args.add_runtime:
129 print(f"runtime = {runtime}")
130 elif self.args.json:
131 dialect_dict: Dict[str, Any] = dialect.to_dict()
132 if self.args.add_runtime:
133 dialect_dict["runtime"] = runtime
134 print(json.dumps(dialect_dict))
135 else:
136 print("Detected: " + str(dialect))
137 if self.args.add_runtime:
138 print(f"Runtime: {runtime:.6f} seconds")
139 return 0