Debian Codegraph @

clevercsv/break_ties.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 """
4 Break ties in the data consistency measure.
5
6 Author: Gertjan van den Burg
7
8 """
9
10 from typing import List
11 from typing import Optional
12
13 from .cparser_util import parse_string
14 from .dialect import SimpleDialect
15 from .utils import pairwise
16
17
18 def tie_breaker(
19 data: str, dialects: List[SimpleDialect]
20 ) -> Optional[SimpleDialect]:
21 """
22 Break ties between dialects.
23
24 This function is used to break ties where possible between two, three, or
25 four dialects that receive the same value for the data consistency measure.
26
27 Parameters
28 ----------
29 data: str
30 The data as a single string
31 dialects: list
32 Dialects that are tied
33
34 Returns
35 -------
36 dialect: SimpleDialect
37 One of the dialects from the list provided or None.
38
39
40 """
41 if len(dialects) == 2:
42 return break_ties_two(data, dialects[0], dialects[1])
43 elif len(dialects) == 3:
44 return break_ties_three(data, dialects[0], dialects[1], dialects[2])
45 elif len(dialects) == 4:
46 return break_ties_four(data, dialects)
47 return None
48
49
50 def reduce_pairwise(
51 data: str, dialects: List[SimpleDialect]
52 ) -> Optional[List[SimpleDialect]]:
53 """Reduce the set of dialects by breaking pairwise ties
54
55 Parameters
56 ----------
57
58 data: str
59 The data of the file as a string
60
61 dialects: list
62 List of SimpleDialect objects
63
64 Returns
65 -------
66 dialects: list
67 List of SimpleDialect objects.
68
69 """
70 equal_delim = len(set([d.delimiter for d in dialects])) == 1
71 if not equal_delim:
72 return None # TODO: This might be wrong, it can just return the input!
73
74 # First, identify dialects that result in the same parsing result.
75 equal_dialects = []
76 for a, b in pairwise(dialects):
77 X = list(parse_string(data, a))
78 Y = list(parse_string(data, b))
79 if X == Y:
80 equal_dialects.append((a, b))
81
82 # Try to break the ties in these pairs
83 new_dialects = set()
84 visited = set()
85 for A, B in equal_dialects:
86 ans = break_ties_two(data, A, B)
87 if ans is not None:
88 new_dialects.add(ans)
89 visited.add(A)
90 visited.add(B)
91
92 # and add the dialects that we didn't visit
93 for d in dialects:
94 if d not in visited:
95 new_dialects.add(d)
96
97 return list(new_dialects)
98
99
100 def _dialects_only_differ_in_field(
101 A: SimpleDialect, B: SimpleDialect, field: str
102 ) -> bool:
103 keys = ["delimiter", "quotechar", "escapechar"]
104 return all(
105 getattr(A, key) == getattr(B, key) for key in keys if key != field
106 )
107
108
109 def break_ties_two(
110 data: str, A: SimpleDialect, B: SimpleDialect
111 ) -> Optional[SimpleDialect]:
112 """Break ties between two dialects.
113
114 This function breaks ties between two dialects that give the same score. We
115 distinguish several cases:
116
117 1. If delimiter and escapechar are the same and one of the quote characters
118 is the empty string. We parse the file with both dialects and check if the
119 parsing result is the same. If it is, the correct dialect is the one with
120 no quotechar, otherwise it's the other one.
121 2. If quotechar and escapechar are the same and the delimiters are comma
122 and space, then we go for comma. Alternatively, if either of the delimiters
123 is the hyphen, we assume it's the other dialect.
124 3. If the delimiter and quotechar is the same and one dialect uses the
125 escapchar and the other doesn't. We break this tie by checking if the
126 escapechar has an effect and if it occurs an even or odd number of times.
127
128 If it's none of these cases, we don't break the tie and return None.
129
130 Parameters
131 ----------
132
133 data: str
134 The data of the file as a string.
135
136 A: SimpleDialect
137 A potential dialect
138
139 B: SimpleDialect
140 A potential dialect
141
142 Returns
143 -------
144
145 dialect: SimpleDialect or None
146 The chosen dialect if the tie can be broken, None otherwise.
147
148 """
149 if _dialects_only_differ_in_field(A, B, "quotechar"):
150 if A.quotechar == "" or B.quotechar == "":
151 d_no = A if A.quotechar == "" else B
152 d_yes = B if d_no == A else A
153
154 X = list(parse_string(data, dialect=d_no))
155 Y = list(parse_string(data, dialect=d_yes))
156
157 if X == Y:
158 # quotechar has no effect
159 return d_no
160 else:
161 # quotechar has an effect
162 return d_yes
163 elif _dialects_only_differ_in_field(A, B, "delimiter"):
164 if set([A.delimiter, B.delimiter]) == set([",", " "]):
165 # Artifact due to type detection (comma as radix point)
166 if A.delimiter == ",":
167 return A
168 else:
169 return B
170 elif A.delimiter == "-" or B.delimiter == "-":
171 # Artifact due to type detection (dash as minus sign)
172 if A.delimiter == "-":
173 return B
174 else:
175 return A
176 elif _dialects_only_differ_in_field(A, B, "escapechar"):
177 Dnone, Descape = (A, B) if A.escapechar == "" else (B, A)
178
179 X = list(parse_string(data, Dnone))
180 Y = list(parse_string(data, Descape))
181
182 # double check shape. Usually if the shape differs the pattern score
183 # should have caught it, but if by a freakish occurance it hasn't then
184 # we can't break this tie (for now)
185 if len(X) != len(Y):
186 return None
187 for row_X, row_Y in zip(X, Y):
188 if len(row_X) != len(row_Y):
189 return None
190
191 cells_escaped = []
192 cells_unescaped = []
193 for row_X, row_Y in zip(X, Y):
194 for u, v in zip(row_X, row_Y):
195 if u != v:
196 cells_unescaped.append(u)
197 cells_escaped.append(v)
198
199 # We will break the ties in the following ways:
200 #
201 # If the escapechar precedes the quotechar an even number of times
202 # within each offending cell, then we think it is a functional escape
203 # and the escaped version is the correct dialect. Note that if an odd
204 # number of escaped quotechars would occur, then the shape of the file
205 # will be different if it is ignored. Only if it occurs an even number
206 # of times within the cell can we get the same shape.
207 for u in cells_unescaped:
208 count = 0
209 for a, b in pairwise(u):
210 if a != Descape.escapechar:
211 continue
212 if a == Descape.escapechar and b == Descape.quotechar:
213 count += 1
214 if count > 0 and count % 2 == 0:
215 return Descape
216 else:
217 return Dnone
218 elif A.delimiter == B.delimiter:
219 Aq, Ae = A.quotechar, A.escapechar
220 Bq, Be = B.quotechar, B.escapechar
221 if (Aq, Ae) == ("", "") or (Bq, Be) == ("", ""):
222 # This case is activated if the escapechar+quotechar combination
223 # occurs in the cells (i.e. "Jill\'s data") but no actual quoting
224 # is done with the quote character.
225 d_no = A if (Aq, Ae) == ("", "") else B
226 d_yes = B if d_no == A else A
227
228 X = list(parse_string(data, dialect=d_no))
229 Y = list(parse_string(data, dialect=d_yes))
230
231 if len(X) != len(Y):
232 return None
233 for row_X, row_Y in zip(X, Y):
234 if len(row_X) != len(row_Y):
235 return None
236
237 # if we're here, then there is no effect on structure.
238 # we test if the only cells that differ are those that have an
239 # escapechar+quotechar combination.
240 assert isinstance(d_yes.escapechar, str)
241 assert isinstance(d_yes.quotechar, str)
242 eq = d_yes.escapechar + d_yes.quotechar
243 for row_X, row_Y in zip(X, Y):
244 for x, y in zip(row_X, row_Y):
245 if x != y:
246 if eq not in x:
247 return None
248
249 # Now we know that the only cells that have the
250 # escapechar+quotechar combination are the cause of the difference.
251 # The right thing to do is to return the dialect that uses them.
252 return d_yes
253
254 return None
255
256
257 def break_ties_three(
258 data: str, A: SimpleDialect, B: SimpleDialect, C: SimpleDialect
259 ) -> Optional[SimpleDialect]:
260 """Break ties between three dialects.
261
262 If the delimiters and the escape characters are all equal, then we look for
263 the dialect that has no quotechar. The tie is broken by calling
264 :func:`break_ties_two` for the dialect without quotechar and another
265 dialect that gives the same parsing result.
266
267 If only the delimiter is the same for all dialects then use
268 :func:`break_ties_two` on the dialects that do not have a quotechar,
269 provided there are only two of these.
270
271 Parameters
272 ----------
273
274 data: str
275 The data of the file as a string
276
277 A: SimpleDialect
278 a dialect
279
280 B: SimpleDialect
281 a dialect
282
283 C: SimpleDialect
284 a dialect
285
286 Returns
287 -------
288
289 dialect: Optional[SimpleDialect]
290 The chosen dialect if the tie can be broken, None otherwise.
291
292 Notes
293 -----
294 We have only observed one tie for each case during development, so
295 this may need to be improved in the future.
296
297 """
298
299 equal_delim = A.delimiter == B.delimiter == C.delimiter
300 equal_escape = A.escapechar == B.escapechar == C.escapechar
301
302 if equal_delim and equal_escape:
303 # difference is *only* in quotechar
304 dialects = [A, B, C]
305
306 pA = list(parse_string(data, A))
307 pB = list(parse_string(data, B))
308 pC = list(parse_string(data, C))
309
310 if len(pA) != len(pB) or len(pA) != len(pC) or len(pB) != len(pC):
311 return None
312
313 p_none, d_none = next(
314 (
315 (p, d)
316 for p, d in zip([pA, pB, pC], dialects)
317 if d.quotechar == ""
318 ),
319 (None, None),
320 )
321 if p_none is None:
322 return None
323 assert d_none is not None
324
325 rem = [
326 (p, d) for p, d in zip([pA, pB, pC], dialects) if not p == p_none
327 ]
328
329 if len(rem) <= 1:
330 # This case was reached for the file
331 # 6da5ab459bcc7c3a5ed2e06d65810958.csv from the GitHub corpus of
332 # the CSV paper. When fixing the delimiter to Tab, rem = [].
333 # Try to reduce pairwise
334 new_dialects = reduce_pairwise(data, dialects)
335 if new_dialects is None:
336 return None
337 if len(new_dialects) == 1:
338 return new_dialects[0]
339 return None
340 if p_none == rem[0][0]:
341 return break_ties_two(data, d_none, rem[0][1])
342 elif len(rem) > 1 and p_none == rem[1][0]:
343 return break_ties_two(data, d_none, rem[1][1])
344 elif equal_delim:
345 # difference is in quotechar *and* escapechar
346
347 # The reasoning here is as follows. If we are in this situation,
348 # then there is both a potential escapechar and there are quotechars,
349 # but the pattern score is the same and the type score can't make a
350 # difference because no cells become clean if we interpret the
351 # quote/escape correctly. This implies that the quote and escape do
352 # have a function. Thus, we find the dialects that have a quote and
353 # defer to break_ties_two.
354
355 dialects = [A, B, C]
356 with_quote = [d for d in dialects if d.quotechar != ""]
357
358 if len(with_quote) != 2:
359 return None
360
361 return break_ties_two(data, with_quote[0], with_quote[1])
362
363 return None
364
365
366 def break_ties_four(
367 data: str, dialects: List[SimpleDialect]
368 ) -> Optional[SimpleDialect]:
369 """Break ties between four dialects.
370
371 This function works by breaking the ties between pairs of dialects that
372 result in the same parsing result (if any). If this reduces the number of
373 dialects, then :func:`break_ties_three` or :func:`break_ties_two` is used,
374 otherwise, the tie can't be broken.
375
376 Ties are only broken if all dialects have the same delimiter.
377
378 Parameters
379 ----------
380
381 data: str
382 The data of the file as a string
383
384 dialects: list
385 List of SimpleDialect objects
386
387 Returns
388 -------
389 dialect: Optional[SimpleDialect]
390 The chosen dialect if the tie can be broken, None otherwise.
391
392 Notes
393 -----
394 We have only observed one case during development where this
395 function was needed. It may need to be revisited in the future if other
396 examples are found.
397
398 """
399 # TODO: Check for length 4, handle more than 4 too?
400
401 equal_delim = len(set([d.delimiter for d in dialects])) == 1
402 if not equal_delim:
403 return None
404
405 reduced_dialects = reduce_pairwise(data, dialects)
406 if reduced_dialects is None:
407 return None
408
409 # Defer to other functions if the number of dialects was reduced
410 if len(reduced_dialects) == 1:
411 return reduced_dialects[0]
412 elif len(reduced_dialects) == 2:
413 return break_ties_two(data, *reduced_dialects)
414 elif len(reduced_dialects) == 3:
415 return break_ties_three(data, *reduced_dialects)
416
417 return None