Debian Codegraph @

clevercsv/detect_type.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 """
4 Code for computing the type score.
5
6 Author: Gertjan van den Burg
7
8 """
9
10 import json
11
12 from typing import Dict
13 from typing import List
14 from typing import Optional
15 from typing import Pattern
16
17 from ._regexes import DEFAULT_TYPE_REGEXES
18 from .cparser_util import parse_string
19 from .dialect import SimpleDialect
20
21 DEFAULT_EPS_TYPE: float = 1e-10
22
23
24 class TypeDetector:
25 def __init__(
26 self,
27 patterns: Optional[Dict[str, Pattern[str]]] = None,
28 strip_whitespace: bool = True,
29 ) -> None:
30 self.patterns = patterns or DEFAULT_TYPE_REGEXES.copy()
31 self.strip_whitespace = strip_whitespace
32 self._register_type_tests()
33
34 def _register_type_tests(self) -> None:
35 self._type_tests = [
36 ("empty", self.is_empty),
37 ("url", self.is_url),
38 ("email", self.is_email),
39 ("ipv4", self.is_ipv4),
40 ("number", self.is_number),
41 ("time", self.is_time),
42 ("percentage", self.is_percentage),
43 ("currency", self.is_currency),
44 ("unix_path", self.is_unix_path),
45 ("nan", self.is_nan),
46 ("date", self.is_date),
47 ("datetime", self.is_datetime),
48 ("unicode_alphanum", self.is_unicode_alphanum),
49 ("bytearray", self.is_bytearray),
50 ("json", self.is_json_obj),
51 ]
52
53 def list_known_types(self) -> List[str]:
54 return [tt[0] for tt in self._type_tests]
55
56 def is_known_type(self, cell: str, is_quoted: bool = False) -> bool:
57 return self.detect_type(cell, is_quoted=is_quoted) is not None
58
59 def detect_type(self, cell: str, is_quoted: bool = False) -> Optional[str]:
60 cell = cell.strip() if self.strip_whitespace else cell
61 for name, func in self._type_tests:
62 if func(cell, is_quoted=is_quoted):
63 return name
64 return None
65
66 def _run_regex(self, cell: str, patname: str) -> bool:
67 cell = cell.strip() if self.strip_whitespace else cell
68 pat = self.patterns.get(patname, None)
69 assert pat is not None
70 match = pat.fullmatch(cell)
71 return match is not None
72
73 def is_number(self, cell: str, is_quoted: bool = False) -> bool:
74 if cell == "":
75 return False
76 if self._run_regex(cell, "number_1"):
77 return True
78 if self._run_regex(cell, "number_2"):
79 return True
80 if self._run_regex(cell, "number_3"):
81 return True
82 return False
83
84 def is_ipv4(self, cell: str, is_quoted: bool = False) -> bool:
85 return self._run_regex(cell, "ipv4")
86
87 def is_url(self, cell: str, is_quoted: bool = False) -> bool:
88 return self._run_regex(cell, "url")
89
90 def is_email(self, cell: str, is_quoted: bool = False) -> bool:
91 return self._run_regex(cell, "email")
92
93 def is_unicode_alphanum(self, cell: str, is_quoted: bool = False) -> bool:
94 if is_quoted:
95 return self._run_regex(cell, "unicode_alphanum_quoted")
96 return self._run_regex(cell, "unicode_alphanum")
97
98 def is_date(self, cell: str, is_quoted: bool = False) -> bool:
99 # This function assumes the cell is not a number.
100 cell = cell.strip() if self.strip_whitespace else cell
101 if not cell:
102 return False
103 if not cell[0].isdigit():
104 return False
105 return self._run_regex(cell, "date")
106
107 def is_time(self, cell: str, is_quoted: bool = False) -> bool:
108 cell = cell.strip() if self.strip_whitespace else cell
109 if not cell:
110 return False
111 if not cell[0].isdigit():
112 return False
113 return (
114 self._run_regex(cell, "time_hmm")
115 or self._run_regex(cell, "time_hhmm")
116 or self._run_regex(cell, "time_hhmmss")
117 or self._run_regex(cell, "time_hhmmsszz")
118 )
119
120 def is_empty(self, cell: str, is_quoted: bool = False) -> bool:
121 return cell == ""
122
123 def is_percentage(self, cell: str, is_quoted: bool = False) -> bool:
124 return cell.endswith("%") and self.is_number(cell.rstrip("%"))
125
126 def is_currency(self, cell: str, is_quoted: bool = False) -> bool:
127 pat = self.patterns.get("currency", None)
128 assert pat is not None
129 m = pat.fullmatch(cell)
130 if m is None:
131 return False
132 grp = m.group(1)
133 if not self.is_number(grp):
134 return False
135 return True
136
137 def is_datetime(self, cell: str, is_quoted: bool = False) -> bool:
138 # Takes care of cells with '[date] [time]' and '[date]T[time]' (iso)
139 if not cell:
140 return False
141
142 if not cell[0].isdigit():
143 return False
144
145 if " " in cell:
146 parts = cell.split(" ")
147 if len(parts) > 2:
148 return False
149 return self.is_date(parts[0]) and self.is_time(parts[1])
150 elif "T" in cell:
151 parts = cell.split("T")
152 if len(parts) > 2:
153 return False
154 isdate = self.is_date(parts[0])
155 if not isdate:
156 return False
157 # [date]T[time] or [date]T[time]Z
158 if parts[1].endswith("Z") and self.is_time(parts[1][:-1]):
159 return True
160 if self.is_time(parts[1]):
161 return True
162 # [date]T[time][+-][time]
163 if "+" in parts[1]:
164 subparts = parts[1].split("+")
165 istime1 = self.is_time(subparts[0])
166 if not istime1:
167 return False
168 istime2 = self.is_time(subparts[1])
169 if istime2:
170 return True
171 if self._run_regex(subparts[1], "time_HHMM"):
172 return True
173 if self._run_regex(subparts[1], "time_HH"):
174 return True
175 elif "-" in parts[1]:
176 subparts = parts[1].split("-")
177 istime1 = self.is_time(subparts[0])
178 if not istime1:
179 return False
180 istime2 = self.is_time(subparts[1])
181 if istime2:
182 return True
183 if self._run_regex(subparts[1], "time_HHMM"):
184 return True
185 if self._run_regex(subparts[1], "time_HH"):
186 return True
187 return False
188
189 def is_nan(self, cell: str, is_quoted: bool = False) -> bool:
190 if cell.lower() in ["n/a", "na", "nan"]:
191 return True
192 return False
193
194 def is_unix_path(self, cell: str, is_quoted: bool = False) -> bool:
195 return self._run_regex(cell, "unix_path")
196
197 def is_bytearray(self, cell: str, is_quoted: bool = False) -> bool:
198 return cell.startswith("bytearray(b") and cell.endswith(")")
199
200 def is_json_obj(self, cell: str, is_quoted: bool = False) -> bool:
201 if not (cell.startswith("{") and cell.endswith("}")):
202 return False
203 try:
204 _ = json.loads(cell)
205 except json.JSONDecodeError:
206 return False
207 return True
208
209
210 def gen_known_type(cells):
211 """
212 Utility that yields a generator over whether or not the provided cells are
213 of a known type or not.
214 """
215 td = TypeDetector()
216 for cell in cells:
217 yield td.is_known_type(cell)
218
219
220 def type_score(
221 data: str, dialect: SimpleDialect, eps: float = DEFAULT_EPS_TYPE
222 ) -> float:
223 """
224 Compute the type score as the ratio of cells with a known type.
225
226 Parameters
227 ----------
228 data: str
229 the data as a single string
230
231 dialect: SimpleDialect
232 the dialect to use
233
234 eps: float
235 the minimum value of the type score
236
237 Returns
238 -------
239 type_score: float
240 The computed type score
241
242 """
243 total = 0
244 known = 0
245 td = TypeDetector()
246 for row in parse_string(data, dialect, return_quoted=True):
247 for cell, is_quoted in row:
248 total += 1
249 known += td.is_known_type(cell, is_quoted=is_quoted)
250 if total == 0:
251 return eps
252 return max(eps, known / total)