smith-utils 0.3.0__tar.gz → 0.4.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.
Files changed (34) hide show
  1. smith_utils-0.4.0/.gitignore +59 -0
  2. {smith_utils-0.3.0/src/smith_utils.egg-info → smith_utils-0.4.0}/PKG-INFO +38 -20
  3. {smith_utils-0.3.0 → smith_utils-0.4.0}/README.md +23 -5
  4. {smith_utils-0.3.0 → smith_utils-0.4.0}/pyproject.toml +17 -5
  5. {smith_utils-0.3.0 → smith_utils-0.4.0}/src/smith_utils/__init__.py +6 -0
  6. smith_utils-0.4.0/src/smith_utils/crypto/__init__.py +6 -0
  7. smith_utils-0.4.0/src/smith_utils/crypto/hashes.py +26 -0
  8. smith_utils-0.4.0/src/smith_utils/file/__init__.py +6 -0
  9. smith_utils-0.4.0/src/smith_utils/file/classification.py +177 -0
  10. smith_utils-0.4.0/tests/test_file_classification.py +79 -0
  11. smith_utils-0.4.0/tests/test_hashes.py +34 -0
  12. {smith_utils-0.3.0 → smith_utils-0.4.0}/tests/test_package_exports.py +5 -1
  13. smith_utils-0.3.0/PKG-INFO +0 -123
  14. smith_utils-0.3.0/setup.cfg +0 -4
  15. smith_utils-0.3.0/src/smith_utils.egg-info/SOURCES.txt +0 -25
  16. smith_utils-0.3.0/src/smith_utils.egg-info/dependency_links.txt +0 -1
  17. smith_utils-0.3.0/src/smith_utils.egg-info/requires.txt +0 -7
  18. smith_utils-0.3.0/src/smith_utils.egg-info/top_level.txt +0 -1
  19. {smith_utils-0.3.0 → smith_utils-0.4.0}/LICENSE +0 -0
  20. {smith_utils-0.3.0 → smith_utils-0.4.0}/src/smith_utils/datetime/__init__.py +0 -0
  21. {smith_utils-0.3.0 → smith_utils-0.4.0}/src/smith_utils/datetime/date_utils.py +0 -0
  22. {smith_utils-0.3.0 → smith_utils-0.4.0}/src/smith_utils/numeric/__init__.py +0 -0
  23. {smith_utils-0.3.0 → smith_utils-0.4.0}/src/smith_utils/numeric/refinement.py +0 -0
  24. {smith_utils-0.3.0 → smith_utils-0.4.0}/src/smith_utils/text/__init__.py +0 -0
  25. {smith_utils-0.3.0 → smith_utils-0.4.0}/src/smith_utils/text/metrics.py +0 -0
  26. {smith_utils-0.3.0 → smith_utils-0.4.0}/src/smith_utils/text/newlines.py +0 -0
  27. {smith_utils-0.3.0 → smith_utils-0.4.0}/src/smith_utils/text/normalization.py +0 -0
  28. {smith_utils-0.3.0 → smith_utils-0.4.0}/src/smith_utils/text/unicode_char_names.py +0 -0
  29. {smith_utils-0.3.0 → smith_utils-0.4.0}/tests/test_date_utils.py +0 -0
  30. {smith_utils-0.3.0 → smith_utils-0.4.0}/tests/test_metrics.py +0 -0
  31. {smith_utils-0.3.0 → smith_utils-0.4.0}/tests/test_newlines.py +0 -0
  32. {smith_utils-0.3.0 → smith_utils-0.4.0}/tests/test_normalization.py +0 -0
  33. {smith_utils-0.3.0 → smith_utils-0.4.0}/tests/test_refinement.py +0 -0
  34. {smith_utils-0.3.0 → smith_utils-0.4.0}/tests/test_unicode_char_names.py +0 -0
@@ -0,0 +1,59 @@
1
+ # Python artifacts
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # Distribution / packaging
7
+ build/
8
+ develop-eggs/
9
+ dist/
10
+ downloads/
11
+ eggs/
12
+ .eggs/
13
+ parts/
14
+ sdist/
15
+ var/
16
+ wheels/
17
+ *.egg-info/
18
+ .installed.cfg
19
+ *.egg
20
+
21
+ # Unit test / coverage reports
22
+ htmlcov/
23
+ .tox/
24
+ .nox/
25
+ .coverage
26
+ .coverage.*
27
+ .cache
28
+ nosetests.xml
29
+ coverage.xml
30
+ *.cover
31
+ *.sved
32
+ .pytest_cache/
33
+ .ruff_cache/
34
+
35
+ # Environments
36
+ .env
37
+ .venv
38
+ env/
39
+ venv/
40
+ ENV/
41
+ env.bak/
42
+ venv.bak/
43
+
44
+ # IDEs and Editors
45
+ .idea/
46
+ .vscode/
47
+ *.swp
48
+ *.swo
49
+
50
+ # Project specific
51
+ legacy/
52
+ *.log
53
+
54
+ # Documentation
55
+ docs/_build/
56
+ docs/source/generated/
57
+
58
+ # Misc
59
+ scripts/
@@ -1,7 +1,11 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: smith-utils
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: A utility library for data cleaning and parsing.
5
+ Project-URL: Homepage, https://github.com/yeiichi/smith-utils
6
+ Project-URL: Repository, https://github.com/yeiichi/smith-utils
7
+ Project-URL: Documentation, https://smith-utils.readthedocs.io/
8
+ Project-URL: Changelog, https://smith-utils.readthedocs.io/en/latest/changelog.html
5
9
  Author-email: Eiichi YAMAMOTO <info@yeiichi.com>
6
10
  License: MIT License
7
11
 
@@ -24,27 +28,23 @@ License: MIT License
24
28
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
25
29
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
26
30
  IN THE SOFTWARE.
27
-
28
- Project-URL: Homepage, https://github.com/yeiichi/smith-utils
29
- Project-URL: Repository, https://github.com/yeiichi/smith-utils
30
- Project-URL: Documentation, https://smith-utils.readthedocs.io/
31
- Project-URL: Changelog, https://smith-utils.readthedocs.io/en/latest/changelog.html
32
- Keywords: csv,deduplication,data-filtering,file-organization,filtering
31
+ License-File: LICENSE
32
+ Keywords: csv,data-filtering,deduplication,file-organization,filtering
33
+ Classifier: Intended Audience :: Developers
34
+ Classifier: License :: OSI Approved :: MIT License
33
35
  Classifier: Programming Language :: Python :: 3
34
36
  Classifier: Programming Language :: Python :: 3 :: Only
35
- Classifier: License :: OSI Approved :: MIT License
36
- Classifier: Intended Audience :: Developers
37
37
  Classifier: Topic :: Software Development :: Libraries
38
38
  Classifier: Topic :: Utilities
39
39
  Requires-Python: >=3.10
40
- Description-Content-Type: text/markdown
41
- License-File: LICENSE
40
+ Provides-Extra: dev
41
+ Requires-Dist: pytest<9,>=8; extra == 'dev'
42
42
  Provides-Extra: docs
43
- Requires-Dist: sphinx<9,>=8; extra == "docs"
44
- Requires-Dist: furo>=2024.8.6; extra == "docs"
43
+ Requires-Dist: furo>=2024.8.6; extra == 'docs'
44
+ Requires-Dist: sphinx<9,>=8; extra == 'docs'
45
45
  Provides-Extra: release
46
- Requires-Dist: python-semantic-release<10,>=9; extra == "release"
47
- Dynamic: license-file
46
+ Requires-Dist: python-semantic-release<10,>=9; extra == 'release'
47
+ Description-Content-Type: text/markdown
48
48
 
49
49
  # smith-utils
50
50
  [![PyPI version](https://img.shields.io/pypi/v/smith-utils.svg)](https://pypi.org/project/smith-utils/)
@@ -60,18 +60,18 @@ This package consolidates distributed utility functions to improve code reuse an
60
60
 
61
61
  ## Key Features
62
62
 
63
- ### 📅 Datetime Utilities (`smith_utils.datetime`)
63
+ ### Datetime Utilities (`smith_utils.datetime`)
64
64
  Robust date parsing and formatting.
65
65
  - `ensure_date`: Flexible conversion of strings, `datetime.date` objects, or `None` (returns today) into a `date` object.
66
66
  - `parse_strict_date`: Strict parsing for `YYYYMMDD` or `YYYY-MM-DD` formats, rejecting ambiguous inputs.
67
67
  - `format_ordinal`: Converts integers to ordinal strings (e.g., `1` → `"1st"`, `22` → `"22nd"`).
68
68
 
69
- ### 🔢 Numeric Refinement (`smith_utils.numeric`)
69
+ ### Numeric Refinement (`smith_utils.numeric`)
70
70
  Clean and parse messy numeric data.
71
71
  - `parse_numeric_value`: Handles custom separators, decimals, and negative formats like `(1,234.56)`.
72
72
  - `parse_currency_value`: Alias for numeric parsing, specifically for currency strings.
73
73
 
74
- ### 📝 Text Normalization & Metrics (`smith_utils.text`)
74
+ ### Text Normalization & Metrics (`smith_utils.text`)
75
75
  Standardize text and compare string similarity.
76
76
  - `normalize_text`: Unicode NFKC normalization, case folding, and whitespace handling.
77
77
  - `StringDistance`: Implementation of Damerau-Levenshtein and Jaro-Winkler algorithms for fuzzy matching.
@@ -81,6 +81,16 @@ Standardize text and compare string similarity.
81
81
  - `normalize_newlines_stream`: Stream-based newline normalization to LF with newline type detection.
82
82
  - `normalize_file_to_lf`: File-based newline normalization helper.
83
83
 
84
+ ### Crypto Hash Utilities (`smith_utils.crypto`)
85
+ Calculate SHA-256 digests for text and files.
86
+ - `get_text_digest`: Returns the SHA-256 hexadecimal digest for a text string.
87
+ - `get_file_digest`: Returns the SHA-256 hexadecimal digest for a file using streaming reads.
88
+
89
+ ### File Classification Utilities (`smith_utils.file`)
90
+ Classify files from multiple evidence sources.
91
+ - `classify_file`: Returns extension, MIME, magic-number, and `file(1)` classification evidence.
92
+ - `FileClassification`: Dataclass result containing raw signals, `file_class`, and derived categories.
93
+
84
94
  ## Installation
85
95
 
86
96
  Install via pip:
@@ -92,9 +102,9 @@ pip install smith-utils
92
102
  ## Quick Start
93
103
 
94
104
  ```python
95
- from smith_utils import ensure_date, parse_numeric_value, normalize_text
105
+ from smith_utils import ensure_date, get_text_digest, parse_numeric_value, normalize_text
96
106
  from smith_utils import make_unicode_char_name_records
97
- from smith_utils import normalize_file_to_lf
107
+ from smith_utils import classify_file, get_file_digest, normalize_file_to_lf
98
108
 
99
109
  # Datetime
100
110
  date = ensure_date("20231225") # datetime.date(2023, 12, 25)
@@ -112,6 +122,14 @@ records = make_unicode_char_name_records("Aあ")
112
122
  # Normalize a file's newlines to LF
113
123
  summary = normalize_file_to_lf("input.txt", "output.txt")
114
124
  # {'newline_type': 'CRLF', 'bytes_in': ..., 'bytes_out': ...}
125
+
126
+ # SHA-256 digests
127
+ text_digest = get_text_digest("smith-utils")
128
+ file_digest = get_file_digest("input.txt")
129
+
130
+ # File classification
131
+ classification = classify_file("input.pdf")
132
+ # FileClassification(extension='.pdf', file_class='document', categories=('document', 'pdf'), ...)
115
133
  ```
116
134
 
117
135
  ## Directory Structure
@@ -12,18 +12,18 @@ This package consolidates distributed utility functions to improve code reuse an
12
12
 
13
13
  ## Key Features
14
14
 
15
- ### 📅 Datetime Utilities (`smith_utils.datetime`)
15
+ ### Datetime Utilities (`smith_utils.datetime`)
16
16
  Robust date parsing and formatting.
17
17
  - `ensure_date`: Flexible conversion of strings, `datetime.date` objects, or `None` (returns today) into a `date` object.
18
18
  - `parse_strict_date`: Strict parsing for `YYYYMMDD` or `YYYY-MM-DD` formats, rejecting ambiguous inputs.
19
19
  - `format_ordinal`: Converts integers to ordinal strings (e.g., `1` → `"1st"`, `22` → `"22nd"`).
20
20
 
21
- ### 🔢 Numeric Refinement (`smith_utils.numeric`)
21
+ ### Numeric Refinement (`smith_utils.numeric`)
22
22
  Clean and parse messy numeric data.
23
23
  - `parse_numeric_value`: Handles custom separators, decimals, and negative formats like `(1,234.56)`.
24
24
  - `parse_currency_value`: Alias for numeric parsing, specifically for currency strings.
25
25
 
26
- ### 📝 Text Normalization & Metrics (`smith_utils.text`)
26
+ ### Text Normalization & Metrics (`smith_utils.text`)
27
27
  Standardize text and compare string similarity.
28
28
  - `normalize_text`: Unicode NFKC normalization, case folding, and whitespace handling.
29
29
  - `StringDistance`: Implementation of Damerau-Levenshtein and Jaro-Winkler algorithms for fuzzy matching.
@@ -33,6 +33,16 @@ Standardize text and compare string similarity.
33
33
  - `normalize_newlines_stream`: Stream-based newline normalization to LF with newline type detection.
34
34
  - `normalize_file_to_lf`: File-based newline normalization helper.
35
35
 
36
+ ### Crypto Hash Utilities (`smith_utils.crypto`)
37
+ Calculate SHA-256 digests for text and files.
38
+ - `get_text_digest`: Returns the SHA-256 hexadecimal digest for a text string.
39
+ - `get_file_digest`: Returns the SHA-256 hexadecimal digest for a file using streaming reads.
40
+
41
+ ### File Classification Utilities (`smith_utils.file`)
42
+ Classify files from multiple evidence sources.
43
+ - `classify_file`: Returns extension, MIME, magic-number, and `file(1)` classification evidence.
44
+ - `FileClassification`: Dataclass result containing raw signals, `file_class`, and derived categories.
45
+
36
46
  ## Installation
37
47
 
38
48
  Install via pip:
@@ -44,9 +54,9 @@ pip install smith-utils
44
54
  ## Quick Start
45
55
 
46
56
  ```python
47
- from smith_utils import ensure_date, parse_numeric_value, normalize_text
57
+ from smith_utils import ensure_date, get_text_digest, parse_numeric_value, normalize_text
48
58
  from smith_utils import make_unicode_char_name_records
49
- from smith_utils import normalize_file_to_lf
59
+ from smith_utils import classify_file, get_file_digest, normalize_file_to_lf
50
60
 
51
61
  # Datetime
52
62
  date = ensure_date("20231225") # datetime.date(2023, 12, 25)
@@ -64,6 +74,14 @@ records = make_unicode_char_name_records("Aあ")
64
74
  # Normalize a file's newlines to LF
65
75
  summary = normalize_file_to_lf("input.txt", "output.txt")
66
76
  # {'newline_type': 'CRLF', 'bytes_in': ..., 'bytes_out': ...}
77
+
78
+ # SHA-256 digests
79
+ text_digest = get_text_digest("smith-utils")
80
+ file_digest = get_file_digest("input.txt")
81
+
82
+ # File classification
83
+ classification = classify_file("input.pdf")
84
+ # FileClassification(extension='.pdf', file_class='document', categories=('document', 'pdf'), ...)
67
85
  ```
68
86
 
69
87
  ## Directory Structure
@@ -1,10 +1,10 @@
1
1
  [build-system]
2
- requires = ["setuptools>=68.0", "wheel"]
3
- build-backend = "setuptools.build_meta"
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "smith-utils"
7
- version = "0.3.0"
7
+ version = "0.4.0"
8
8
  description = "A utility library for data cleaning and parsing."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -34,6 +34,9 @@ classifiers = [
34
34
  dependencies = []
35
35
 
36
36
  [project.optional-dependencies]
37
+ dev = [
38
+ "pytest>=8,<9",
39
+ ]
37
40
  docs = [
38
41
  "sphinx>=8,<9",
39
42
  "furo>=2024.8.6",
@@ -48,8 +51,17 @@ Repository = "https://github.com/yeiichi/smith-utils"
48
51
  Documentation = "https://smith-utils.readthedocs.io/"
49
52
  Changelog = "https://smith-utils.readthedocs.io/en/latest/changelog.html"
50
53
 
51
- [tool.setuptools.packages.find]
52
- where = ["src"]
54
+ [tool.hatch.build.targets.wheel]
55
+ packages = ["src/smith_utils"]
56
+
57
+ [tool.hatch.build.targets.sdist]
58
+ include = [
59
+ "src/smith_utils",
60
+ "tests",
61
+ "README.md",
62
+ "LICENSE",
63
+ "pyproject.toml",
64
+ ]
53
65
 
54
66
  [tool.semantic_release]
55
67
  allow_zero_version = true
@@ -1,4 +1,6 @@
1
+ from .crypto import get_file_digest, get_text_digest
1
2
  from .datetime import ensure_date, format_ordinal, parse_strict_date
3
+ from .file import FileClassification, classify_file
2
4
  from .numeric import parse_currency_value, parse_numeric_value
3
5
  from .text import (
4
6
  NewlineType,
@@ -20,8 +22,12 @@ __all__ = [
20
22
  "StringDistance",
21
23
  "UnicodeCharNameRecord",
22
24
  "analyze_pair",
25
+ "FileClassification",
26
+ "classify_file",
23
27
  "ensure_date",
24
28
  "format_ordinal",
29
+ "get_file_digest",
30
+ "get_text_digest",
25
31
  "make_unicode_char_name_records",
26
32
  "normalize_file_to_lf",
27
33
  "normalize_newlines_stream",
@@ -0,0 +1,6 @@
1
+ from .hashes import get_file_digest, get_text_digest
2
+
3
+ __all__ = [
4
+ "get_file_digest",
5
+ "get_text_digest",
6
+ ]
@@ -0,0 +1,26 @@
1
+ """Utilities for calculating SHA-256 digests."""
2
+
3
+ import hashlib
4
+ import sys
5
+ from pathlib import Path
6
+
7
+
8
+ def get_text_digest(text, encoding="utf-8"):
9
+ """Return the SHA-256 hexadecimal digest for ``text`` encoded as ``encoding``."""
10
+
11
+ return hashlib.sha256(text.encode(encoding)).hexdigest()
12
+
13
+
14
+ def get_file_digest(file_path):
15
+ """Return the SHA-256 hexadecimal digest for the file at ``file_path``."""
16
+
17
+ file_path = Path(file_path)
18
+ if sys.version_info >= (3, 11):
19
+ with open(file_path, "rb") as file:
20
+ return hashlib.file_digest(file, "sha256").hexdigest()
21
+
22
+ hasher = hashlib.sha256()
23
+ with open(file_path, "rb") as file:
24
+ while chunk := file.read(65536):
25
+ hasher.update(chunk)
26
+ return hasher.hexdigest()
@@ -0,0 +1,6 @@
1
+ from .classification import FileClassification, classify_file
2
+
3
+ __all__ = [
4
+ "FileClassification",
5
+ "classify_file",
6
+ ]
@@ -0,0 +1,177 @@
1
+ """Utilities for classifying file types from multiple signals."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ import mimetypes
7
+ from pathlib import Path
8
+ import shutil
9
+ import subprocess
10
+
11
+
12
+ _MAGIC_SIGNATURES = [
13
+ (b"%PDF-", "PDF document", "application/pdf", {"document", "pdf"}),
14
+ (b"\x89PNG\r\n\x1a\n", "PNG image", "image/png", {"image", "png"}),
15
+ (b"\xff\xd8\xff", "JPEG image", "image/jpeg", {"image", "jpeg"}),
16
+ (b"GIF87a", "GIF image", "image/gif", {"image", "gif"}),
17
+ (b"GIF89a", "GIF image", "image/gif", {"image", "gif"}),
18
+ (b"PK\x03\x04", "ZIP archive", "application/zip", {"archive", "zip"}),
19
+ (b"PK\x05\x06", "ZIP archive", "application/zip", {"archive", "zip"}),
20
+ (b"PK\x07\x08", "ZIP archive", "application/zip", {"archive", "zip"}),
21
+ (b"\x1f\x8b", "gzip compressed data", "application/gzip", {"archive", "gzip"}),
22
+ (b"BZh", "bzip2 compressed data", "application/x-bzip2", {"archive", "bzip2"}),
23
+ (b"7z\xbc\xaf\x27\x1c", "7-zip archive", "application/x-7z-compressed", {"archive", "7z"}),
24
+ (b"SQLite format 3\x00", "SQLite database", "application/vnd.sqlite3", {"database", "sqlite"}),
25
+ (b"\x7fELF", "ELF executable", "application/x-elf", {"binary", "executable", "elf"}),
26
+ (b"\xca\xfe\xba\xbe", "Java class or Mach-O universal binary", "application/octet-stream", {"binary"}),
27
+ (b"\xfe\xed\xfa\xce", "Mach-O executable", "application/x-mach-binary", {"binary", "executable", "mach-o"}),
28
+ (b"\xfe\xed\xfa\xcf", "Mach-O executable", "application/x-mach-binary", {"binary", "executable", "mach-o"}),
29
+ (b"\xce\xfa\xed\xfe", "Mach-O executable", "application/x-mach-binary", {"binary", "executable", "mach-o"}),
30
+ (b"\xcf\xfa\xed\xfe", "Mach-O executable", "application/x-mach-binary", {"binary", "executable", "mach-o"}),
31
+ ]
32
+
33
+
34
+ _MIME_CATEGORIES = {
35
+ "application/gzip": {"archive", "gzip"},
36
+ "application/pdf": {"document", "pdf"},
37
+ "application/vnd.sqlite3": {"database", "sqlite"},
38
+ "application/x-7z-compressed": {"archive", "7z"},
39
+ "application/x-bzip2": {"archive", "bzip2"},
40
+ "application/x-elf": {"binary", "executable", "elf"},
41
+ "application/x-mach-binary": {"binary", "executable", "mach-o"},
42
+ "application/zip": {"archive", "zip"},
43
+ "text/csv": {"text", "csv"},
44
+ }
45
+
46
+
47
+ _EXTENSION_CATEGORIES = {
48
+ ".7z": {"archive", "7z"},
49
+ ".bz2": {"archive", "bzip2"},
50
+ ".csv": {"text", "csv"},
51
+ ".db": {"database"},
52
+ ".gif": {"image", "gif"},
53
+ ".gz": {"archive", "gzip"},
54
+ ".jpeg": {"image", "jpeg"},
55
+ ".jpg": {"image", "jpeg"},
56
+ ".json": {"text", "json"},
57
+ ".md": {"text", "markdown"},
58
+ ".pdf": {"document", "pdf"},
59
+ ".png": {"image", "png"},
60
+ ".sqlite": {"database", "sqlite"},
61
+ ".sqlite3": {"database", "sqlite"},
62
+ ".txt": {"text"},
63
+ ".zip": {"archive", "zip"},
64
+ }
65
+
66
+
67
+ _CLASS_PRIORITY = (
68
+ "document",
69
+ "image",
70
+ "video",
71
+ "audio",
72
+ "archive",
73
+ "database",
74
+ "text",
75
+ "binary",
76
+ "font",
77
+ )
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class FileClassification:
82
+ """Classification evidence for a file path."""
83
+
84
+ path: Path
85
+ extension: str
86
+ file_description: str | None
87
+ file_mime_type: str | None
88
+ extension_mime_type: str | None
89
+ magic_type: str | None
90
+ magic_mime_type: str | None
91
+ file_class: str | None
92
+ categories: tuple[str, ...]
93
+
94
+
95
+ def classify_file(path: str | Path, *, sample_size: int = 4096) -> FileClassification:
96
+ """Classify a file using extension, magic bytes, MIME, and ``file(1)`` signals."""
97
+
98
+ file_path = Path(path)
99
+ extension = file_path.suffix.lower()
100
+ header = _read_header(file_path, sample_size)
101
+ magic_type, magic_mime_type, magic_categories = _classify_magic(header)
102
+ file_description = _run_file_command(file_path, "--brief")
103
+ file_mime_type = _run_file_command(file_path, "--brief", "--mime-type")
104
+ extension_mime_type = mimetypes.guess_type(file_path.name)[0]
105
+
106
+ categories = set()
107
+ categories.update(_EXTENSION_CATEGORIES.get(extension, set()))
108
+ categories.update(magic_categories)
109
+ categories.update(_categories_for_mime(extension_mime_type))
110
+ categories.update(_categories_for_mime(file_mime_type))
111
+ categories.update(_categories_for_mime(magic_mime_type))
112
+
113
+ sorted_categories = tuple(sorted(categories))
114
+
115
+ return FileClassification(
116
+ path=file_path,
117
+ extension=extension,
118
+ file_description=file_description,
119
+ file_mime_type=file_mime_type,
120
+ extension_mime_type=extension_mime_type,
121
+ magic_type=magic_type,
122
+ magic_mime_type=magic_mime_type,
123
+ file_class=_select_file_class(sorted_categories),
124
+ categories=sorted_categories,
125
+ )
126
+
127
+
128
+ def _read_header(path: Path, sample_size: int) -> bytes:
129
+ if sample_size < 1:
130
+ raise ValueError("sample_size must be greater than zero")
131
+
132
+ with path.open("rb") as file:
133
+ return file.read(sample_size)
134
+
135
+
136
+ def _classify_magic(header: bytes) -> tuple[str | None, str | None, set[str]]:
137
+ for signature, file_type, mime_type, categories in _MAGIC_SIGNATURES:
138
+ if header.startswith(signature):
139
+ return file_type, mime_type, set(categories)
140
+ return None, None, set()
141
+
142
+
143
+ def _categories_for_mime(mime_type: str | None) -> set[str]:
144
+ if not mime_type:
145
+ return set()
146
+
147
+ categories = set(_MIME_CATEGORIES.get(mime_type, set()))
148
+ root_type = mime_type.split("/", 1)[0]
149
+ if root_type in {"audio", "font", "image", "text", "video"}:
150
+ categories.add(root_type)
151
+ return categories
152
+
153
+
154
+ def _select_file_class(categories: tuple[str, ...]) -> str | None:
155
+ category_set = set(categories)
156
+ for file_class in _CLASS_PRIORITY:
157
+ if file_class in category_set:
158
+ return file_class
159
+ return categories[0] if categories else None
160
+
161
+
162
+ def _run_file_command(path: Path, *args: str) -> str | None:
163
+ if shutil.which("file") is None:
164
+ return None
165
+
166
+ try:
167
+ result = subprocess.run(
168
+ ["file", *args, str(path)],
169
+ capture_output=True,
170
+ check=True,
171
+ text=True,
172
+ )
173
+ except (OSError, subprocess.CalledProcessError):
174
+ return None
175
+
176
+ output = result.stdout.strip()
177
+ return output or None
@@ -0,0 +1,79 @@
1
+ import pytest
2
+
3
+ from src.smith_utils import FileClassification, classify_file
4
+ from src.smith_utils.file import classification
5
+
6
+
7
+ def test_classify_file_combines_extension_magic_and_mime(tmp_path):
8
+ sample_file = tmp_path / "sample.pdf"
9
+ sample_file.write_bytes(b"%PDF-1.7\nsmith-utils\n")
10
+
11
+ result = classify_file(sample_file)
12
+
13
+ assert isinstance(result, FileClassification)
14
+ assert result.path == sample_file
15
+ assert result.extension == ".pdf"
16
+ assert result.extension_mime_type == "application/pdf"
17
+ assert result.magic_type == "PDF document"
18
+ assert result.magic_mime_type == "application/pdf"
19
+ assert result.file_class == "document"
20
+ assert "document" in result.categories
21
+ assert "pdf" in result.categories
22
+
23
+
24
+ def test_classify_file_detects_magic_even_when_extension_disagrees(tmp_path):
25
+ sample_file = tmp_path / "wrong.txt"
26
+ sample_file.write_bytes(b"\x89PNG\r\n\x1a\nimage bytes")
27
+
28
+ result = classify_file(sample_file)
29
+
30
+ assert result.extension == ".txt"
31
+ assert result.extension_mime_type == "text/plain"
32
+ assert result.magic_type == "PNG image"
33
+ assert result.magic_mime_type == "image/png"
34
+ assert result.file_class == "image"
35
+ assert "text" in result.categories
36
+ assert "image" in result.categories
37
+ assert "png" in result.categories
38
+
39
+
40
+ def test_classify_file_returns_file_command_output_when_available(tmp_path, monkeypatch):
41
+ sample_file = tmp_path / "sample.bin"
42
+ sample_file.write_bytes(b"data")
43
+
44
+ monkeypatch.setattr(classification.shutil, "which", lambda command: "/usr/bin/file")
45
+
46
+ def fake_run(command, capture_output, check, text):
47
+ assert command[-1] == str(sample_file)
48
+
49
+ class Result:
50
+ stdout = "ASCII text\n" if "--mime-type" not in command else "text/plain\n"
51
+
52
+ return Result()
53
+
54
+ monkeypatch.setattr(classification.subprocess, "run", fake_run)
55
+
56
+ result = classify_file(sample_file)
57
+
58
+ assert result.file_description == "ASCII text"
59
+ assert result.file_mime_type == "text/plain"
60
+ assert "text" in result.categories
61
+
62
+
63
+ def test_classify_file_tolerates_missing_file_command(tmp_path, monkeypatch):
64
+ sample_file = tmp_path / "sample.unknown"
65
+ sample_file.write_bytes(b"data")
66
+ monkeypatch.setattr(classification.shutil, "which", lambda command: None)
67
+
68
+ result = classify_file(sample_file)
69
+
70
+ assert result.file_description is None
71
+ assert result.file_mime_type is None
72
+
73
+
74
+ def test_classify_file_rejects_invalid_sample_size(tmp_path):
75
+ sample_file = tmp_path / "sample.txt"
76
+ sample_file.write_text("text")
77
+
78
+ with pytest.raises(ValueError, match="sample_size"):
79
+ classify_file(sample_file, sample_size=0)
@@ -0,0 +1,34 @@
1
+ import hashlib
2
+
3
+ from src.smith_utils import crypto
4
+ from src.smith_utils.crypto import hashes
5
+ from src.smith_utils.crypto import get_file_digest, get_text_digest
6
+
7
+
8
+ def test_get_file_digest_returns_sha256_hexdigest(tmp_path):
9
+ sample_file = tmp_path / "sample.txt"
10
+ content = b"smith-utils\n"
11
+ sample_file.write_bytes(content)
12
+
13
+ assert get_file_digest(sample_file) == hashlib.sha256(content).hexdigest()
14
+
15
+
16
+ def test_get_text_digest_returns_sha256_hexdigest():
17
+ text = "smith-utils\n"
18
+
19
+ assert get_text_digest(text) == hashlib.sha256(text.encode("utf-8")).hexdigest()
20
+
21
+
22
+ def test_get_text_digest_handles_unicode_text():
23
+ text = "こんにちは smith-utils"
24
+
25
+ assert get_text_digest(text) == hashlib.sha256(text.encode("utf-8")).hexdigest()
26
+
27
+
28
+ def test_crypto_package_exports_hash_functions():
29
+ assert "get_file_digest" in crypto.__all__
30
+ assert "get_text_digest" in crypto.__all__
31
+ assert crypto.get_file_digest is get_file_digest
32
+ assert crypto.get_text_digest is get_text_digest
33
+ assert hashes.get_file_digest is get_file_digest
34
+ assert hashes.get_text_digest is get_text_digest
@@ -1,8 +1,10 @@
1
1
  from src import smith_utils
2
2
 
3
3
 
4
- def test_text_exports_are_available_globally():
4
+ def test_exports_are_available_globally():
5
5
  expected = {
6
+ "get_file_digest",
7
+ "get_text_digest",
6
8
  "NewlineType",
7
9
  "normalize_file_to_lf",
8
10
  "normalize_newlines_stream",
@@ -13,6 +15,8 @@ def test_text_exports_are_available_globally():
13
15
  "normalize_text",
14
16
  "UnicodeCharNameRecord",
15
17
  "make_unicode_char_name_records",
18
+ "FileClassification",
19
+ "classify_file",
16
20
  }
17
21
 
18
22
  for name in expected:
@@ -1,123 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: smith-utils
3
- Version: 0.3.0
4
- Summary: A utility library for data cleaning and parsing.
5
- Author-email: Eiichi YAMAMOTO <info@yeiichi.com>
6
- License: MIT License
7
-
8
- Copyright (c) 2026 Eiichi YAMAMOTO
9
-
10
- Permission is hereby granted, free of charge, to any person obtaining a copy
11
- of this software and associated documentation files (the "Software"), to deal
12
- in the Software without restriction, including without limitation the rights
13
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
- copies of the Software, and to permit persons to whom the Software is
15
- furnished to do so, subject to the following conditions:
16
-
17
- The above copyright notice and this permission notice shall be included in
18
- all copies or substantial portions of the Software.
19
-
20
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
25
- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
26
- IN THE SOFTWARE.
27
-
28
- Project-URL: Homepage, https://github.com/yeiichi/smith-utils
29
- Project-URL: Repository, https://github.com/yeiichi/smith-utils
30
- Project-URL: Documentation, https://smith-utils.readthedocs.io/
31
- Project-URL: Changelog, https://smith-utils.readthedocs.io/en/latest/changelog.html
32
- Keywords: csv,deduplication,data-filtering,file-organization,filtering
33
- Classifier: Programming Language :: Python :: 3
34
- Classifier: Programming Language :: Python :: 3 :: Only
35
- Classifier: License :: OSI Approved :: MIT License
36
- Classifier: Intended Audience :: Developers
37
- Classifier: Topic :: Software Development :: Libraries
38
- Classifier: Topic :: Utilities
39
- Requires-Python: >=3.10
40
- Description-Content-Type: text/markdown
41
- License-File: LICENSE
42
- Provides-Extra: docs
43
- Requires-Dist: sphinx<9,>=8; extra == "docs"
44
- Requires-Dist: furo>=2024.8.6; extra == "docs"
45
- Provides-Extra: release
46
- Requires-Dist: python-semantic-release<10,>=9; extra == "release"
47
- Dynamic: license-file
48
-
49
- # smith-utils
50
- [![PyPI version](https://img.shields.io/pypi/v/smith-utils.svg)](https://pypi.org/project/smith-utils/)
51
- ![Python versions](https://img.shields.io/pypi/pyversions/smith-utils.svg)
52
- ![Status](https://img.shields.io/badge/status-Alpha-orange.svg)
53
- ![License](https://img.shields.io/badge/license-MIT-blue.svg)
54
- ![Tests](https://img.shields.io/badge/tests-passing-brightgreen.svg)
55
- [![Documentation Status](https://readthedocs.org/projects/smith-utils/badge/?version=latest)](https://smith-utils.readthedocs.io/en/latest/?badge=latest)
56
-
57
-
58
- **Smith Utils** is a central hub for data cleaning and parsing scripts.
59
- This package consolidates distributed utility functions to improve code reuse and maintenance efficiency across all yeiichi projects.
60
-
61
- ## Key Features
62
-
63
- ### 📅 Datetime Utilities (`smith_utils.datetime`)
64
- Robust date parsing and formatting.
65
- - `ensure_date`: Flexible conversion of strings, `datetime.date` objects, or `None` (returns today) into a `date` object.
66
- - `parse_strict_date`: Strict parsing for `YYYYMMDD` or `YYYY-MM-DD` formats, rejecting ambiguous inputs.
67
- - `format_ordinal`: Converts integers to ordinal strings (e.g., `1` → `"1st"`, `22` → `"22nd"`).
68
-
69
- ### 🔢 Numeric Refinement (`smith_utils.numeric`)
70
- Clean and parse messy numeric data.
71
- - `parse_numeric_value`: Handles custom separators, decimals, and negative formats like `(1,234.56)`.
72
- - `parse_currency_value`: Alias for numeric parsing, specifically for currency strings.
73
-
74
- ### 📝 Text Normalization & Metrics (`smith_utils.text`)
75
- Standardize text and compare string similarity.
76
- - `normalize_text`: Unicode NFKC normalization, case folding, and whitespace handling.
77
- - `StringDistance`: Implementation of Damerau-Levenshtein and Jaro-Winkler algorithms for fuzzy matching.
78
- - `analyze_pair`: Convenience function for string comparison returning a `Result`.
79
- - `Relation` / `Result`: Relation enum and typed result for text comparisons.
80
- - `make_unicode_char_name_records`: Extract Unicode codepoint/name metadata from text.
81
- - `normalize_newlines_stream`: Stream-based newline normalization to LF with newline type detection.
82
- - `normalize_file_to_lf`: File-based newline normalization helper.
83
-
84
- ## Installation
85
-
86
- Install via pip:
87
-
88
- ```bash
89
- pip install smith-utils
90
- ```
91
-
92
- ## Quick Start
93
-
94
- ```python
95
- from smith_utils import ensure_date, parse_numeric_value, normalize_text
96
- from smith_utils import make_unicode_char_name_records
97
- from smith_utils import normalize_file_to_lf
98
-
99
- # Datetime
100
- date = ensure_date("20231225") # datetime.date(2023, 12, 25)
101
-
102
- # Numeric
103
- value = parse_numeric_value("(1,250.50)") # -1250.5
104
-
105
- # Text
106
- clean_text = normalize_text(" Smith Utils ") # "smith utils"
107
-
108
- # Unicode metadata
109
- records = make_unicode_char_name_records("Aあ")
110
- # [UnicodeCharNameRecord(index=0, codepoint='U+0041', ...), ...]
111
-
112
- # Normalize a file's newlines to LF
113
- summary = normalize_file_to_lf("input.txt", "output.txt")
114
- # {'newline_type': 'CRLF', 'bytes_in': ..., 'bytes_out': ...}
115
- ```
116
-
117
- ## Directory Structure
118
- - `src/smith_utils/`: Main package source.
119
- - `legacy/`: Legacy scripts and templates (not included in distribution).
120
- - `tests/`: Comprehensive test suite.
121
-
122
- ## License
123
- This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
@@ -1,4 +0,0 @@
1
- [egg_info]
2
- tag_build =
3
- tag_date = 0
4
-
@@ -1,25 +0,0 @@
1
- LICENSE
2
- README.md
3
- pyproject.toml
4
- src/smith_utils/__init__.py
5
- src/smith_utils.egg-info/PKG-INFO
6
- src/smith_utils.egg-info/SOURCES.txt
7
- src/smith_utils.egg-info/dependency_links.txt
8
- src/smith_utils.egg-info/requires.txt
9
- src/smith_utils.egg-info/top_level.txt
10
- src/smith_utils/datetime/__init__.py
11
- src/smith_utils/datetime/date_utils.py
12
- src/smith_utils/numeric/__init__.py
13
- src/smith_utils/numeric/refinement.py
14
- src/smith_utils/text/__init__.py
15
- src/smith_utils/text/metrics.py
16
- src/smith_utils/text/newlines.py
17
- src/smith_utils/text/normalization.py
18
- src/smith_utils/text/unicode_char_names.py
19
- tests/test_date_utils.py
20
- tests/test_metrics.py
21
- tests/test_newlines.py
22
- tests/test_normalization.py
23
- tests/test_package_exports.py
24
- tests/test_refinement.py
25
- tests/test_unicode_char_names.py
@@ -1,7 +0,0 @@
1
-
2
- [docs]
3
- sphinx<9,>=8
4
- furo>=2024.8.6
5
-
6
- [release]
7
- python-semantic-release<10,>=9
@@ -1 +0,0 @@
1
- smith_utils
File without changes