csv-detective 0.8.1.dev1416__py3-none-any.whl → 0.8.1.dev1440__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. {csv_detective-0.8.1.dev1416.data → csv_detective-0.8.1.dev1440.data}/data/share/csv_detective/CHANGELOG.md +2 -1
  2. csv_detective-0.8.1.dev1440.data/data/share/csv_detective/LICENSE +21 -0
  3. {csv_detective-0.8.1.dev1416.data → csv_detective-0.8.1.dev1440.data}/data/share/csv_detective/README.md +6 -39
  4. csv_detective-0.8.1.dev1440.dist-info/METADATA +267 -0
  5. {csv_detective-0.8.1.dev1416.dist-info → csv_detective-0.8.1.dev1440.dist-info}/RECORD +9 -29
  6. csv_detective-0.8.1.dev1440.dist-info/licenses/LICENSE +21 -0
  7. csv_detective/detect_fields/FR/other/code_csp_insee/code_csp_insee.txt +0 -498
  8. csv_detective/detect_fields/FR/other/csp_insee/csp_insee.txt +0 -571
  9. csv_detective/detect_fields/FR/other/insee_ape700/insee_ape700.txt +0 -733
  10. csv_detective/detect_fields/geo/iso_country_code_alpha2/iso_country_code_alpha2.txt +0 -495
  11. csv_detective/detect_fields/geo/iso_country_code_alpha3/iso_country_code_alpha3.txt +0 -251
  12. csv_detective/detect_fields/geo/iso_country_code_numeric/iso_country_code_numeric.txt +0 -251
  13. csv_detective/detection/columns.py +0 -89
  14. csv_detective/detection/encoding.py +0 -27
  15. csv_detective/detection/engine.py +0 -46
  16. csv_detective/detection/formats.py +0 -145
  17. csv_detective/detection/headers.py +0 -32
  18. csv_detective/detection/rows.py +0 -18
  19. csv_detective/detection/separator.py +0 -44
  20. csv_detective/detection/variables.py +0 -98
  21. csv_detective/parsing/columns.py +0 -139
  22. csv_detective/parsing/compression.py +0 -11
  23. csv_detective/parsing/csv.py +0 -55
  24. csv_detective/parsing/excel.py +0 -169
  25. csv_detective/parsing/load.py +0 -97
  26. csv_detective/parsing/text.py +0 -61
  27. csv_detective-0.8.1.dev1416.data/data/share/csv_detective/LICENSE.AGPL.txt +0 -661
  28. csv_detective-0.8.1.dev1416.dist-info/METADATA +0 -42
  29. csv_detective-0.8.1.dev1416.dist-info/licenses/LICENSE.AGPL.txt +0 -661
  30. {csv_detective-0.8.1.dev1416.dist-info → csv_detective-0.8.1.dev1440.dist-info}/WHEEL +0 -0
  31. {csv_detective-0.8.1.dev1416.dist-info → csv_detective-0.8.1.dev1440.dist-info}/entry_points.txt +0 -0
  32. {csv_detective-0.8.1.dev1416.dist-info → csv_detective-0.8.1.dev1440.dist-info}/top_level.txt +0 -0
@@ -1,98 +0,0 @@
1
- from ast import literal_eval
2
- import logging
3
- from time import time
4
-
5
- import pandas as pd
6
-
7
- from csv_detective.utils import display_logs_depending_process_time
8
-
9
-
10
- def detect_continuous_variable(table: pd.DataFrame, continuous_th: float = 0.9, verbose: bool = False):
11
- """
12
- Detects whether a column contains continuous variables. We consider a continuous column
13
- one that contains a considerable amount of float values.
14
- We removed the integers as we then end up with postal codes, insee codes, and all sort
15
- of codes and types.
16
- This is not optimal but it will do for now.
17
- """
18
- # if we need this again in the future, could be first based on columns detected as int/float to cut time
19
-
20
- def check_threshold(serie: pd.Series, continuous_th: float) -> bool:
21
- count = serie.value_counts().to_dict()
22
- total_nb = len(serie)
23
- if float in count:
24
- nb_floats = count[float]
25
- else:
26
- return False
27
- if nb_floats / total_nb >= continuous_th:
28
- return True
29
- else:
30
- return False
31
-
32
- def parses_to_integer(value: str):
33
- try:
34
- value = value.replace(",", ".")
35
- value = literal_eval(value)
36
- return type(value)
37
- # flake8: noqa
38
- except:
39
- return False
40
-
41
- if verbose:
42
- start = time()
43
- logging.info("Detecting continuous columns")
44
- res = table.apply(
45
- lambda serie: check_threshold(serie.apply(parses_to_integer), continuous_th)
46
- )
47
- if verbose:
48
- display_logs_depending_process_time(
49
- f"Detected {sum(res)} continuous columns in {round(time() - start, 3)}s",
50
- time() - start,
51
- )
52
- return res.index[res]
53
-
54
-
55
- def detect_categorical_variable(
56
- table: pd.DataFrame,
57
- threshold_pct_categorical: float = 0.05,
58
- max_number_categorical_values: int = 25,
59
- verbose: bool = False,
60
- ):
61
- """
62
- Heuristically detects whether a table (df) contains categorical values according to
63
- the number of unique values contained.
64
- As the idea of detecting categorical values is to then try to learn models to predict
65
- them, we limit categorical values to at most 25 different modes or at most 5% disparity.
66
- Postal code, insee code, code region and so on, may be thus not considered categorical values.
67
- :param table:
68
- :param threshold_pct_categorical:
69
- :param max_number_categorical_values:
70
- :return:
71
- """
72
-
73
- def abs_number_different_values(column_values: pd.Series):
74
- return column_values.nunique()
75
-
76
- def rel_number_different_values(column_values: pd.Series):
77
- return column_values.nunique() / len(column_values)
78
-
79
- def detect_categorical(column_values: pd.Series):
80
- abs_unique_values = abs_number_different_values(column_values)
81
- rel_unique_values = rel_number_different_values(column_values)
82
- if (
83
- abs_unique_values <= max_number_categorical_values
84
- or rel_unique_values <= threshold_pct_categorical
85
- ):
86
- return True
87
- return False
88
-
89
- if verbose:
90
- start = time()
91
- logging.info("Detecting categorical columns")
92
- res = table.apply(lambda serie: detect_categorical(serie))
93
- if verbose:
94
- display_logs_depending_process_time(
95
- f"Detected {sum(res)} categorical columns out of {len(table.columns)} in {round(time() - start, 3)}s",
96
- time() - start,
97
- )
98
- return res.index[res], res
@@ -1,139 +0,0 @@
1
- import logging
2
- from time import time
3
- from typing import Callable
4
-
5
- import pandas as pd
6
-
7
- from csv_detective.utils import display_logs_depending_process_time
8
-
9
-
10
- def test_col_val(
11
- serie: pd.Series,
12
- test_func: Callable,
13
- proportion: float = 0.9,
14
- skipna: bool = True,
15
- limited_output: bool = False,
16
- verbose: bool = False,
17
- ):
18
- """Tests values of the serie using test_func.
19
- - skipna : if True indicates that NaNs are not counted as False
20
- - proportion : indicates the proportion of values that have to pass the test
21
- for the serie to be detected as a certain format
22
- """
23
- if verbose:
24
- start = time()
25
-
26
- # TODO : change for a cleaner method and only test columns in modules labels
27
- def apply_test_func(serie: pd.Series, test_func: Callable, _range: int):
28
- return serie.sample(n=_range).apply(test_func)
29
- try:
30
- if skipna:
31
- serie = serie[serie.notnull()]
32
- ser_len = len(serie)
33
- if ser_len == 0:
34
- return 0.0
35
- if not limited_output:
36
- result = apply_test_func(serie, test_func, ser_len).sum() / ser_len
37
- return result if result >= proportion else 0.0
38
- else:
39
- if proportion == 1: # Then try first 1 value, then 5, then all
40
- for _range in [
41
- min(1, ser_len),
42
- min(5, ser_len),
43
- ser_len,
44
- ]: # Pour ne pas faire d'opérations inutiles, on commence par 1,
45
- # puis 5 valeurs puis la serie complète
46
- if all(apply_test_func(serie, test_func, _range)):
47
- # print(serie.name, ': check OK')
48
- pass
49
- else:
50
- return 0.0
51
- return 1.0
52
- else:
53
- # if we have a proportion, statistically it's OK to analyse up to 10k rows
54
- # (arbitrary number) and get a significant result
55
- to_analyse = min(ser_len, 10000)
56
- result = apply_test_func(serie, test_func, to_analyse).sum() / to_analyse
57
- return result if result >= proportion else 0.0
58
- finally:
59
- if verbose and time() - start > 3:
60
- display_logs_depending_process_time(
61
- f"\t/!\\ Column '{serie.name}' took too long ({round(time() - start, 3)}s)",
62
- time() - start
63
- )
64
-
65
-
66
- def test_col_label(label: str, test_func: Callable, proportion: float = 1, limited_output: bool = False):
67
- """Tests label (from header) using test_func.
68
- - proportion : indicates the minimum score to pass the test for the serie
69
- to be detected as a certain format
70
- """
71
- if not limited_output:
72
- return test_func(label)
73
- else:
74
- result = test_func(label)
75
- return result if result >= proportion else 0
76
-
77
-
78
- def test_col(table: pd.DataFrame, all_tests: list, limited_output: bool, skipna: bool = True, verbose: bool = False):
79
- if verbose:
80
- start = time()
81
- logging.info("Testing columns to get types")
82
- test_funcs = dict()
83
- for test in all_tests:
84
- name = test.__name__.split(".")[-1]
85
- test_funcs[name] = {"func": test._is, "prop": test.PROPORTION}
86
- return_table = pd.DataFrame(columns=table.columns)
87
- for idx, (key, value) in enumerate(test_funcs.items()):
88
- if verbose:
89
- start_type = time()
90
- logging.info(f"\t- Starting with type '{key}'")
91
- # improvement lead : put the longest tests behind and make them only if previous tests not satisfactory
92
- # => the following needs to change, "apply" means all columns are tested for one type at once
93
- return_table.loc[key] = table.apply(
94
- lambda serie: test_col_val(
95
- serie,
96
- value["func"],
97
- value["prop"],
98
- skipna=skipna,
99
- limited_output=limited_output,
100
- verbose=verbose,
101
- )
102
- )
103
- if verbose:
104
- display_logs_depending_process_time(
105
- f'\t> Done with type "{key}" in {round(time() - start_type, 3)}s ({idx+1}/{len(test_funcs)})',
106
- time() - start_type
107
- )
108
- if verbose:
109
- display_logs_depending_process_time(f"Done testing columns in {round(time() - start, 3)}s", time() - start)
110
- return return_table
111
-
112
-
113
- def test_label(table: pd.DataFrame, all_tests: list, limited_output: bool, verbose: bool = False):
114
- if verbose:
115
- start = time()
116
- logging.info("Testing labels to get types")
117
- test_funcs = dict()
118
- for test in all_tests:
119
- name = test.__name__.split(".")[-1]
120
- test_funcs[name] = {"func": test._is, "prop": test.PROPORTION}
121
-
122
- return_table = pd.DataFrame(columns=table.columns)
123
- for idx, (key, value) in enumerate(test_funcs.items()):
124
- if verbose:
125
- start_type = time()
126
- return_table.loc[key] = [
127
- test_col_label(
128
- col_name, value["func"], value["prop"], limited_output=limited_output
129
- )
130
- for col_name in table.columns
131
- ]
132
- if verbose:
133
- display_logs_depending_process_time(
134
- f'\t- Done with type "{key}" in {round(time() - start_type, 3)}s ({idx+1}/{len(test_funcs)})',
135
- time() - start_type
136
- )
137
- if verbose:
138
- display_logs_depending_process_time(f"Done testing labels in {round(time() - start, 3)}s", time() - start)
139
- return return_table
@@ -1,11 +0,0 @@
1
- import gzip
2
- from io import BytesIO
3
-
4
-
5
- def unzip(binary_file: BytesIO, engine: str) -> BytesIO:
6
- if engine == "gzip":
7
- with gzip.open(binary_file, mode="rb") as binary_file:
8
- file_content = binary_file.read()
9
- else:
10
- raise NotImplementedError(f"{engine} is not yet supported")
11
- return BytesIO(file_content)
@@ -1,55 +0,0 @@
1
- import logging
2
- from time import time
3
- from typing import TextIO
4
-
5
- import pandas as pd
6
-
7
- from csv_detective.utils import display_logs_depending_process_time
8
-
9
-
10
- def parse_csv(
11
- the_file: TextIO,
12
- encoding: str,
13
- sep: str,
14
- num_rows: int,
15
- skiprows: int,
16
- random_state: int = 42,
17
- verbose: bool = False,
18
- ) -> tuple[pd.DataFrame, int, int]:
19
- if verbose:
20
- start = time()
21
- logging.info("Parsing table")
22
- table = None
23
-
24
- if not isinstance(the_file, str):
25
- the_file.seek(0)
26
-
27
- total_lines = None
28
- for encoding in [encoding, "ISO-8859-1", "utf-8"]:
29
- if encoding is None:
30
- continue
31
-
32
- if "ISO-8859" in encoding:
33
- encoding = "ISO-8859-1"
34
- try:
35
- table = pd.read_csv(
36
- the_file, sep=sep, dtype="unicode", encoding=encoding, skiprows=skiprows
37
- )
38
- total_lines = len(table)
39
- nb_duplicates = len(table.loc[table.duplicated()])
40
- if num_rows > 0:
41
- num_rows = min(num_rows - 1, total_lines)
42
- table = table.sample(num_rows, random_state=random_state)
43
- # else : table is unchanged
44
- break
45
- except TypeError:
46
- print("Trying encoding : {encoding}".format(encoding=encoding))
47
-
48
- if table is None:
49
- raise ValueError("Could not load file")
50
- if verbose:
51
- display_logs_depending_process_time(
52
- f'Table parsed successfully in {round(time() - start, 3)}s',
53
- time() - start,
54
- )
55
- return table, total_lines, nb_duplicates
@@ -1,169 +0,0 @@
1
- from io import BytesIO
2
- from time import time
3
- from typing import Optional
4
-
5
- import openpyxl
6
- import pandas as pd
7
- import requests
8
- import xlrd
9
-
10
- from csv_detective.detection.engine import engine_to_file
11
- from csv_detective.detection.rows import remove_empty_first_rows
12
- from csv_detective.utils import (
13
- display_logs_depending_process_time,
14
- is_url,
15
- )
16
-
17
- NEW_EXCEL_EXT = [".xlsx", ".xlsm", ".xltx", ".xltm"]
18
- OLD_EXCEL_EXT = [".xls"]
19
- OPEN_OFFICE_EXT = [".odf", ".ods", ".odt"]
20
- XLS_LIKE_EXT = NEW_EXCEL_EXT + OLD_EXCEL_EXT + OPEN_OFFICE_EXT
21
-
22
-
23
- def parse_excel(
24
- file_path: str,
25
- num_rows: int = -1,
26
- engine: Optional[str] = None,
27
- sheet_name: Optional[str] = None,
28
- random_state: int = 42,
29
- verbose: bool = False,
30
- ) -> tuple[pd.DataFrame, int, int, str, str, int]:
31
- """"Excel-like parsing is really slow, could be a good improvement for future development"""
32
- if verbose:
33
- start = time()
34
- no_sheet_specified = sheet_name is None
35
-
36
- if (
37
- engine in ['openpyxl', 'xlrd'] or
38
- any([file_path.endswith(k) for k in NEW_EXCEL_EXT + OLD_EXCEL_EXT])
39
- ):
40
- remote_content = None
41
- if is_url(file_path):
42
- r = requests.get(file_path)
43
- r.raise_for_status()
44
- remote_content = BytesIO(r.content)
45
- if not engine:
46
- if any([file_path.endswith(k) for k in NEW_EXCEL_EXT]):
47
- engine = "openpyxl"
48
- else:
49
- engine = "xlrd"
50
- if sheet_name is None:
51
- if verbose:
52
- display_logs_depending_process_time(
53
- f'Detected {engine_to_file[engine]} file, no sheet specified, reading the largest one',
54
- time() - start,
55
- )
56
- try:
57
- if engine == "openpyxl":
58
- # openpyxl doesn't want to open files that don't have a valid extension
59
- # see: https://foss.heptapod.net/openpyxl/openpyxl/-/issues/2157
60
- # if the file is remote, we have a remote content anyway so it's fine
61
- if not remote_content and '.' not in file_path.split('/')[-1]:
62
- with open(file_path, 'rb') as f:
63
- remote_content = BytesIO(f.read())
64
- # faster than loading all sheets
65
- wb = openpyxl.load_workbook(remote_content or file_path, read_only=True)
66
- try:
67
- sizes = {s.title: s.max_row * s.max_column for s in wb.worksheets}
68
- except TypeError:
69
- # sometimes read_only can't get the info, so we have to open the file for real
70
- # this takes more time but it's for a limited number of files
71
- # and it's this or nothing
72
- wb = openpyxl.load_workbook(remote_content or file_path)
73
- sizes = {s.title: s.max_row * s.max_column for s in wb.worksheets}
74
- else:
75
- if remote_content:
76
- wb = xlrd.open_workbook(file_contents=remote_content.read())
77
- else:
78
- wb = xlrd.open_workbook(file_path)
79
- sizes = {s.name: s.nrows * s.ncols for s in wb.sheets()}
80
- sheet_name = max(sizes, key=sizes.get)
81
- except xlrd.biffh.XLRDError:
82
- # sometimes a xls file is recognized as ods
83
- if verbose:
84
- display_logs_depending_process_time(
85
- 'Could not read file with classic xls reader, trying with ODS',
86
- time() - start,
87
- )
88
- engine = "odf"
89
-
90
- if engine == "odf" or any([file_path.endswith(k) for k in OPEN_OFFICE_EXT]):
91
- # for ODS files, no way to get sheets' sizes without
92
- # loading the file one way or another (pandas or pure odfpy)
93
- # so all in one
94
- engine = "odf"
95
- if sheet_name is None:
96
- if verbose:
97
- display_logs_depending_process_time(
98
- f'Detected {engine_to_file[engine]} file, no sheet specified, reading the largest one',
99
- time() - start,
100
- )
101
- tables = pd.read_excel(
102
- file_path,
103
- engine="odf",
104
- sheet_name=None,
105
- dtype="unicode",
106
- )
107
- sizes = {sheet_name: table.size for sheet_name, table in tables.items()}
108
- sheet_name = max(sizes, key=sizes.get)
109
- if verbose:
110
- display_logs_depending_process_time(
111
- f'Going forwards with sheet "{sheet_name}"',
112
- time() - start,
113
- )
114
- table = tables[sheet_name]
115
- else:
116
- if verbose:
117
- display_logs_depending_process_time(
118
- f'Detected {engine_to_file[engine]} file, reading sheet "{sheet_name}"',
119
- time() - start,
120
- )
121
- table = pd.read_excel(
122
- file_path,
123
- engine="odf",
124
- sheet_name=sheet_name,
125
- dtype="unicode",
126
- )
127
- table, header_row_idx = remove_empty_first_rows(table)
128
- total_lines = len(table)
129
- nb_duplicates = len(table.loc[table.duplicated()])
130
- if num_rows > 0:
131
- num_rows = min(num_rows - 1, total_lines)
132
- table = table.sample(num_rows, random_state=random_state)
133
- if verbose:
134
- display_logs_depending_process_time(
135
- f'Table parsed successfully in {round(time() - start, 3)}s',
136
- time() - start,
137
- )
138
- return table, total_lines, nb_duplicates, sheet_name, engine, header_row_idx
139
-
140
- # so here we end up with (old and new) excel files only
141
- if verbose:
142
- if no_sheet_specified:
143
- display_logs_depending_process_time(
144
- f'Going forwards with sheet "{sheet_name}"',
145
- time() - start,
146
- )
147
- else:
148
- display_logs_depending_process_time(
149
- f'Detected {engine_to_file[engine]} file, reading sheet "{sheet_name}"',
150
- time() - start,
151
- )
152
- table = pd.read_excel(
153
- file_path,
154
- engine=engine,
155
- sheet_name=sheet_name,
156
- dtype="unicode",
157
- )
158
- table, header_row_idx = remove_empty_first_rows(table)
159
- total_lines = len(table)
160
- nb_duplicates = len(table.loc[table.duplicated()])
161
- if num_rows > 0:
162
- num_rows = min(num_rows - 1, total_lines)
163
- table = table.sample(num_rows, random_state=random_state)
164
- if verbose:
165
- display_logs_depending_process_time(
166
- f'Table parsed successfully in {round(time() - start, 3)}s',
167
- time() - start,
168
- )
169
- return table, total_lines, nb_duplicates, sheet_name, engine, header_row_idx
@@ -1,97 +0,0 @@
1
- from io import BytesIO, StringIO
2
- from typing import Optional, Union
3
-
4
- import pandas as pd
5
- import requests
6
-
7
- from csv_detective.detection.columns import detect_heading_columns, detect_trailing_columns
8
- from csv_detective.detection.encoding import detect_encoding
9
- from csv_detective.detection.engine import (
10
- COMPRESSION_ENGINES,
11
- EXCEL_ENGINES,
12
- detect_engine,
13
- )
14
- from csv_detective.detection.headers import detect_headers
15
- from csv_detective.detection.separator import detect_separator
16
- from csv_detective.utils import is_url
17
- from .compression import unzip
18
- from .csv import parse_csv
19
- from .excel import (
20
- XLS_LIKE_EXT,
21
- parse_excel,
22
- )
23
-
24
-
25
- def load_file(
26
- file_path: str,
27
- num_rows: int = 500,
28
- encoding: Optional[str] = None,
29
- sep: Optional[str] = None,
30
- verbose: bool = False,
31
- sheet_name: Optional[Union[str, int]] = None,
32
- ) -> tuple[pd.DataFrame, dict]:
33
- file_name = file_path.split('/')[-1]
34
- engine = None
35
- if '.' not in file_name or not file_name.endswith("csv"):
36
- # file has no extension, we'll investigate how to read it
37
- engine = detect_engine(file_path, verbose=verbose)
38
-
39
- if engine in EXCEL_ENGINES or any([file_path.endswith(k) for k in XLS_LIKE_EXT]):
40
- table, total_lines, nb_duplicates, sheet_name, engine, header_row_idx = parse_excel(
41
- file_path=file_path,
42
- num_rows=num_rows,
43
- engine=engine,
44
- sheet_name=sheet_name,
45
- verbose=verbose,
46
- )
47
- header = table.columns.to_list()
48
- analysis = {
49
- "engine": engine,
50
- "sheet_name": sheet_name,
51
- }
52
- else:
53
- # fetching or reading file as binary
54
- if is_url(file_path):
55
- r = requests.get(file_path, allow_redirects=True)
56
- r.raise_for_status()
57
- binary_file = BytesIO(r.content)
58
- else:
59
- binary_file = open(file_path, "rb")
60
- # handling compression
61
- if engine in COMPRESSION_ENGINES:
62
- binary_file: BytesIO = unzip(binary_file=binary_file, engine=engine)
63
- # detecting encoding if not specified
64
- if encoding is None:
65
- encoding: str = detect_encoding(binary_file, verbose=verbose)
66
- binary_file.seek(0)
67
- # decoding and reading file
68
- if is_url(file_path) or engine in COMPRESSION_ENGINES:
69
- str_file = StringIO(binary_file.read().decode(encoding=encoding))
70
- else:
71
- str_file = open(file_path, "r", encoding=encoding)
72
- if sep is None:
73
- sep = detect_separator(str_file, verbose=verbose)
74
- header_row_idx, header = detect_headers(str_file, sep, verbose=verbose)
75
- if header is None:
76
- return {"error": True}
77
- elif isinstance(header, list):
78
- if any([x is None for x in header]):
79
- return {"error": True}
80
- heading_columns = detect_heading_columns(str_file, sep, verbose=verbose)
81
- trailing_columns = detect_trailing_columns(str_file, sep, heading_columns, verbose=verbose)
82
- table, total_lines, nb_duplicates = parse_csv(
83
- str_file, encoding, sep, num_rows, header_row_idx, verbose=verbose
84
- )
85
- analysis = {
86
- "encoding": encoding,
87
- "separator": sep,
88
- "heading_columns": heading_columns,
89
- "trailing_columns": trailing_columns,
90
- }
91
- analysis.update({
92
- "header_row_idx": header_row_idx,
93
- "header": header,
94
- "total_lines": total_lines,
95
- "nb_duplicates": nb_duplicates,
96
- })
97
- return table, analysis
@@ -1,61 +0,0 @@
1
- from re import finditer
2
-
3
-
4
- def camel_case_split(identifier: str):
5
- matches = finditer(
6
- ".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)", identifier
7
- )
8
- return " ".join([m.group(0) for m in matches])
9
-
10
-
11
- translate_dict = {
12
- " ": ["-", "_", "'", ",", " "],
13
- "a": ["à", "â"],
14
- "c": ["ç"],
15
- "e": ["é", "è", "ê", "é"],
16
- "i": ["î", "ï"],
17
- "o": ["ô", "ö"],
18
- "u": ["ù", "û", "ü"],
19
- }
20
-
21
-
22
- # Process text
23
- def _process_text(val: str):
24
- """Traitement des chaînes de caractères pour les standardiser.
25
- Plusieurs alternatives ont été testées : .translate, unidecode.unidecode,
26
- des méthodes hybrides, mais aucune ne s'est avérée plus performante."""
27
- val = camel_case_split(val)
28
- val = val.lower()
29
- for target in translate_dict:
30
- for source in translate_dict[target]:
31
- val = val.replace(source, target)
32
- val = val.strip()
33
- return val
34
-
35
-
36
- def is_word_in_string(word: str, string: str):
37
- # if the substring is too short, the test can become irrelevant
38
- return len(word) > 2 and word in string
39
-
40
-
41
- def header_score(header: str, words_combinations_list: list[str]) -> float:
42
- """Returns:
43
- - 1 if the header is exactly in the specified list
44
- - 0.5 if any of the words is within the header
45
- - 0 otherwise"""
46
- processed_header = _process_text(header)
47
-
48
- header_matches_words_combination = float(
49
- any(
50
- words_combination == processed_header for words_combination in words_combinations_list
51
- )
52
- )
53
- words_combination_in_header = 0.5 * (
54
- any(
55
- is_word_in_string(
56
- words_combination, processed_header
57
- ) for words_combination in words_combinations_list
58
- )
59
- )
60
-
61
- return max(header_matches_words_combination, words_combination_in_header)