codec-bridge 0.1.0__tar.gz

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.
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.1
2
+ Name: codec_bridge
3
+ Version: 0.1.0
4
+ Summary: Detect encoding from CSV files and return the accepted case format for analytical tools (currently supports DuckDB)
5
+ Home-page: https://github.com/jpferraz-git/codec_bridge
6
+ Author: João Pedro Ferraz Bezerra
7
+ Author-email: João Pedro Ferraz Bezerra <jpferraz554@gmail.com>
8
+ License: MIT License
9
+
10
+ Copyright (c) 2025 João Pedro Ferraz Bezerra
11
+
12
+ Permission is hereby granted, free of charge, to any person obtaining a copy
13
+ of this software and associated documentation files (the "Software"), to deal
14
+ in the Software without restriction, including without limitation the rights
15
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
+ copies of the Software, and to permit persons to whom the Software is
17
+ furnished to do so, subject to the following conditions:
18
+
19
+ The above copyright notice and this permission notice shall be included in all
20
+ copies or substantial portions of the Software.
21
+
22
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
+ SOFTWARE.
29
+
30
+ Classifier: Programming Language :: Python :: 3.12
31
+ Classifier: Operating System :: OS Independent
32
+ Classifier: Operating System :: Microsoft :: Windows
33
+ Classifier: Operating System :: POSIX :: Linux
34
+ Requires-Python: >=3.12
35
+ Description-Content-Type: text/markdown
36
+ License-File: license.txt
37
+
38
+ # codec_bridge
39
+
40
+ A Python utility library that bridges encoding mismatches between Python and DuckDB when reading raw CSV files.
41
+
42
+ ## 🔍 Motivation
43
+
44
+ DuckDB recently introduced the `encodings` extension, supporting over a thousand character encodings. However, Python often detects encodings using a format or casing that DuckDB does not accept directly.
45
+
46
+ For example:
47
+ - Python detects: `ISO-8859-1`
48
+ - DuckDB expects: `latin`
49
+
50
+ This mismatch can break ingestion pipelines, especially when dealing with large volumes of raw CSV files from diverse sources. The goal of this library is to act as a **bridge**, translating Python-standard encoding names into DuckDB-compatible formats.
51
+
52
+ ## ⚙️ Features
53
+
54
+ - ✅ `get_duckdb_encoding`: Main method that maps Python encoding names to DuckDB-compatible formats.
55
+ - 🔍 `detect_encoding`: Detects the encoding of a file using `charset-normalizer`.
56
+ - 📌 `detect_delimiter`: Identifies the most likely delimiter used in a CSV file.
57
+ - ✍️ `write_utf8_csv`: Rewrites a file to UTF-8 encoding when necessary.
58
+ - 📦 `process_files`: Scans a directory of CSV files and returns metadata for each file.
59
+
60
+ ## 📦 Installation
61
+
62
+ ```bash
63
+ pip install codec_bridge
64
+ ```
65
+
66
+ ## 🔧 Requirements
67
+
68
+ This library depends on:
69
+
70
+ - `duckdb` (>=1.3.2)
71
+ - `charset-normalizer` (>=3.4.2)
72
+
73
+ These will be installed automatically when using `pip install codec_bridge`.
@@ -0,0 +1,36 @@
1
+ # codec_bridge
2
+
3
+ A Python utility library that bridges encoding mismatches between Python and DuckDB when reading raw CSV files.
4
+
5
+ ## 🔍 Motivation
6
+
7
+ DuckDB recently introduced the `encodings` extension, supporting over a thousand character encodings. However, Python often detects encodings using a format or casing that DuckDB does not accept directly.
8
+
9
+ For example:
10
+ - Python detects: `ISO-8859-1`
11
+ - DuckDB expects: `latin`
12
+
13
+ This mismatch can break ingestion pipelines, especially when dealing with large volumes of raw CSV files from diverse sources. The goal of this library is to act as a **bridge**, translating Python-standard encoding names into DuckDB-compatible formats.
14
+
15
+ ## ⚙️ Features
16
+
17
+ - ✅ `get_duckdb_encoding`: Main method that maps Python encoding names to DuckDB-compatible formats.
18
+ - 🔍 `detect_encoding`: Detects the encoding of a file using `charset-normalizer`.
19
+ - 📌 `detect_delimiter`: Identifies the most likely delimiter used in a CSV file.
20
+ - ✍️ `write_utf8_csv`: Rewrites a file to UTF-8 encoding when necessary.
21
+ - 📦 `process_files`: Scans a directory of CSV files and returns metadata for each file.
22
+
23
+ ## 📦 Installation
24
+
25
+ ```bash
26
+ pip install codec_bridge
27
+ ```
28
+
29
+ ## 🔧 Requirements
30
+
31
+ This library depends on:
32
+
33
+ - `duckdb` (>=1.3.2)
34
+ - `charset-normalizer` (>=3.4.2)
35
+
36
+ These will be installed automatically when using `pip install codec_bridge`.
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.1
2
+ Name: codec-bridge
3
+ Version: 0.1.0
4
+ Summary: Detect encoding from CSV files and return the accepted case format for analytical tools (currently supports DuckDB)
5
+ Home-page: https://github.com/jpferraz-git/codec_bridge
6
+ Author: João Pedro Ferraz Bezerra
7
+ Author-email: João Pedro Ferraz Bezerra <jpferraz554@gmail.com>
8
+ License: MIT License
9
+
10
+ Copyright (c) 2025 João Pedro Ferraz Bezerra
11
+
12
+ Permission is hereby granted, free of charge, to any person obtaining a copy
13
+ of this software and associated documentation files (the "Software"), to deal
14
+ in the Software without restriction, including without limitation the rights
15
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
+ copies of the Software, and to permit persons to whom the Software is
17
+ furnished to do so, subject to the following conditions:
18
+
19
+ The above copyright notice and this permission notice shall be included in all
20
+ copies or substantial portions of the Software.
21
+
22
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
+ SOFTWARE.
29
+
30
+ Classifier: Programming Language :: Python :: 3.12
31
+ Classifier: Operating System :: OS Independent
32
+ Classifier: Operating System :: Microsoft :: Windows
33
+ Classifier: Operating System :: POSIX :: Linux
34
+ Requires-Python: >=3.12
35
+ Description-Content-Type: text/markdown
36
+ License-File: license.txt
37
+
38
+ # codec_bridge
39
+
40
+ A Python utility library that bridges encoding mismatches between Python and DuckDB when reading raw CSV files.
41
+
42
+ ## 🔍 Motivation
43
+
44
+ DuckDB recently introduced the `encodings` extension, supporting over a thousand character encodings. However, Python often detects encodings using a format or casing that DuckDB does not accept directly.
45
+
46
+ For example:
47
+ - Python detects: `ISO-8859-1`
48
+ - DuckDB expects: `latin`
49
+
50
+ This mismatch can break ingestion pipelines, especially when dealing with large volumes of raw CSV files from diverse sources. The goal of this library is to act as a **bridge**, translating Python-standard encoding names into DuckDB-compatible formats.
51
+
52
+ ## ⚙️ Features
53
+
54
+ - ✅ `get_duckdb_encoding`: Main method that maps Python encoding names to DuckDB-compatible formats.
55
+ - 🔍 `detect_encoding`: Detects the encoding of a file using `charset-normalizer`.
56
+ - 📌 `detect_delimiter`: Identifies the most likely delimiter used in a CSV file.
57
+ - ✍️ `write_utf8_csv`: Rewrites a file to UTF-8 encoding when necessary.
58
+ - 📦 `process_files`: Scans a directory of CSV files and returns metadata for each file.
59
+
60
+ ## 📦 Installation
61
+
62
+ ```bash
63
+ pip install codec_bridge
64
+ ```
65
+
66
+ ## 🔧 Requirements
67
+
68
+ This library depends on:
69
+
70
+ - `duckdb` (>=1.3.2)
71
+ - `charset-normalizer` (>=3.4.2)
72
+
73
+ These will be installed automatically when using `pip install codec_bridge`.
@@ -0,0 +1,16 @@
1
+ README.md
2
+ license.txt
3
+ pyproject.toml
4
+ setup.py
5
+ codec_bridge.egg-info/PKG-INFO
6
+ codec_bridge.egg-info/SOURCES.txt
7
+ codec_bridge.egg-info/dependency_links.txt
8
+ codec_bridge.egg-info/requires.txt
9
+ codec_bridge.egg-info/top_level.txt
10
+ repository/__init__.py
11
+ repository/python_to_duckdb.py
12
+ src/__init__.py
13
+ src/encoding_translator.py
14
+ tests/__init__.py
15
+ tests/duckdb_utils.py
16
+ tests/generate_test_data.py
@@ -0,0 +1,2 @@
1
+ charset-normalizer>=3.4.2
2
+ duckdb>=1.3.2
@@ -0,0 +1,3 @@
1
+ repository
2
+ src
3
+ tests
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 João Pedro Ferraz Bezerra
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,26 @@
1
+ [project]
2
+ name = "codec_bridge"
3
+ version = "0.1.0"
4
+ description = "Detect encoding from CSV files and return the accepted case format for analytical tools (currently supports DuckDB)"
5
+ authors = [
6
+ { name = "João Pedro Ferraz Bezerra", email = "jpferraz554@gmail.com" }
7
+ ]
8
+ license = { file = "license.txt"}
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+
12
+ dependencies = [
13
+ "charset-normalizer>=3.4.2",
14
+ "duckdb>=1.3.2"
15
+ ]
16
+
17
+ classifiers = [
18
+ "Programming Language :: Python :: 3.12",
19
+ "Operating System :: OS Independent",
20
+ "Operating System :: Microsoft :: Windows",
21
+ "Operating System :: POSIX :: Linux"
22
+ ]
23
+
24
+ [build-system]
25
+ requires = ["setuptools>=61.0", "wheel"]
26
+ build-backend = "setuptools.build_meta"
File without changes
@@ -0,0 +1,80 @@
1
+ PYTHON_TO_DUCKDB_ENCODING = {
2
+ # --- UTF-8 ---
3
+ 'utf_8': 'utf-8',
4
+ 'utf8': 'utf_8',
5
+ 'utf_16': 'utf-16',
6
+ 'utf-16': 'utf-16',
7
+ 'utf_16be': 'utf-16-be',
8
+ 'utf_16le': 'utf-16-le',
9
+
10
+ # --- ASCII ---
11
+ 'ascii': 'ascii',
12
+ 'us-ascii': 'ascii',
13
+ 'ibm-367_p100-1995': 'ascii',
14
+ 'iso-ir-6': 'ascii',
15
+
16
+ # --- Latin-1 (Ocidental Europe) ---
17
+ 'latin-1': 'latin_1',
18
+ 'latin1': 'latin_1',
19
+ 'iso-8859-1': 'latin_1',
20
+ 'iso_8859_1': 'latin_1',
21
+ 'ibm-819': 'latin_1',
22
+ 'cp819': 'latin_1',
23
+ 'iso8859_1': 'latin_1',
24
+ 'iso8859_14': 'ISO_8859_14',
25
+ 'iso8859_10': 'ISO_8859_10',
26
+
27
+ # --- Windows-1252 ---
28
+ 'windows-1252': 'ISO8859_1',
29
+ 'cp1252': 'windows_1252',
30
+
31
+ # --- Latin-2 (Central Europe / Oriental Europe) ---
32
+ 'iso-8859-2': 'latin_2',
33
+ 'iso_8859_2': 'latin_2',
34
+ 'latin-2': 'latin_2',
35
+ 'latin2': 'latin_2',
36
+ 'windows-1250': 'CP1250',
37
+ 'cp1250': 'windows_1250',
38
+ 'cp852': 'cp852',
39
+ "mac_iceland": "MAC_IS",
40
+
41
+ # --- Cyrillic ---
42
+ 'iso-8859-5': 'iso_8859_5',
43
+ 'iso_8859_5': 'iso_8859_5',
44
+ 'cyrillic': 'iso_8859_5',
45
+ 'windows-1251': 'windows_1251',
46
+ 'cp1251': 'windows_1251',
47
+ 'koi8-r': 'koi8_r',
48
+ 'koi8_r': 'koi8_r',
49
+
50
+ # --- Greek ---
51
+ 'iso-8859-7': 'iso_8859_7',
52
+ 'iso_8859_7': 'iso_8859_7',
53
+ 'windows-1253': 'windows_1253',
54
+ 'cp1253': 'windows_1253',
55
+
56
+ # --- Japenese ---
57
+ 'shift_jis': 'shift_jis',
58
+ 'sjis': 'shift_jis',
59
+ 'ibm-943': 'shift_jis',
60
+ 'windows-932': 'shift_jis',
61
+ 'euc-jp': 'euc_jp',
62
+
63
+ # --- Chinese ---
64
+ 'gbk': 'gbk',
65
+ 'gb2312': 'gb2312',
66
+ 'big5': 'big5',
67
+
68
+ # --- Korean ---
69
+ 'euc-kr': 'euc_kr',
70
+ 'cp949': 'cp949',
71
+ 'johab': 'johab',
72
+ }
73
+
74
+ ENCODINGS_UNDERSCORE_CONFLICT = {
75
+ 'shift_jis',
76
+ 'cp932',
77
+ 'big5',
78
+ 'gbk',
79
+ 'gb2312',
80
+ }
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,20 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ name='codec_bridge',
5
+ version='0.1.0',
6
+ description='Encoding and case normalization bridge for DuckDB and other engines',
7
+ long_description=open('README.md', encoding='utf-8').read(),
8
+ long_description_content_type='text/markdown',
9
+ author='João Pedro Ferraz Bezerra',
10
+ author_email='jpferraz554@gmail.com',
11
+ url='https://github.com/jpferraz-git/codec_bridge',
12
+ packages=find_packages(),
13
+ classifiers=[
14
+ 'Programming Language :: Python :: 3.12',
15
+ 'Operating System :: OS Independent',
16
+ 'Operating System :: Microsoft :: Windows',
17
+ 'Operating System :: POSIX :: Linux',
18
+ ],
19
+ python_requires='>=3.12',
20
+ )
File without changes
@@ -0,0 +1,141 @@
1
+ import charset_normalizer
2
+ import os
3
+ import re
4
+
5
+ from repository.python_to_duckdb import PYTHON_TO_DUCKDB_ENCODING, ENCODINGS_UNDERSCORE_CONFLICT
6
+
7
+
8
+ def get_duckdb_encoding(python_encoding_name: str) -> str:
9
+ """
10
+ Translates a Python-standard encoding name to the name expected by DuckDB.
11
+ If no specific mapping is found, it returns the original name as a fallback.
12
+
13
+ :param python_encoding_name: The encoding name detected (e.g., 'iso-8859-1').
14
+ :return: The translated encoding name for DuckDB (e.g., 'ibm-819').
15
+ """
16
+ if not python_encoding_name:
17
+ return 'utf-8'
18
+
19
+ normalized_name = python_encoding_name.lower()
20
+ return PYTHON_TO_DUCKDB_ENCODING.get(normalized_name, python_encoding_name)
21
+
22
+
23
+ def detect_encoding(file_path: str, chunk: int = 1000000) -> str:
24
+ """
25
+ Detects the character encoding of a file using charset_normalizer.
26
+
27
+ :param file_path: The full path to the file.
28
+ :return: The detected encoding name as a string.
29
+ """
30
+ with open(file_path, "rb") as file:
31
+ data_sample = file.read(chunk)
32
+ result = charset_normalizer.detect(data_sample)
33
+ return result.get("encoding") if result else "utf-8"
34
+
35
+ def detect_delimiter(file_path: str, encoding: str = "utf-8") -> str:
36
+ """
37
+ Detects the most likely delimiter based on the first line of the file.
38
+
39
+ :param file_path: The full path to the file.
40
+ :param encoding: The encoding to use when reading the file.
41
+ :return: The detected delimiter character.
42
+ """
43
+ possible_delimiters = [',', ';', '\t', '|']
44
+ detected_delimiter = ',' # Default to comma
45
+ if encoding.lower() in ENCODINGS_UNDERSCORE_CONFLICT:
46
+ return '|'
47
+ try:
48
+ with open(file_path, 'r', encoding=encoding, errors='replace') as f:
49
+ first_line = f.readline()
50
+ # Find the delimiter with the highest count in the header line
51
+ counts = {d: first_line.count(d) for d in possible_delimiters}
52
+ if any(c > 0 for c in counts.values()):
53
+ detected_delimiter = max(counts, key=counts.get)
54
+ except Exception as e:
55
+ print(f"[WARN] Could not detect delimiter for {os.path.basename(file_path)}: {e}")
56
+
57
+ return detected_delimiter
58
+
59
+ def process_files(directory_path: str) -> list[dict]:
60
+ """
61
+ Iterates through all CSV files in the instance's directory, detects their
62
+ properties (encoding, delimiter), and stores them as metadata.
63
+
64
+ This method acts as a utility to scan and prepare a batch of files.
65
+
66
+ :return: A list of dictionaries, each containing metadata for a file.
67
+ """
68
+ if not os.path.isdir(directory_path):
69
+ print(f"Error: The directory '{directory_path}' does not exist.")
70
+ return []
71
+
72
+ results = []
73
+ for filename in os.listdir(directory_path):
74
+ if not filename.lower().endswith('.csv'):
75
+ continue
76
+
77
+ file_path = os.path.join(directory_path, filename)
78
+
79
+ # Detect properties
80
+ python_encoding = detect_encoding(file_path)
81
+ delimiter = detect_delimiter(file_path, encoding=python_encoding)
82
+
83
+ # Translate encoding for the target enconding case
84
+ duckdb_encoding = get_duckdb_encoding(python_encoding)
85
+
86
+ # Sanitize filename to create a valid table name
87
+ table_name = re.sub(r'[^a-zA-Z0-9_]', '_', os.path.splitext(filename)[0])
88
+
89
+ results.append({
90
+ "filename": filename,
91
+ "path": file_path,
92
+ "python_encoding": python_encoding,
93
+ "duckdb_encoding": duckdb_encoding,
94
+ "delimiter": delimiter,
95
+ "table_name": table_name
96
+ })
97
+
98
+ return results
99
+
100
+ def write_utf8_csv(file_path: str, new_csv_file_path: str):
101
+
102
+ """
103
+ Rewrites a CSV file using UTF-8 encoding.
104
+
105
+ This method is intended for cases where, even after DuckDB's encoding detection,
106
+ the file is still incorrectly interpreted when inserted into the database.
107
+
108
+ :param file_path: Path to the original CSV file.
109
+ :param new_csv_file_path: Path where the UTF-8 encoded CSV will be saved.
110
+ :return: None. The UTF-8 encoded file is written to disk.
111
+ """
112
+ with open(file_path, 'r') as file:
113
+ with open(new_csv_file_path, 'w', encoding='utf-8') as new_file:
114
+ for line in file:
115
+ new_file.write(line)
116
+
117
+ if __name__ == "__main__":
118
+ import duckdb
119
+ from tests.duckdb_utils import create_table_from_csv
120
+
121
+ csv_directory_path = "//tests/assets/"
122
+
123
+ connection = duckdb.connect(database=":memory:")
124
+
125
+ connection.execute("INSTALL encodings")
126
+ connection.execute("LOAD encodings")
127
+
128
+ detector = get_duckdb_encoding(csv_directory_path)
129
+
130
+ file_results = process_files(csv_directory_path)
131
+
132
+ for result in file_results:
133
+ create_table_from_csv(
134
+ conn=connection,
135
+ file_path=result["path"],
136
+ table_name=result["table_name"],
137
+ delimiter=result["delimiter"],
138
+ encoding=result["duckdb_encoding"]
139
+ )
140
+
141
+ connection.close()
File without changes
@@ -0,0 +1,21 @@
1
+ import os
2
+ def create_table_from_csv(conn, file_path: str, table_name: str, delimiter: str = '|', encoding: str = "utf-8"):
3
+ """
4
+ Create a table on DuckDB
5
+ """
6
+ print(f"Processando '{os.path.basename(file_path)}': Tabela='{table_name}', Encoding='{encoding}', Delim='{delimiter}'")
7
+ try:
8
+ conn.sql(f"""
9
+ CREATE OR REPLACE TEMP TABLE "{table_name}" AS
10
+ (SELECT * FROM
11
+ read_csv('{file_path}',
12
+ delim='{delimiter}',
13
+ encoding='{encoding}',
14
+ header=true,
15
+ auto_detect=true
16
+ ) LIMIT 1000)
17
+ """)
18
+ print(f"✅ Tabela '{table_name}' criada com sucesso.")
19
+ print(conn.sql(f'SELECT * FROM "{table_name}" LIMIT 3'))
20
+ except Exception as e:
21
+ print(f"❌ ERRO ao criar a tabela '{table_name}': {e}")
@@ -0,0 +1,61 @@
1
+ import csv
2
+ import os
3
+
4
+
5
+ DEFAULT_OUTPUT_DIR = os.path.join(os.path.dirname(__file__), "assets")
6
+
7
+ def generate_csv_test_files(output_dir: str = DEFAULT_OUTPUT_DIR, num_rows: int = 1000):
8
+ """
9
+ Generates a suite of CSV files with different encodings and characters
10
+ to be used as assets for running tests.
11
+ """
12
+ os.makedirs(output_dir, exist_ok=True)
13
+ print(f"Generating test files in: {output_dir}")
14
+
15
+ encodings_to_test = [
16
+ "utf-8", "utf-16", "iso-8859-1", "windows-1252",
17
+ "ascii", "iso-8859-2", "iso-8859-5", "koi8-r",
18
+ "shift_jis", "gbk", "big5", "windows-1253", "iso-8859-15"
19
+ ]
20
+
21
+ # Dictionary of "killer characters" to make each encoding unique
22
+ special_chars = {
23
+ "iso-8859-1": "ç",
24
+ "windows-1252": "€",
25
+ "iso-8859-2": "ść",
26
+ "iso-8859-5": "ДЖ",
27
+ "koi8-r": "ДЖ",
28
+ "shift_jis": "ア",
29
+ "gbk": "你好",
30
+ "big5": "你好",
31
+ "windows-1253": "αβ",
32
+ "iso-8859-15": "€",
33
+ "utf-8": "🚀",
34
+ "utf-16": "🚀",
35
+ }
36
+
37
+ def generate_rows(example_char=""):
38
+ # Add the special character to the first cell of each row
39
+ return [[f"Data_{i}_{j}{example_char if j == 0 else ''}" for j in range(10)] for i in range(num_rows)]
40
+
41
+ # Loop through encodings and generate files
42
+ for enc in encodings_to_test:
43
+ filename = os.path.join(output_dir, f"test_{enc}.csv")
44
+ special_char = special_chars.get(enc, "")
45
+ rows = generate_rows(special_char)
46
+
47
+ try:
48
+ with open(filename, mode="w", encoding=enc, newline="") as file:
49
+ writer = csv.writer(file)
50
+ writer.writerow(["Header_1", "Header_2", "Header_3", "Header_4", "Header_5"])
51
+ writer.writerows(rows)
52
+ print(f"✅ Generated: {os.path.basename(filename)} (with char: '{special_char}')")
53
+ except UnicodeEncodeError:
54
+ print(f"❌ Encoding Error with {enc}: The character '{special_char}' is not supported.")
55
+ except Exception as e:
56
+ print(f"⚠️ Unexpected Error with {enc}: {e}")
57
+
58
+ if __name__ == "__main__":
59
+ # This allows you to run the script directly to generate the files
60
+ # python tests/generate_test_data.py
61
+ generate_csv_test_files()