Debian Codegraph @

clevercsv/normal_form.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 """
4 Detect the dialect with very strict functional tests.
5
6 This module uses so-called "normal forms" to detect the dialect of CSV files.
7 Normal forms are detected with strict functional tests. The normal forms are
8 used as a pre-test to check if files are simple enough that computing the data
9 consistency measure is not necessary.
10
11 Author: Gertjan van den Burg
12
13 """
14
15 import itertools
16
17 from typing import Callable
18 from typing import Iterable
19 from typing import List
20 from typing import Optional
21 from typing import Tuple
22
23 import regex
24
25 from .dialect import SimpleDialect
26 from .escape import is_potential_escapechar
27 from .utils import pairwise
28
29 DELIMS: List[str] = [",", ";", "|", "\t"]
30 QUOTECHARS: List[str] = ["'", '"']
31
32
33 def detect_dialect_normal(
34 data: str,
35 encoding: str = "UTF-8",
36 delimiters: Optional[Iterable[str]] = None,
37 verbose: bool = False,
38 ) -> Optional[SimpleDialect]:
39 """Detect the normal form of a file from a given sample
40
41 Parameters
42 ----------
43 data : str
44 The data as a single string
45
46 encoding : str
47 The encoding of the data
48
49 Returns
50 -------
51 dialect : SimpleDialect
52 The dialect detected using normal forms, or None if no such dialect can
53 be found.
54 """
55 if delimiters is None:
56 delimiters = DELIMS
57 delimiters = list(delimiters)
58 for delim, quotechar in itertools.product(delimiters, QUOTECHARS):
59 if maybe_has_escapechar(data, encoding, delim, quotechar):
60 if verbose:
61 print("Not normal, has potential escapechar.")
62 return None
63
64 form_and_dialect: List[
65 Tuple[int, Callable[[List[str], SimpleDialect], bool], SimpleDialect]
66 ] = []
67
68 for delim in delimiters:
69 dialect = SimpleDialect(delimiter=delim, quotechar="", escapechar="")
70 form_and_dialect.append((2, is_form_2, dialect))
71
72 for delim, quotechar in itertools.product(delimiters, QUOTECHARS):
73 dialect = SimpleDialect(
74 delimiter=delim, quotechar=quotechar, escapechar=""
75 )
76 form_and_dialect.append((1, is_form_1, dialect))
77 form_and_dialect.append((3, is_form_3, dialect))
78 form_and_dialect.append((5, is_form_5, dialect))
79 for quotechar in QUOTECHARS:
80 dialect = SimpleDialect(
81 delimiter="", quotechar=quotechar, escapechar=""
82 )
83 form_and_dialect.append((4, is_form_4, dialect))
84
85 form_and_dialect.append(
86 (
87 4,
88 is_form_4,
89 SimpleDialect(delimiter="", quotechar="", escapechar=""),
90 )
91 )
92
93 rows = split_file(data)
94
95 for ID, form_func, dialect in form_and_dialect:
96 if form_func(rows, dialect):
97 if verbose:
98 print("Matched normal form %i." % ID)
99 return dialect
100 if verbose:
101 print("Didn't match any normal forms.")
102 return None
103
104
105 def is_quoted_cell(cell: str, quotechar: str) -> bool:
106 if len(cell) < 2:
107 return False
108 return cell[0] == quotechar and cell[-1] == quotechar
109
110
111 def is_any_quoted_cell(cell: str) -> bool:
112 return is_quoted_cell(cell, "'") or is_quoted_cell(cell, '"')
113
114
115 def is_any_partial_quoted_cell(cell: str) -> bool:
116 if len(cell) < 1:
117 return False
118 return (
119 cell[0] == '"' or cell[0] == "'" or cell[-1] == '"' or cell[-1] == "'"
120 )
121
122
123 def is_empty_quoted(cell: str, quotechar: str) -> bool:
124 return len(cell) == 2 and is_quoted_cell(cell, quotechar)
125
126
127 def is_empty_unquoted(cell: str) -> bool:
128 return cell == ""
129
130
131 def is_any_empty(cell: str) -> bool:
132 return (
133 is_empty_unquoted(cell)
134 or is_empty_quoted(cell, "'")
135 or is_empty_quoted(cell, '"')
136 )
137
138
139 def has_delimiter(string: str, delim: str) -> bool:
140 return delim in string
141
142
143 def has_nested_quotes(string: str, quotechar: str) -> bool:
144 return quotechar in string[1:-1]
145
146
147 def maybe_has_escapechar(
148 data: str, encoding: str, delim: str, quotechar: str
149 ) -> bool:
150 if delim not in data and quotechar not in data:
151 return False
152 for u, v in pairwise(data):
153 if v in [delim, quotechar] and is_potential_escapechar(u, encoding):
154 return True
155 return False
156
157
158 def strip_trailing_crnl(data: str) -> str:
159 while data.endswith("\n"):
160 data = data.rstrip("\n")
161 while data.endswith("\r"):
162 data = data.rstrip("\r")
163 return data
164
165
166 def every_row_has_delim(rows: List[str], dialect: SimpleDialect) -> bool:
167 assert dialect.delimiter is not None
168 for row in rows:
169 if not has_delimiter(row, dialect.delimiter):
170 return False
171 return True
172
173
174 def every_row_has_delim_and_is_the_same_length(
175 rows: List[str], dialect: SimpleDialect
176 ) -> bool:
177 assert dialect.delimiter is not None
178 if len(rows) == 0:
179 return False
180
181 first_len = len(split_row(rows[0], dialect))
182 for row in rows:
183 if not has_delimiter(row, dialect.delimiter):
184 return False
185 if len(split_row(row, dialect)) != first_len:
186 return False
187 return True
188
189
190 def is_elementary(cell: str) -> bool:
191 return (
192 regex.fullmatch(r"[a-zA-Z0-9\.\_\&\-\@\+\%\(\)\ \/]+", cell)
193 is not None
194 )
195
196
197 def split_file(data: str) -> List[str]:
198 data = strip_trailing_crnl(data)
199 if "\r\n" in data:
200 return data.split("\r\n")
201 elif "\n" in data:
202 return data.split("\n")
203 elif "\r" in data:
204 return data.split("\r")
205 return [data]
206
207
208 def split_row(row: str, dialect: SimpleDialect) -> List[str]:
209 # no nested quotes
210 assert dialect.quotechar is not None
211 if (not dialect.quotechar) or (dialect.quotechar not in row):
212 if not dialect.delimiter:
213 return [row]
214 return row.split(dialect.delimiter)
215
216 cells = []
217 current_cell = ""
218 in_quotes = False
219 for c in row:
220 if c == dialect.delimiter and not in_quotes:
221 cells.append(current_cell)
222 current_cell = ""
223 elif c == dialect.quotechar:
224 in_quotes = not in_quotes
225 current_cell += c
226 else:
227 current_cell += c
228 if current_cell:
229 cells.append(current_cell)
230 return cells
231
232
233 def is_form_1(rows: List[str], dialect: SimpleDialect) -> bool:
234 # All cells quoted, quoted empty allowed, no nested quotes, more than one
235 # column
236 assert dialect.quotechar is not None
237
238 if not every_row_has_delim_and_is_the_same_length(rows, dialect):
239 return False
240
241 for row in rows:
242 cells = split_row(row, dialect)
243 if len(cells) == 1:
244 return False
245 for cell in cells:
246 # No empty cells
247 if is_empty_unquoted(cell):
248 return False
249
250 # All cells must be quoted
251 if not is_quoted_cell(cell, dialect.quotechar):
252 return False
253
254 # No quotes inside quotes
255 if has_nested_quotes(cell, dialect.quotechar):
256 return False
257
258 return True
259
260
261 def is_form_2(rows: List[str], dialect: SimpleDialect) -> bool:
262 # All unquoted, empty allowed, all elementary
263 if not every_row_has_delim_and_is_the_same_length(rows, dialect):
264 return False
265
266 for row in rows:
267 cells = split_row(row, dialect)
268 if len(cells) == 1:
269 return False
270 for cell in cells:
271 # All cells must be unquoted
272 if is_any_quoted_cell(cell):
273 return False
274 # All cells must not be partially quoted
275 if is_any_partial_quoted_cell(cell):
276 return False
277 # Cells have to be elementary
278 if not is_empty_unquoted(cell) and not is_elementary(cell):
279 return False
280 return True
281
282
283 def is_form_3(rows: List[str], dialect: SimpleDialect) -> bool:
284 # some quoted, some not quoted, no empty, no nested quotes
285 assert dialect.quotechar is not None
286
287 if not every_row_has_delim_and_is_the_same_length(rows, dialect):
288 return False
289 if len(rows) <= 1:
290 return False
291
292 for row in rows:
293 cells = split_row(row, dialect)
294 if len(cells) == 1:
295 return False
296 for cell in cells:
297 if is_any_empty(cell):
298 return False
299
300 # if it is quoted
301 if is_any_quoted_cell(cell):
302 # but not quoted with the quotechar of the dialect
303 if not is_quoted_cell(cell, dialect.quotechar):
304 # then this form isn't right
305 return False
306 # if it's not quoted
307 else:
308 # and it's not elementary
309 if not is_elementary(cell):
310 # then this form isn't right
311 return False
312
313 return True
314
315
316 def is_form_4(rows: List[str], dialect: SimpleDialect) -> bool:
317 # no delim, single column (either entirely quoted or entirely unquoted)
318 assert dialect.quotechar is not None
319
320 if len(rows) <= 1:
321 return False
322
323 unquoted_search = regex.compile(r"[^A-Za-z0-9.\_&\-]").search
324 quoted_search = regex.compile(r"[^A-Za-z0-9.\_&\-\ ]").search
325 for row in rows:
326 cell = row[:]
327 if dialect.quotechar == "":
328 if is_any_quoted_cell(cell):
329 return False
330 if unquoted_search(cell):
331 return False
332 else:
333 if not is_quoted_cell(cell, dialect.quotechar):
334 return False
335 if quoted_search(cell[1:-1]):
336 return False
337
338 return True
339
340
341 def is_form_5(rows: List[str], dialect: SimpleDialect) -> bool:
342 # all rows quoted, no nested quotes
343 # basically form 2 but with quotes around each row
344 if not every_row_has_delim(rows, dialect):
345 return False
346 if len(rows) <= 1:
347 return False
348
349 for row in rows:
350 if not (
351 len(row) > 2
352 and row[0] == dialect.quotechar
353 and row[-1] == dialect.quotechar
354 ):
355 return False
356
357 newrows = []
358 for row in rows:
359 newrows.append(row[1:-1])
360
361 return is_form_2(newrows, dialect)