csv-sanitizer-schema-validator 0.1.0__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.
File without changes
CSV_Sanitizer/cli.py ADDED
@@ -0,0 +1,80 @@
1
+ """Command-line entry point for csv-sanitizer."""
2
+
3
+ import argparse
4
+ import os
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ from dotenv import load_dotenv
9
+
10
+ from .core import sanitize_csv
11
+
12
+
13
+ def get_enterprise_paths():
14
+ """Legacy .env fallback: TARGET_INPUT_DIR / CLEAN_OUTPUT_DIR / ERROR_LOG_PATH."""
15
+ BASE_DIR = Path(__file__).resolve().parent.parent.parent
16
+ load_dotenv(dotenv_path=BASE_DIR / ".env", override=True)
17
+
18
+ input_dir = os.getenv("TARGET_INPUT_DIR")
19
+ output_dir = os.getenv("CLEAN_OUTPUT_DIR")
20
+ log_path = os.getenv("ERROR_LOG_PATH")
21
+
22
+ if not input_dir or not output_dir:
23
+ raise EnvironmentError(
24
+ "TARGET_INPUT_DIR and CLEAN_OUTPUT_DIR must be set in .env"
25
+ )
26
+
27
+ input_csv = Path(input_dir) / "dirty_data.csv"
28
+ output_csv = Path(output_dir) / "clean_data.csv"
29
+ return str(input_csv), str(output_csv), log_path
30
+
31
+
32
+ def build_parser():
33
+ parser = argparse.ArgumentParser(
34
+ prog="csv-sanitizer",
35
+ description="Stream, sanitize, and schema-validate a messy CSV file.",
36
+ )
37
+ parser.add_argument(
38
+ "input", nargs="?", default=None, help="Path to the dirty input CSV file"
39
+ )
40
+ parser.add_argument(
41
+ "output", nargs="?", default=None, help="Path to write the cleaned CSV file"
42
+ )
43
+ parser.add_argument(
44
+ "--log",
45
+ dest="log_path",
46
+ default=None,
47
+ help="Optional path for a log of skipped rows",
48
+ )
49
+ return parser
50
+
51
+
52
+ def main(argv=None) -> int:
53
+ args = build_parser().parse_args(argv)
54
+ input_path, output_path, log_path = args.input, args.output, args.log_path
55
+
56
+ if not input_path or not output_path:
57
+ try:
58
+ input_path, output_path, env_log_path = get_enterprise_paths()
59
+ log_path = log_path or env_log_path
60
+ except EnvironmentError as e:
61
+ print(
62
+ f"Error: no input/output given, and no .env fallback found.\n {e}",
63
+ file=sys.stderr,
64
+ )
65
+ return 1
66
+
67
+ try:
68
+ stats = sanitize_csv(input_path, output_path, log_path)
69
+ except FileNotFoundError:
70
+ print(f"Error: input file not found: {input_path}", file=sys.stderr)
71
+ return 1
72
+
73
+ print(
74
+ f"Done. {stats['rows_written']} rows written, {stats['rows_skipped']} rows skipped."
75
+ )
76
+ return 0
77
+
78
+
79
+ if __name__ == "__main__":
80
+ sys.exit(main())
CSV_Sanitizer/core.py ADDED
@@ -0,0 +1,94 @@
1
+ """Core CSV sanitization and schema-validation logic.
2
+
3
+ Nothing in this file runs on import — everything happens inside sanitize_csv().
4
+ """
5
+
6
+ import logging
7
+ from pathlib import Path
8
+
9
+ from dateutil import parser
10
+
11
+
12
+ def clean_whitespace(dirty_input: str) -> str:
13
+ if not isinstance(dirty_input, str):
14
+ return ""
15
+ cleaned_string = dirty_input.replace("\ufeff", "")
16
+ return cleaned_string.strip()
17
+
18
+
19
+ def parse_to_iso_8601(date_str: str) -> str:
20
+ parsed_date = parser.parse(date_str)
21
+ clean_date = parsed_date.date().isoformat()
22
+ return clean_date
23
+
24
+
25
+ def validate_row_schema(row: list, expected_length: int) -> bool:
26
+ return len(row) == expected_length
27
+
28
+
29
+ def sanitize_csv(input_path, output_path, log_path=None) -> dict:
30
+ """Reads input_path, writes a cleaned CSV to output_path.
31
+
32
+ Returns {"rows_written": int, "rows_skipped": int}.
33
+ """
34
+ input_path = Path(input_path)
35
+ output_path = Path(output_path)
36
+ output_path.parent.mkdir(parents=True, exist_ok=True)
37
+
38
+ if log_path:
39
+ log_path = Path(log_path)
40
+ log_path.parent.mkdir(parents=True, exist_ok=True)
41
+ logging.basicConfig(
42
+ filename=str(log_path),
43
+ filemode="a",
44
+ level=logging.INFO,
45
+ format="%(asctime)s - %(levelname)s - %(message)s",
46
+ force=True,
47
+ )
48
+
49
+ rows_written = 0
50
+ rows_skipped = 0
51
+
52
+ with (
53
+ open(input_path, "r", encoding="utf-8") as file,
54
+ open(output_path, "w", encoding="utf-8") as cleaned_file,
55
+ ):
56
+ row_headings = file.readline()
57
+ header_list = [clean_whitespace(h) for h in row_headings.split(",")]
58
+ expected_length = len(header_list)
59
+
60
+ clean_headings = ",".join(header_list) + "\n"
61
+ cleaned_file.write(clean_headings)
62
+
63
+ for line in file:
64
+ cleaned_line = line.strip()
65
+ if not cleaned_line:
66
+ continue
67
+
68
+ raw_row = cleaned_line.split(",")
69
+
70
+ if not validate_row_schema(raw_row, expected_length):
71
+ logging.warning(f"MALFORMED ROW ISOLATED (COLUMN MISMATCH): {raw_row}")
72
+ rows_skipped += 1
73
+ continue
74
+
75
+ try:
76
+ cleaned_id = clean_whitespace(raw_row[0])
77
+ cleaned_name = clean_whitespace(raw_row[1])
78
+ cleaned_date = parse_to_iso_8601(raw_row[2])
79
+ cleaned_role = clean_whitespace(raw_row[3])
80
+
81
+ clean_line = (
82
+ f"{cleaned_id},{cleaned_name},{cleaned_date},{cleaned_role}\n"
83
+ )
84
+ cleaned_file.write(clean_line)
85
+ rows_written += 1
86
+
87
+ except Exception as parsing_err:
88
+ logging.warning(
89
+ f"MALFORMED ROW ISOLATED (PARSING ERROR): {raw_row} | Reason: {parsing_err}"
90
+ )
91
+ rows_skipped += 1
92
+ continue
93
+
94
+ return {"rows_written": rows_written, "rows_skipped": rows_skipped}
@@ -0,0 +1,97 @@
1
+ Metadata-Version: 2.4
2
+ Name: csv-sanitizer-schema-validator
3
+ Version: 0.1.0
4
+ Summary: Stream, sanitize, and schema-validate messy CSV files
5
+ Project-URL: Homepage, https://github.com/hgandhi2010/CSV_Sanitizer_Schema_Validator
6
+ Author: Hemin Gandhi
7
+ License: MIT
8
+ License-File: LICENSE
9
+ Requires-Python: >=3.9
10
+ Requires-Dist: python-dateutil==2.9.0.post0
11
+ Requires-Dist: python-dotenv==1.0.1
12
+ Provides-Extra: dev
13
+ Requires-Dist: pytest==8.2.2; extra == 'dev'
14
+ Description-Content-Type: text/markdown
15
+
16
+ # Enterprise CSV Sanitizer & Schema Validator
17
+
18
+ A production-grade command-line interface (CLI) data engineering utility built to stream, scrub, and validate high-volume unstructured enterprise sheets and application logs cleanly without memory leaks or unhandled script execution crashes.
19
+
20
+ ---
21
+
22
+ ## 🎯 Core Project Overview (STAR Metrics)
23
+
24
+ * **Situation:** Helpdesk systems and standard application roles regularly deal with corrupted data pipelines, downstream import rejections, and crashing analytics engines due to malformed, unescaped, and corrupt manual CSV exports from legacy corporate platforms.
25
+
26
+ * **Task:** Build a resilient, automated command-line sanitation workflow capable of operating completely isolated from system-level environment risks. It must stream arbitrary file volumes, standardize dynamic mixed date formats, isolate corrupt multi-column breaks, and strip invisible anomalies without processing loop disruptions.
27
+
28
+ * **Action:** Implemented a strict modular Python streaming engine. Wrapped processing iterations within isolated `try-except` data boundaries, enforced `python-dotenv` masking configurations to eliminate raw environment path leaks, integrated `python-dateutil` for automated timeline parsing, and diverted structural edge cases into isolated fault logs.
29
+
30
+ * **Result:** Achieved 100% crash-resilient streaming loops over highly asymmetric rows. Converts messy runtime string configurations into clean ISO 8601 formatting, intercepts operating system level directory faults safely, and scales gracefully across large data sheets with a flat horizontal memory allocation signature.
31
+
32
+ ---
33
+
34
+ ## ⚙️ Environment Setup & Installation
35
+
36
+ 1. Initialize the Virtual Workspace
37
+ Isolate the project dependency layout from your global system environment:
38
+
39
+ ```powershell
40
+ python -m venv .venv
41
+ .\.venv\Scripts\Activate.ps1
42
+ ```
43
+
44
+ 2. Dependency Ingestion
45
+ Install the concrete engine components into your active virtual bubble:
46
+ python -m pip install python-dotenv python-dateutil pytest
47
+
48
+ 3. Environment Context
49
+ Create an .env file in the root workspace directory to configure engine file streams dynamically:
50
+ TARGET_INPUT_DIR=./data/Input
51
+ CLEAN_OUTPUT_DIR=./data/Output
52
+ ERROR_LOG_PATH=./data/Output/malformed_rows.log
53
+
54
+ 🚀 Execution & Verification Pipelines
55
+ Core Pipeline Execution
56
+ To ingest, sanitize, and execute the core cleaning loops against your raw data targets:
57
+ python .\Src\main.py
58
+
59
+ Test Suite Validation
60
+ Execute full system assertion validations via the explicit Python module path layer:
61
+ python -m pytest -v
62
+
63
+
64
+ 📊 Pipeline Architecture
65
+ The following data flow map demonstrates how data transitions through our validation layers cleanly:
66
+
67
+ ```mermaid
68
+ graph TD
69
+ %% Base Color Layout Schemes
70
+ classDef input fill:#0d47a1,stroke:#1565c0,stroke-width:2px,color:#ffffff;
71
+ classDef process fill:#1e293b,stroke:#3b82f6,stroke-width:2px,color:#f8fafc;
72
+ classDef decision fill:#311b92,stroke:#673ab7,stroke-width:2px,color:#ffffff;
73
+ classDef success fill:#1b5e20,stroke:#2e7d32,stroke-width:2px,color:#ffffff;
74
+ classDef failure fill:#b71c1c,stroke:#c62828,stroke-width:2px,color:#ffffff;
75
+
76
+ %% Data Pipeline Node Tree Map
77
+ A([📥 Raw Dirty CSV Input Target]) --> B[⚙️ Load Environment Config via python-dotenv]
78
+ B --> C{🔍 Is Directory Valid?}
79
+
80
+ C -- Path Fault --> D[❌ Abort Loop & Log Configuration Fault]
81
+ C -- Valid Path --> E[🔄 Stream Row-by-Row Active Iterator]
82
+
83
+ E --> F{📐 Check Column Schema Dimensions}
84
+
85
+ F -- Size Mismatch --> G[⚠️ Route Malformed Row to Fault Log]
86
+ F -- Uniform Schema --> H[🪥 Clean Whitespace & Strip Hidden Bytes]
87
+
88
+ H --> I[📅 Standardize Mixed Timestamps to ISO 8601]
89
+ I --> J[📤 Commit Sanitized Payload to Stream Buffer]
90
+ J --> K([✨ Complete Production CSV File Pipeline])
91
+
92
+ %% Dynamic Class Injections
93
+ class A input;
94
+ class C,F decision;
95
+ class B,E,H,I,J process;
96
+ class D,G failure;
97
+ class K success;
@@ -0,0 +1,8 @@
1
+ CSV_Sanitizer/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ CSV_Sanitizer/cli.py,sha256=kO8uS3Yo-Sy1JI8F_ftz_rUr8vkPa_0iHBrbLiMhLuk,2432
3
+ CSV_Sanitizer/core.py,sha256=RSBRXir3j4Vf6u0igXbgarMxWr06yZ32NXwBBh7KiHk,3047
4
+ csv_sanitizer_schema_validator-0.1.0.dist-info/METADATA,sha256=meaACU9jtXYvw1K48WH29MUeXNsB27Q_6w0_8l6FNjg,4460
5
+ csv_sanitizer_schema_validator-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
6
+ csv_sanitizer_schema_validator-0.1.0.dist-info/entry_points.txt,sha256=cY1ARZTYm50ze-BdESmwuqECxCZeTFKycqHkt7DD00k,57
7
+ csv_sanitizer_schema_validator-0.1.0.dist-info/licenses/LICENSE,sha256=MsH4OflZgWa6Rbw-HstDYhZi6lwCweFMSz4XQBy2xN0,1089
8
+ csv_sanitizer_schema_validator-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ csv-sanitizer = CSV_Sanitizer.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 hgandhi2010
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.