| 1 |
|
| 2 |
|
| 3 |
""" |
| 4 |
Detect the dialect using the data consistency measure. |
| 5 |
|
| 6 |
Author: Gertjan van den Burg |
| 7 |
|
| 8 |
""" |
| 9 |
|
| 10 |
from dataclasses import dataclass |
| 11 |
from functools import lru_cache |
| 12 |
|
| 13 |
from typing import Dict |
| 14 |
from typing import Iterable |
| 15 |
from typing import List |
| 16 |
from typing import Optional |
| 17 |
|
| 18 |
from . import field_size_limit |
| 19 |
from .break_ties import tie_breaker |
| 20 |
from .cparser_util import parse_string |
| 21 |
from .detect_pattern import pattern_score |
| 22 |
from .detect_type import DEFAULT_EPS_TYPE |
| 23 |
from .detect_type import TypeDetector |
| 24 |
from .dialect import SimpleDialect |
| 25 |
from .potential_dialects import get_dialects |
| 26 |
|
| 27 |
|
| 28 |
@dataclass |
| 29 |
class ConsistencyScore: |
| 30 |
"""Container to track the consistency score calculation |
| 31 |
|
| 32 |
Parameters |
| 33 |
---------- |
| 34 |
P : float |
| 35 |
The pattern score |
| 36 |
|
| 37 |
T : Optional[float] |
| 38 |
The type score. Can be None if not computed for speed. |
| 39 |
|
| 40 |
Q : Optional[float] |
| 41 |
The consistency score. Can be None if not computed for speed. |
| 42 |
|
| 43 |
""" |
| 44 |
|
| 45 |
P: float |
| 46 |
T: Optional[float] |
| 47 |
Q: Optional[float] |
| 48 |
|
| 49 |
|
| 50 |
class ConsistencyDetector: |
| 51 |
"""Detect the dialect with the data consistency measure |
| 52 |
|
| 53 |
This class uses the data consistency measure to detect the dialect. See the |
| 54 |
paper for details. |
| 55 |
|
| 56 |
Parameters |
| 57 |
---------- |
| 58 |
skip : bool |
| 59 |
Skip computation of the type score for dialects with a low pattern |
| 60 |
score. |
| 61 |
|
| 62 |
verbose : bool |
| 63 |
Print out the dialects considered and their scores. |
| 64 |
|
| 65 |
cache_capacity: int |
| 66 |
The size of the cache for type detection. Caching the type detection |
| 67 |
result greatly speeds up the computation of the consistency measure. |
| 68 |
The size of the cache can be changed to trade off memory use and speed. |
| 69 |
|
| 70 |
""" |
| 71 |
|
| 72 |
def __init__( |
| 73 |
self, |
| 74 |
skip: bool = True, |
| 75 |
verbose: bool = False, |
| 76 |
cache_capacity: int = 100_000, |
| 77 |
) -> None: |
| 78 |
self._skip = skip |
| 79 |
self._verbose = verbose |
| 80 |
self._type_detector = TypeDetector() |
| 81 |
self._cache_capacity = cache_capacity |
| 82 |
|
| 83 |
|
| 84 |
@lru_cache(cache_capacity) |
| 85 |
def cached_is_known_type(cell: str, is_quoted: bool) -> bool: |
| 86 |
return self._type_detector.is_known_type(cell, is_quoted) |
| 87 |
|
| 88 |
self._cached_is_known_type = cached_is_known_type |
| 89 |
|
| 90 |
def detect( |
| 91 |
self, data: str, delimiters: Optional[List[str]] = None |
| 92 |
) -> Optional[SimpleDialect]: |
| 93 |
"""Detect the dialect using the consistency measure |
| 94 |
|
| 95 |
Parameters |
| 96 |
---------- |
| 97 |
data : str |
| 98 |
The data of the file as a string |
| 99 |
|
| 100 |
delimiters : iterable |
| 101 |
List of delimiters to consider. If None, the :func:`get_delimiters` |
| 102 |
function is used to automatically detect this (as described in the |
| 103 |
paper). |
| 104 |
|
| 105 |
Returns |
| 106 |
------- |
| 107 |
dialect : SimpleDialect |
| 108 |
The detected dialect. If no dialect could be detected, returns None. |
| 109 |
|
| 110 |
""" |
| 111 |
self._cached_is_known_type.cache_clear() |
| 112 |
|
| 113 |
|
| 114 |
dialects = get_dialects(data, delimiters=delimiters) |
| 115 |
|
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
old_limit = field_size_limit(len(data) + 1) |
| 120 |
|
| 121 |
scores = self.compute_consistency_scores(data, dialects) |
| 122 |
best_dialects = ConsistencyDetector.get_best_dialects(scores) |
| 123 |
result: Optional[SimpleDialect] = None |
| 124 |
if len(best_dialects) == 1: |
| 125 |
result = best_dialects[0] |
| 126 |
else: |
| 127 |
result = tie_breaker(data, best_dialects) |
| 128 |
|
| 129 |
field_size_limit(old_limit) |
| 130 |
return result |
| 131 |
|
| 132 |
def compute_consistency_scores( |
| 133 |
self, data: str, dialects: List[SimpleDialect] |
| 134 |
) -> Dict[SimpleDialect, ConsistencyScore]: |
| 135 |
"""Compute the consistency score for each dialect |
| 136 |
|
| 137 |
This function computes the consistency score for each dialect. This is |
| 138 |
done by first computing the pattern score for a dialect. If the class |
| 139 |
is instantiated with ``skip`` set to False, it also computes the type |
| 140 |
score for each dialect. If ``skip`` is True (the default), the type |
| 141 |
score is only computed if the pattern score is larger or equal to the |
| 142 |
current best combined score. |
| 143 |
|
| 144 |
Parameters |
| 145 |
---------- |
| 146 |
data : str |
| 147 |
The data of the file as a string |
| 148 |
|
| 149 |
dialects : Iterable[SimpleDialect] |
| 150 |
An iterable of delimiters to consider. |
| 151 |
|
| 152 |
Returns |
| 153 |
------- |
| 154 |
scores : Dict[SimpleDialect, ConsistencyScore] |
| 155 |
A map with a :class:`ConsistencyScore` object for each dialect |
| 156 |
provided as input. |
| 157 |
|
| 158 |
""" |
| 159 |
|
| 160 |
scores: Dict[SimpleDialect, ConsistencyScore] = {} |
| 161 |
incumbent_score = -float("inf") |
| 162 |
for dialect in sorted(dialects): |
| 163 |
P = pattern_score(data, dialect) |
| 164 |
if P < incumbent_score and self._skip: |
| 165 |
scores[dialect] = ConsistencyScore(P, None, None) |
| 166 |
if self._verbose: |
| 167 |
print("%15r:\tP = %15.6f\tskip." % (dialect, P)) |
| 168 |
continue |
| 169 |
|
| 170 |
T = self.compute_type_score(data, dialect) |
| 171 |
Q = P * T |
| 172 |
incumbent_score = max(incumbent_score, Q) |
| 173 |
scores[dialect] = ConsistencyScore(P, T, Q) |
| 174 |
if self._verbose: |
| 175 |
print( |
| 176 |
"%15r:\tP = %15.6f\tT = %15.6f\tQ = %15.6f" |
| 177 |
% (dialect, P, T, Q) |
| 178 |
) |
| 179 |
return scores |
| 180 |
|
| 181 |
@staticmethod |
| 182 |
def get_best_dialects( |
| 183 |
scores: Dict[SimpleDialect, ConsistencyScore] |
| 184 |
) -> List[SimpleDialect]: |
| 185 |
"""Identify the dialects with the highest consistency score""" |
| 186 |
Qscores = [score.Q for score in scores.values()] |
| 187 |
Qmax = -float("inf") |
| 188 |
for q in Qscores: |
| 189 |
if q is None: |
| 190 |
continue |
| 191 |
Qmax = max(Qmax, q) |
| 192 |
return [d for d, score in scores.items() if score.Q == Qmax] |
| 193 |
|
| 194 |
def compute_type_score( |
| 195 |
self, data: str, dialect: SimpleDialect, eps: float = DEFAULT_EPS_TYPE |
| 196 |
) -> float: |
| 197 |
"""Compute the type score""" |
| 198 |
total = known = 0 |
| 199 |
for row in parse_string(data, dialect, return_quoted=True): |
| 200 |
assert all(isinstance(cell, tuple) for cell in row) |
| 201 |
for cell, is_quoted in row: |
| 202 |
total += 1 |
| 203 |
known += self._cached_is_known_type(cell, is_quoted=is_quoted) |
| 204 |
if not total: |
| 205 |
return eps |
| 206 |
return max(eps, known / total) |
| 207 |
|
| 208 |
|
| 209 |
def detect_dialect_consistency( |
| 210 |
data: str, |
| 211 |
delimiters: Optional[Iterable[str]] = None, |
| 212 |
skip: bool = True, |
| 213 |
verbose: bool = False, |
| 214 |
) -> Optional[SimpleDialect]: |
| 215 |
"""Helper function that wraps ConsistencyDetector""" |
| 216 |
|
| 217 |
consistency_detector = ConsistencyDetector(skip=skip, verbose=verbose) |
| 218 |
if delimiters is not None: |
| 219 |
delimiters = list(delimiters) |
| 220 |
return consistency_detector.detect(data, delimiters=delimiters) |