smith-utils 0.4.0__tar.gz → 0.4.1__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 (32) hide show
  1. {smith_utils-0.4.0 → smith_utils-0.4.1}/PKG-INFO +19 -2
  2. {smith_utils-0.4.0 → smith_utils-0.4.1}/README.md +18 -1
  3. {smith_utils-0.4.0 → smith_utils-0.4.1}/pyproject.toml +4 -1
  4. {smith_utils-0.4.0 → smith_utils-0.4.1}/src/smith_utils/__init__.py +6 -0
  5. smith_utils-0.4.1/src/smith_utils/cli.py +126 -0
  6. {smith_utils-0.4.0 → smith_utils-0.4.1}/src/smith_utils/text/__init__.py +4 -0
  7. smith_utils-0.4.1/src/smith_utils/text/random_string.py +54 -0
  8. smith_utils-0.4.1/tests/test_cli.py +79 -0
  9. {smith_utils-0.4.0 → smith_utils-0.4.1}/tests/test_package_exports.py +3 -0
  10. smith_utils-0.4.1/tests/test_random_string.py +64 -0
  11. {smith_utils-0.4.0 → smith_utils-0.4.1}/.gitignore +0 -0
  12. {smith_utils-0.4.0 → smith_utils-0.4.1}/LICENSE +0 -0
  13. {smith_utils-0.4.0 → smith_utils-0.4.1}/src/smith_utils/crypto/__init__.py +0 -0
  14. {smith_utils-0.4.0 → smith_utils-0.4.1}/src/smith_utils/crypto/hashes.py +0 -0
  15. {smith_utils-0.4.0 → smith_utils-0.4.1}/src/smith_utils/datetime/__init__.py +0 -0
  16. {smith_utils-0.4.0 → smith_utils-0.4.1}/src/smith_utils/datetime/date_utils.py +0 -0
  17. {smith_utils-0.4.0 → smith_utils-0.4.1}/src/smith_utils/file/__init__.py +0 -0
  18. {smith_utils-0.4.0 → smith_utils-0.4.1}/src/smith_utils/file/classification.py +0 -0
  19. {smith_utils-0.4.0 → smith_utils-0.4.1}/src/smith_utils/numeric/__init__.py +0 -0
  20. {smith_utils-0.4.0 → smith_utils-0.4.1}/src/smith_utils/numeric/refinement.py +0 -0
  21. {smith_utils-0.4.0 → smith_utils-0.4.1}/src/smith_utils/text/metrics.py +0 -0
  22. {smith_utils-0.4.0 → smith_utils-0.4.1}/src/smith_utils/text/newlines.py +0 -0
  23. {smith_utils-0.4.0 → smith_utils-0.4.1}/src/smith_utils/text/normalization.py +0 -0
  24. {smith_utils-0.4.0 → smith_utils-0.4.1}/src/smith_utils/text/unicode_char_names.py +0 -0
  25. {smith_utils-0.4.0 → smith_utils-0.4.1}/tests/test_date_utils.py +0 -0
  26. {smith_utils-0.4.0 → smith_utils-0.4.1}/tests/test_file_classification.py +0 -0
  27. {smith_utils-0.4.0 → smith_utils-0.4.1}/tests/test_hashes.py +0 -0
  28. {smith_utils-0.4.0 → smith_utils-0.4.1}/tests/test_metrics.py +0 -0
  29. {smith_utils-0.4.0 → smith_utils-0.4.1}/tests/test_newlines.py +0 -0
  30. {smith_utils-0.4.0 → smith_utils-0.4.1}/tests/test_normalization.py +0 -0
  31. {smith_utils-0.4.0 → smith_utils-0.4.1}/tests/test_refinement.py +0 -0
  32. {smith_utils-0.4.0 → smith_utils-0.4.1}/tests/test_unicode_char_names.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: smith-utils
3
- Version: 0.4.0
3
+ Version: 0.4.1
4
4
  Summary: A utility library for data cleaning and parsing.
5
5
  Project-URL: Homepage, https://github.com/yeiichi/smith-utils
6
6
  Project-URL: Repository, https://github.com/yeiichi/smith-utils
@@ -74,6 +74,7 @@ Clean and parse messy numeric data.
74
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
+ - `random_string`: Generate random ASCII, kanji, or mixed strings using secure randomness.
77
78
  - `StringDistance`: Implementation of Damerau-Levenshtein and Jaro-Winkler algorithms for fuzzy matching.
78
79
  - `analyze_pair`: Convenience function for string comparison returning a `Result`.
79
80
  - `Relation` / `Result`: Relation enum and typed result for text comparisons.
@@ -99,10 +100,12 @@ Install via pip:
99
100
  pip install smith-utils
100
101
  ```
101
102
 
103
+ This also installs the `smith` command.
104
+
102
105
  ## Quick Start
103
106
 
104
107
  ```python
105
- from smith_utils import ensure_date, get_text_digest, parse_numeric_value, normalize_text
108
+ from smith_utils import ensure_date, get_text_digest, parse_numeric_value, normalize_text, random_string
106
109
  from smith_utils import make_unicode_char_name_records
107
110
  from smith_utils import classify_file, get_file_digest, normalize_file_to_lf
108
111
 
@@ -115,6 +118,9 @@ value = parse_numeric_value("(1,250.50)") # -1250.5
115
118
  # Text
116
119
  clean_text = normalize_text(" Smith Utils ") # "smith utils"
117
120
 
121
+ # Random strings
122
+ token = random_string(16)
123
+
118
124
  # Unicode metadata
119
125
  records = make_unicode_char_name_records("Aあ")
120
126
  # [UnicodeCharNameRecord(index=0, codepoint='U+0041', ...), ...]
@@ -132,6 +138,17 @@ classification = classify_file("input.pdf")
132
138
  # FileClassification(extension='.pdf', file_class='document', categories=('document', 'pdf'), ...)
133
139
  ```
134
140
 
141
+ ## CLI
142
+
143
+ ```bash
144
+ smith random-string 16
145
+ smith digest --text "smith-utils"
146
+ smith digest input.txt
147
+ smith normalize-text " Smith Utils "
148
+ smith unicode-names "Aあ"
149
+ smith classify-file input.pdf
150
+ ```
151
+
135
152
  ## Directory Structure
136
153
  - `src/smith_utils/`: Main package source.
137
154
  - `legacy/`: Legacy scripts and templates (not included in distribution).
@@ -26,6 +26,7 @@ Clean and parse messy numeric data.
26
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
+ - `random_string`: Generate random ASCII, kanji, or mixed strings using secure randomness.
29
30
  - `StringDistance`: Implementation of Damerau-Levenshtein and Jaro-Winkler algorithms for fuzzy matching.
30
31
  - `analyze_pair`: Convenience function for string comparison returning a `Result`.
31
32
  - `Relation` / `Result`: Relation enum and typed result for text comparisons.
@@ -51,10 +52,12 @@ Install via pip:
51
52
  pip install smith-utils
52
53
  ```
53
54
 
55
+ This also installs the `smith` command.
56
+
54
57
  ## Quick Start
55
58
 
56
59
  ```python
57
- from smith_utils import ensure_date, get_text_digest, parse_numeric_value, normalize_text
60
+ from smith_utils import ensure_date, get_text_digest, parse_numeric_value, normalize_text, random_string
58
61
  from smith_utils import make_unicode_char_name_records
59
62
  from smith_utils import classify_file, get_file_digest, normalize_file_to_lf
60
63
 
@@ -67,6 +70,9 @@ value = parse_numeric_value("(1,250.50)") # -1250.5
67
70
  # Text
68
71
  clean_text = normalize_text(" Smith Utils ") # "smith utils"
69
72
 
73
+ # Random strings
74
+ token = random_string(16)
75
+
70
76
  # Unicode metadata
71
77
  records = make_unicode_char_name_records("Aあ")
72
78
  # [UnicodeCharNameRecord(index=0, codepoint='U+0041', ...), ...]
@@ -84,6 +90,17 @@ classification = classify_file("input.pdf")
84
90
  # FileClassification(extension='.pdf', file_class='document', categories=('document', 'pdf'), ...)
85
91
  ```
86
92
 
93
+ ## CLI
94
+
95
+ ```bash
96
+ smith random-string 16
97
+ smith digest --text "smith-utils"
98
+ smith digest input.txt
99
+ smith normalize-text " Smith Utils "
100
+ smith unicode-names "Aあ"
101
+ smith classify-file input.pdf
102
+ ```
103
+
87
104
  ## Directory Structure
88
105
  - `src/smith_utils/`: Main package source.
89
106
  - `legacy/`: Legacy scripts and templates (not included in distribution).
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "smith-utils"
7
- version = "0.4.0"
7
+ version = "0.4.1"
8
8
  description = "A utility library for data cleaning and parsing."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -33,6 +33,9 @@ classifiers = [
33
33
 
34
34
  dependencies = []
35
35
 
36
+ [project.scripts]
37
+ smith = "smith_utils.cli:main"
38
+
36
39
  [project.optional-dependencies]
37
40
  dev = [
38
41
  "pytest>=8,<9",
@@ -3,6 +3,7 @@ from .datetime import ensure_date, format_ordinal, parse_strict_date
3
3
  from .file import FileClassification, classify_file
4
4
  from .numeric import parse_currency_value, parse_numeric_value
5
5
  from .text import (
6
+ CharCategory,
6
7
  NewlineType,
7
8
  Relation,
8
9
  Result,
@@ -13,9 +14,12 @@ from .text import (
13
14
  normalize_file_to_lf,
14
15
  normalize_newlines_stream,
15
16
  normalize_text,
17
+ random_mixed_char,
18
+ random_string,
16
19
  )
17
20
 
18
21
  __all__ = [
22
+ "CharCategory",
19
23
  "NewlineType",
20
24
  "Relation",
21
25
  "Result",
@@ -35,4 +39,6 @@ __all__ = [
35
39
  "parse_currency_value",
36
40
  "parse_numeric_value",
37
41
  "parse_strict_date",
42
+ "random_mixed_char",
43
+ "random_string",
38
44
  ]
@@ -0,0 +1,126 @@
1
+ """Command line interface for smith-utils."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+
8
+ from . import (
9
+ classify_file,
10
+ get_file_digest,
11
+ get_text_digest,
12
+ make_unicode_char_name_records,
13
+ normalize_text,
14
+ random_string,
15
+ )
16
+
17
+
18
+ def main(argv: list[str] | None = None) -> int:
19
+ parser = _make_parser()
20
+ args = parser.parse_args(argv)
21
+ args.func(args)
22
+ return 0
23
+
24
+
25
+ def _make_parser() -> argparse.ArgumentParser:
26
+ parser = argparse.ArgumentParser(prog="smith")
27
+ subparsers = parser.add_subparsers(dest="command", required=True)
28
+
29
+ random_parser = subparsers.add_parser("random-string", help="generate a random string")
30
+ random_parser.add_argument("length", type=int)
31
+ random_parser.add_argument(
32
+ "--category",
33
+ choices=("ascii", "kanji", "mix"),
34
+ default="ascii",
35
+ help="character category to use",
36
+ )
37
+ random_parser.add_argument(
38
+ "--ascii-ratio",
39
+ type=float,
40
+ default=0.5,
41
+ help="ASCII probability for --category mix",
42
+ )
43
+ random_parser.set_defaults(func=_random_string_command)
44
+
45
+ digest_parser = subparsers.add_parser("digest", help="calculate a SHA-256 digest")
46
+ digest_input = digest_parser.add_mutually_exclusive_group(required=True)
47
+ digest_input.add_argument("--text", help="text to digest")
48
+ digest_input.add_argument("path", nargs="?", help="file path to digest")
49
+ digest_parser.set_defaults(func=_digest_command)
50
+
51
+ normalize_parser = subparsers.add_parser("normalize-text", help="normalize text")
52
+ normalize_parser.add_argument("text", nargs="?", help="text to normalize; reads stdin when omitted")
53
+ normalize_parser.add_argument("--keep-case", action="store_true", help="preserve text case")
54
+ normalize_parser.add_argument(
55
+ "--remove-all-whitespace",
56
+ action="store_true",
57
+ help="remove all whitespace instead of collapsing it",
58
+ )
59
+ normalize_parser.add_argument("--no-nfkc", action="store_true", help="skip NFKC normalization")
60
+ normalize_parser.set_defaults(func=_normalize_text_command)
61
+
62
+ unicode_parser = subparsers.add_parser("unicode-names", help="show Unicode character names")
63
+ unicode_parser.add_argument("text", help="text to inspect")
64
+ unicode_parser.set_defaults(func=_unicode_names_command)
65
+
66
+ classify_parser = subparsers.add_parser("classify-file", help="classify a file")
67
+ classify_parser.add_argument("path", help="file path to classify")
68
+ classify_parser.set_defaults(func=_classify_file_command)
69
+
70
+ return parser
71
+
72
+
73
+ def _random_string_command(args: argparse.Namespace) -> None:
74
+ print(
75
+ random_string(
76
+ args.length,
77
+ char_category=args.category,
78
+ ascii_ratio=args.ascii_ratio,
79
+ )
80
+ )
81
+
82
+
83
+ def _digest_command(args: argparse.Namespace) -> None:
84
+ if args.text is not None:
85
+ print(get_text_digest(args.text))
86
+ return
87
+
88
+ print(get_file_digest(args.path))
89
+
90
+
91
+ def _normalize_text_command(args: argparse.Namespace) -> None:
92
+ text = sys.stdin.read() if args.text is None else args.text
93
+ print(
94
+ normalize_text(
95
+ text,
96
+ ignore_case=not args.keep_case,
97
+ remove_all_whitespace=args.remove_all_whitespace,
98
+ nfkc=not args.no_nfkc,
99
+ )
100
+ )
101
+
102
+
103
+ def _unicode_names_command(args: argparse.Namespace) -> None:
104
+ for record in make_unicode_char_name_records(args.text):
105
+ print(f"{record.index}\t{record.codepoint}\t{record.char}\t{record.name}")
106
+
107
+
108
+ def _classify_file_command(args: argparse.Namespace) -> None:
109
+ result = classify_file(args.path)
110
+ fields = (
111
+ ("path", str(result.path)),
112
+ ("extension", result.extension),
113
+ ("file_class", result.file_class),
114
+ ("categories", ",".join(result.categories)),
115
+ ("extension_mime_type", result.extension_mime_type),
116
+ ("magic_type", result.magic_type),
117
+ ("magic_mime_type", result.magic_mime_type),
118
+ ("file_description", result.file_description),
119
+ ("file_mime_type", result.file_mime_type),
120
+ )
121
+ for key, value in fields:
122
+ print(f"{key}={'' if value is None else value}")
123
+
124
+
125
+ if __name__ == "__main__":
126
+ raise SystemExit(main())
@@ -1,12 +1,16 @@
1
1
  from .metrics import StringDistance, analyze_pair, Result, Relation
2
2
  from .newlines import NewlineType, normalize_file_to_lf, normalize_newlines_stream
3
3
  from .normalization import normalize_text
4
+ from .random_string import CharCategory, random_mixed_char, random_string
4
5
  from .unicode_char_names import UnicodeCharNameRecord, make_unicode_char_name_records
5
6
 
6
7
  __all__ = [
8
+ "CharCategory",
7
9
  "NewlineType",
8
10
  "normalize_file_to_lf",
9
11
  "normalize_newlines_stream",
12
+ "random_mixed_char",
13
+ "random_string",
10
14
  "StringDistance",
11
15
  "analyze_pair",
12
16
  "Result",
@@ -0,0 +1,54 @@
1
+ """Utilities for generating random strings."""
2
+
3
+ import secrets
4
+ import string
5
+ from typing import Literal
6
+
7
+ CharCategory = Literal["ascii", "kanji", "mix"]
8
+
9
+ ASCII_CHARS = string.ascii_letters + string.digits
10
+ KANJI_CHARS = "".join(chr(i) for i in range(0x4E00, 0xA000))
11
+
12
+ CHARSETS = {
13
+ "ascii": ASCII_CHARS,
14
+ "kanji": KANJI_CHARS,
15
+ }
16
+
17
+
18
+ def _validate_length(length: int) -> None:
19
+ if length < 0:
20
+ raise ValueError("length must be greater than or equal to 0")
21
+
22
+
23
+ def _validate_ascii_ratio(ascii_ratio: float) -> None:
24
+ if not 0 <= ascii_ratio <= 1:
25
+ raise ValueError("ascii_ratio must be between 0 and 1")
26
+
27
+
28
+ def random_mixed_char(*, ascii_ratio: float = 0.5) -> str:
29
+ """Return one random ASCII or kanji character based on ``ascii_ratio``."""
30
+
31
+ _validate_ascii_ratio(ascii_ratio)
32
+ charset = ASCII_CHARS if secrets.randbelow(10_000) < ascii_ratio * 10_000 else KANJI_CHARS
33
+ return secrets.choice(charset)
34
+
35
+
36
+ def random_string(
37
+ length: int,
38
+ *,
39
+ char_category: CharCategory = "ascii",
40
+ ascii_ratio: float = 0.5,
41
+ ) -> str:
42
+ """Generate a random string of the given length and category."""
43
+
44
+ _validate_length(length)
45
+ if char_category == "mix":
46
+ return "".join(random_mixed_char(ascii_ratio=ascii_ratio) for _ in range(length))
47
+
48
+ try:
49
+ population = CHARSETS[char_category]
50
+ except KeyError:
51
+ allowed = ", ".join(repr(key) for key in (*CHARSETS, "mix"))
52
+ raise ValueError(f"char_category must be one of: {allowed}") from None
53
+
54
+ return "".join(secrets.choice(population) for _ in range(length))
@@ -0,0 +1,79 @@
1
+ import hashlib
2
+ import string
3
+
4
+ from src.smith_utils.cli import main
5
+
6
+
7
+ def test_random_string_command_prints_requested_length(capsys):
8
+ assert main(["random-string", "12"]) == 0
9
+
10
+ output = capsys.readouterr().out.strip()
11
+ assert len(output) == 12
12
+ assert set(output) <= set(string.ascii_letters + string.digits)
13
+
14
+
15
+ def test_random_string_command_accepts_category(capsys):
16
+ assert main(["random-string", "4", "--category", "kanji"]) == 0
17
+
18
+ assert len(capsys.readouterr().out.strip()) == 4
19
+
20
+
21
+ def test_digest_command_hashes_text(capsys):
22
+ assert main(["digest", "--text", "smith-utils"]) == 0
23
+
24
+ assert capsys.readouterr().out.strip() == hashlib.sha256(b"smith-utils").hexdigest()
25
+
26
+
27
+ def test_digest_command_hashes_file(tmp_path, capsys):
28
+ sample_file = tmp_path / "sample.txt"
29
+ sample_file.write_bytes(b"file content")
30
+
31
+ assert main(["digest", str(sample_file)]) == 0
32
+
33
+ assert capsys.readouterr().out.strip() == hashlib.sha256(b"file content").hexdigest()
34
+
35
+
36
+ def test_normalize_text_command_normalizes_argument(capsys):
37
+ assert main(["normalize-text", " Smith Utils "]) == 0
38
+
39
+ assert capsys.readouterr().out.strip() == "smith utils"
40
+
41
+
42
+ def test_normalize_text_command_can_read_stdin(monkeypatch, capsys):
43
+ class FakeStdin:
44
+ def read(self):
45
+ return " Hello World "
46
+
47
+ monkeypatch.setattr("src.smith_utils.cli.sys.stdin", FakeStdin())
48
+
49
+ assert main(["normalize-text"]) == 0
50
+
51
+ assert capsys.readouterr().out.strip() == "hello world"
52
+
53
+
54
+ def test_normalize_text_command_can_keep_case(capsys):
55
+ assert main(["normalize-text", "--keep-case", " Hello World "]) == 0
56
+
57
+ assert capsys.readouterr().out.strip() == "Hello World"
58
+
59
+
60
+ def test_unicode_names_command_prints_tab_separated_records(capsys):
61
+ assert main(["unicode-names", "Aあ"]) == 0
62
+
63
+ assert capsys.readouterr().out.splitlines() == [
64
+ "0\tU+0041\tA\tLATIN CAPITAL LETTER A",
65
+ "1\tU+3042\tあ\tHIRAGANA LETTER A",
66
+ ]
67
+
68
+
69
+ def test_classify_file_command_prints_key_value_fields(tmp_path, capsys):
70
+ sample_file = tmp_path / "sample.pdf"
71
+ sample_file.write_bytes(b"%PDF-1.7\nsmith-utils\n")
72
+
73
+ assert main(["classify-file", str(sample_file)]) == 0
74
+
75
+ output = capsys.readouterr().out.splitlines()
76
+ assert f"path={sample_file}" in output
77
+ assert "extension=.pdf" in output
78
+ assert "file_class=document" in output
79
+ assert "magic_type=PDF document" in output
@@ -5,9 +5,12 @@ def test_exports_are_available_globally():
5
5
  expected = {
6
6
  "get_file_digest",
7
7
  "get_text_digest",
8
+ "CharCategory",
8
9
  "NewlineType",
9
10
  "normalize_file_to_lf",
10
11
  "normalize_newlines_stream",
12
+ "random_mixed_char",
13
+ "random_string",
11
14
  "StringDistance",
12
15
  "analyze_pair",
13
16
  "Result",
@@ -0,0 +1,64 @@
1
+ import string
2
+
3
+ import pytest
4
+
5
+ from src.smith_utils import random_mixed_char, random_string
6
+ from src.smith_utils.text import CharCategory
7
+ from src.smith_utils.text.random_string import ASCII_CHARS, KANJI_CHARS
8
+
9
+
10
+ def test_random_string_generates_ascii_string_of_requested_length():
11
+ result = random_string(32)
12
+
13
+ assert len(result) == 32
14
+ assert set(result) <= set(string.ascii_letters + string.digits)
15
+
16
+
17
+ def test_random_string_generates_kanji_string_of_requested_length():
18
+ result = random_string(16, char_category="kanji")
19
+
20
+ assert len(result) == 16
21
+ assert set(result) <= set(KANJI_CHARS)
22
+
23
+
24
+ def test_random_string_generates_mixed_string_of_requested_length():
25
+ result = random_string(20, char_category="mix")
26
+
27
+ assert len(result) == 20
28
+ assert set(result) <= set(ASCII_CHARS + KANJI_CHARS)
29
+
30
+
31
+ def test_random_string_accepts_zero_length():
32
+ assert random_string(0) == ""
33
+
34
+
35
+ def test_random_string_rejects_negative_length():
36
+ with pytest.raises(ValueError, match="length"):
37
+ random_string(-1)
38
+
39
+
40
+ def test_random_string_rejects_unknown_char_category():
41
+ with pytest.raises(ValueError, match="char_category"):
42
+ random_string(8, char_category="emoji")
43
+
44
+
45
+ @pytest.mark.parametrize("ascii_ratio", [-0.1, 1.1])
46
+ def test_random_mixed_char_rejects_ascii_ratio_outside_unit_interval(ascii_ratio):
47
+ with pytest.raises(ValueError, match="ascii_ratio"):
48
+ random_mixed_char(ascii_ratio=ascii_ratio)
49
+
50
+
51
+ def test_random_mixed_char_can_force_ascii():
52
+ result = random_mixed_char(ascii_ratio=1)
53
+
54
+ assert result in ASCII_CHARS
55
+
56
+
57
+ def test_random_mixed_char_can_force_kanji():
58
+ result = random_mixed_char(ascii_ratio=0)
59
+
60
+ assert result in KANJI_CHARS
61
+
62
+
63
+ def test_char_category_type_alias_is_exported():
64
+ assert CharCategory is not None
File without changes
File without changes