chxlibrary 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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,129 @@
1
+ Metadata-Version: 2.4
2
+ Name: chxlibrary
3
+ Version: 0.1.0
4
+ Summary: Utilidades prácticas para Python: texto, números, fechas, archivos y funciones creativas.
5
+ Author: programador777lolxddd-dot
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/programador777lolxddd-dot/CHXlibrary
8
+ Project-URL: Repository, https://github.com/programador777lolxddd-dot/CHXlibrary
9
+ Project-URL: Issues, https://github.com/programador777lolxddd-dot/CHXlibrary/issues
10
+ Keywords: python,utilidades,strings,números,fechas,archivos
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Classifier: Topic :: Utilities
24
+ Requires-Python: >=3.8
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest>=7.0; extra == "dev"
29
+ Requires-Dist: build>=1.0; extra == "dev"
30
+ Requires-Dist: ruff>=0.4; extra == "dev"
31
+ Dynamic: license-file
32
+
33
+ # CHXLibrary
34
+
35
+ **CHXLibrary** es una pequeña colección de utilidades para Python, en español y sin dependencias externas de ejecución. Incluye funciones para trabajar con texto, números, fechas, archivos y herramientas creativas.
36
+
37
+ - **Distribución en PyPI:** `chxlibrary`
38
+ - **Módulo de importación:** `chrotrixurum`
39
+ - **Versión actual del proyecto:** `0.1.0`
40
+ - **Python:** 3.8 o superior
41
+ - **Licencia:** Apache-2.0
42
+
43
+ ## Instalación
44
+
45
+ Cuando la publicación esté disponible en PyPI:
46
+
47
+ ```bash
48
+ python -m pip install chxlibrary
49
+ ```
50
+
51
+ Para desarrollar desde este repositorio:
52
+
53
+ ```bash
54
+ git clone https://github.com/programador777lolxddd-dot/CHXlibrary.git
55
+ cd CHXlibrary
56
+ python -m pip install -e ".[dev]"
57
+ ```
58
+
59
+ ## Inicio rápido
60
+
61
+ ```python
62
+ import chrotrixurum as chx
63
+
64
+ print(chx.slugify("Hola Mundo Ñandú!")) # hola-mundo-nandu
65
+ print(chx.snake_case("HolaMundoCruel")) # hola_mundo_cruel
66
+ print(chx.clamp(15, 0, 10)) # 10
67
+ print(chx.is_prime(97)) # True
68
+ print(list(chx.fibonacci(6))) # [0, 1, 1, 2, 3, 5]
69
+ print(chx.human_size(1536)) # 1.5 KB
70
+ print(chx.is_weekend()) # True o False según la fecha actual
71
+ ```
72
+
73
+ ## Funciones disponibles
74
+
75
+ ### Texto
76
+ - `slugify(text)`: convierte texto en un slug para URLs y elimina acentos.
77
+ - `snake_case(text)`: convierte texto a `snake_case`.
78
+ - `camel_case(text)`: convierte texto a `CamelCase`.
79
+ - `truncate(text, length, suffix="…")`: limita la longitud de un texto.
80
+ - `is_palindrome(text, ignore_case=True)`: comprueba si un texto es palíndromo.
81
+
82
+ ### Números
83
+ - `clamp(value, lo, hi)`: limita un valor a un rango.
84
+ - `lerp(a, b, t)`: interpolación lineal con `t` limitado entre 0 y 1.
85
+ - `is_prime(n)`: comprueba si un entero es primo.
86
+ - `fibonacci(n)`: genera los primeros `n` números de Fibonacci.
87
+ - `percent(part, whole, decimals=1)`: devuelve un porcentaje formateado.
88
+
89
+ ### Fechas y tiempo
90
+ - `humanize_delta(delta)`: expresa una diferencia temporal en español.
91
+ - `days_between(a, b)`: calcula los días absolutos entre dos fechas.
92
+ - `is_weekend(d=None)`: comprueba si una fecha es sábado o domingo.
93
+
94
+ ### Archivos
95
+ - `human_size(bytes_)`: convierte bytes a una unidad legible.
96
+ - `read_lines_safe(path)`: lee un archivo UTF-8 línea por línea.
97
+ - `ensure_dir(path)`: crea un directorio y sus padres si hacen falta.
98
+
99
+ ### Herramientas creativas
100
+ - `divine(question, seed=None)`: genera una respuesta aleatoria reproducible con semilla.
101
+ - `sigil(text, length=12)`: genera un símbolo textual reproducible.
102
+ - `palindrome_magic(text)`: devuelve un análisis lúdico de una frase.
103
+
104
+ ## Ejecutar la demostración
105
+
106
+ ```bash
107
+ python -m chrotrixurum
108
+ ```
109
+
110
+ También puedes usar el comando instalado:
111
+
112
+ ```bash
113
+ chrotrixurum
114
+ ```
115
+
116
+ ## Pruebas
117
+
118
+ ```bash
119
+ python -m pip install -e ".[dev]"
120
+ python -m pytest
121
+ ```
122
+
123
+ ## Licencia
124
+
125
+ Este proyecto se distribuye bajo la licencia **Apache License 2.0**. Consulta el archivo [LICENSE](LICENSE) para ver el texto completo.
126
+
127
+ ## Autor y contribuciones
128
+
129
+ Creado por [programador777lolxddd-dot](https://github.com/programador777lolxddd-dot). Las sugerencias y reportes de errores se pueden enviar en [Issues](https://github.com/programador777lolxddd-dot/CHXlibrary/issues).
@@ -0,0 +1,97 @@
1
+ # CHXLibrary
2
+
3
+ **CHXLibrary** es una pequeña colección de utilidades para Python, en español y sin dependencias externas de ejecución. Incluye funciones para trabajar con texto, números, fechas, archivos y herramientas creativas.
4
+
5
+ - **Distribución en PyPI:** `chxlibrary`
6
+ - **Módulo de importación:** `chrotrixurum`
7
+ - **Versión actual del proyecto:** `0.1.0`
8
+ - **Python:** 3.8 o superior
9
+ - **Licencia:** Apache-2.0
10
+
11
+ ## Instalación
12
+
13
+ Cuando la publicación esté disponible en PyPI:
14
+
15
+ ```bash
16
+ python -m pip install chxlibrary
17
+ ```
18
+
19
+ Para desarrollar desde este repositorio:
20
+
21
+ ```bash
22
+ git clone https://github.com/programador777lolxddd-dot/CHXlibrary.git
23
+ cd CHXlibrary
24
+ python -m pip install -e ".[dev]"
25
+ ```
26
+
27
+ ## Inicio rápido
28
+
29
+ ```python
30
+ import chrotrixurum as chx
31
+
32
+ print(chx.slugify("Hola Mundo Ñandú!")) # hola-mundo-nandu
33
+ print(chx.snake_case("HolaMundoCruel")) # hola_mundo_cruel
34
+ print(chx.clamp(15, 0, 10)) # 10
35
+ print(chx.is_prime(97)) # True
36
+ print(list(chx.fibonacci(6))) # [0, 1, 1, 2, 3, 5]
37
+ print(chx.human_size(1536)) # 1.5 KB
38
+ print(chx.is_weekend()) # True o False según la fecha actual
39
+ ```
40
+
41
+ ## Funciones disponibles
42
+
43
+ ### Texto
44
+ - `slugify(text)`: convierte texto en un slug para URLs y elimina acentos.
45
+ - `snake_case(text)`: convierte texto a `snake_case`.
46
+ - `camel_case(text)`: convierte texto a `CamelCase`.
47
+ - `truncate(text, length, suffix="…")`: limita la longitud de un texto.
48
+ - `is_palindrome(text, ignore_case=True)`: comprueba si un texto es palíndromo.
49
+
50
+ ### Números
51
+ - `clamp(value, lo, hi)`: limita un valor a un rango.
52
+ - `lerp(a, b, t)`: interpolación lineal con `t` limitado entre 0 y 1.
53
+ - `is_prime(n)`: comprueba si un entero es primo.
54
+ - `fibonacci(n)`: genera los primeros `n` números de Fibonacci.
55
+ - `percent(part, whole, decimals=1)`: devuelve un porcentaje formateado.
56
+
57
+ ### Fechas y tiempo
58
+ - `humanize_delta(delta)`: expresa una diferencia temporal en español.
59
+ - `days_between(a, b)`: calcula los días absolutos entre dos fechas.
60
+ - `is_weekend(d=None)`: comprueba si una fecha es sábado o domingo.
61
+
62
+ ### Archivos
63
+ - `human_size(bytes_)`: convierte bytes a una unidad legible.
64
+ - `read_lines_safe(path)`: lee un archivo UTF-8 línea por línea.
65
+ - `ensure_dir(path)`: crea un directorio y sus padres si hacen falta.
66
+
67
+ ### Herramientas creativas
68
+ - `divine(question, seed=None)`: genera una respuesta aleatoria reproducible con semilla.
69
+ - `sigil(text, length=12)`: genera un símbolo textual reproducible.
70
+ - `palindrome_magic(text)`: devuelve un análisis lúdico de una frase.
71
+
72
+ ## Ejecutar la demostración
73
+
74
+ ```bash
75
+ python -m chrotrixurum
76
+ ```
77
+
78
+ También puedes usar el comando instalado:
79
+
80
+ ```bash
81
+ chrotrixurum
82
+ ```
83
+
84
+ ## Pruebas
85
+
86
+ ```bash
87
+ python -m pip install -e ".[dev]"
88
+ python -m pytest
89
+ ```
90
+
91
+ ## Licencia
92
+
93
+ Este proyecto se distribuye bajo la licencia **Apache License 2.0**. Consulta el archivo [LICENSE](LICENSE) para ver el texto completo.
94
+
95
+ ## Autor y contribuciones
96
+
97
+ Creado por [programador777lolxddd-dot](https://github.com/programador777lolxddd-dot). Las sugerencias y reportes de errores se pueden enviar en [Issues](https://github.com/programador777lolxddd-dot/CHXlibrary/issues).
@@ -0,0 +1,268 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ CHXLibrary — utilidades prácticas para Python.
4
+
5
+ Uso como librería:
6
+ >>> import chrotrixurum as chx
7
+ >>> chx.slugify("Hola Mundo Ñandú")
8
+ 'hola-mundo-nandu'
9
+
10
+ Uso como script:
11
+ $ python -m chrotrixurum
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import hashlib
17
+ import random
18
+ import re
19
+ import unicodedata
20
+ from datetime import date, datetime, timedelta
21
+ from pathlib import Path
22
+ from typing import Iterator, Union
23
+
24
+ __version__ = "0.1.0"
25
+ __all__ = [
26
+ "slugify", "snake_case", "camel_case", "truncate", "is_palindrome",
27
+ "clamp", "lerp", "is_prime", "fibonacci", "percent",
28
+ "humanize_delta", "days_between", "is_weekend",
29
+ "human_size", "read_lines_safe", "ensure_dir",
30
+ "divine", "sigil", "palindrome_magic", "main", "__version__",
31
+ ]
32
+
33
+
34
+ # ---------------------------------------------------------------------
35
+ # Strings
36
+ # ---------------------------------------------------------------------
37
+ def _strip_accents(text: str) -> str:
38
+ return "".join(
39
+ char for char in unicodedata.normalize("NFD", text)
40
+ if unicodedata.category(char) != "Mn"
41
+ )
42
+
43
+
44
+ def slugify(text: str) -> str:
45
+ """Convierte texto en un slug apto para URLs."""
46
+ text = _strip_accents(text).lower()
47
+ text = re.sub(r"[^a-z0-9]+", "-", text)
48
+ return text.strip("-")
49
+
50
+
51
+ def snake_case(text: str) -> str:
52
+ """Convierte CamelCase o texto libre a snake_case."""
53
+ text = re.sub(r"(.)([A-Z][a-z]+)", r"\1_\2", text)
54
+ text = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", text)
55
+ return re.sub(r"[\s\-]+", "_", text).lower().strip("_")
56
+
57
+
58
+ def camel_case(text: str) -> str:
59
+ """Convierte texto separado por espacios, guiones o guiones bajos a CamelCase."""
60
+ parts = re.split(r"[_\-\s]+", text.strip())
61
+ return "".join(part.capitalize() for part in parts if part)
62
+
63
+
64
+ def truncate(text: str, length: int, suffix: str = "…") -> str:
65
+ """Limita un texto a *length* caracteres, incluyendo el sufijo."""
66
+ if length < 0:
67
+ raise ValueError("length no puede ser negativo")
68
+ if length == 0:
69
+ return ""
70
+ if len(text) <= length:
71
+ return text
72
+ if length <= len(suffix):
73
+ return suffix[:length]
74
+ return text[: length - len(suffix)] + suffix
75
+
76
+
77
+ def is_palindrome(text: str, ignore_case: bool = True) -> bool:
78
+ """Comprueba si un texto es palíndromo, ignorando espacios y signos."""
79
+ clean = re.sub(r"[^a-zA-Z0-9]", "", _strip_accents(text))
80
+ if ignore_case:
81
+ clean = clean.lower()
82
+ return clean == clean[::-1]
83
+
84
+
85
+ # ---------------------------------------------------------------------
86
+ # Numbers
87
+ # ---------------------------------------------------------------------
88
+ def clamp(value: float, lo: float, hi: float) -> float:
89
+ """Limita *value* al rango [lo, hi]. Si el rango está invertido, lo corrige."""
90
+ if lo > hi:
91
+ lo, hi = hi, lo
92
+ return max(lo, min(hi, value))
93
+
94
+
95
+ def lerp(a: float, b: float, t: float) -> float:
96
+ """Interpola linealmente entre *a* y *b*, limitando *t* al rango [0, 1]."""
97
+ return a + (b - a) * clamp(t, 0.0, 1.0)
98
+
99
+
100
+ def is_prime(n: int) -> bool:
101
+ """Devuelve True si *n* es un número primo."""
102
+ if n < 2:
103
+ return False
104
+ if n in (2, 3):
105
+ return True
106
+ if n % 2 == 0 or n % 3 == 0:
107
+ return False
108
+ divisor = 5
109
+ while divisor * divisor <= n:
110
+ if n % divisor == 0 or n % (divisor + 2) == 0:
111
+ return False
112
+ divisor += 6
113
+ return True
114
+
115
+
116
+ def fibonacci(n: int) -> Iterator[int]:
117
+ """Genera los primeros *n* números de Fibonacci."""
118
+ if n < 0:
119
+ raise ValueError("n no puede ser negativo")
120
+ a, b = 0, 1
121
+ for _ in range(n):
122
+ yield a
123
+ a, b = b, a + b
124
+
125
+
126
+ def percent(part: float, whole: float, decimals: int = 1) -> str:
127
+ """Devuelve *part* como porcentaje de *whole*, formateado como texto."""
128
+ if decimals < 0:
129
+ raise ValueError("decimals no puede ser negativo")
130
+ if whole == 0:
131
+ return "0%"
132
+ return f"{part / whole * 100:.{decimals}f}%"
133
+
134
+
135
+ # ---------------------------------------------------------------------
136
+ # Dates
137
+ # ---------------------------------------------------------------------
138
+ def humanize_delta(delta: timedelta) -> str:
139
+ """Convierte una diferencia temporal en una frase en español.
140
+
141
+ Una diferencia positiva se interpreta como tiempo futuro; una negativa,
142
+ como tiempo pasado.
143
+ """
144
+ total_seconds = delta.total_seconds()
145
+ seconds = int(abs(total_seconds))
146
+ future = total_seconds >= 0
147
+ units = [
148
+ ("año", 365 * 24 * 3600), ("mes", 30 * 24 * 3600),
149
+ ("día", 24 * 3600), ("hora", 3600), ("minuto", 60),
150
+ ("segundo", 1),
151
+ ]
152
+ for name, unit_seconds in units:
153
+ if seconds >= unit_seconds:
154
+ count = seconds // unit_seconds
155
+ plural = "s" if count != 1 else ""
156
+ label = f"{count} {name}{plural}"
157
+ return f"{'dentro de' if future else 'hace'} {label}"
158
+ return "ahora mismo"
159
+
160
+
161
+ def days_between(a: date, b: date) -> int:
162
+ """Devuelve el número absoluto de días entre dos fechas."""
163
+ return abs((b - a).days)
164
+
165
+
166
+ def is_weekend(d: Union[date, datetime, None] = None) -> bool:
167
+ """Comprueba si una fecha es sábado o domingo; por defecto usa hoy."""
168
+ d = d or date.today()
169
+ return d.weekday() >= 5
170
+
171
+
172
+ # ---------------------------------------------------------------------
173
+ # Files
174
+ # ---------------------------------------------------------------------
175
+ def human_size(bytes_: int) -> str:
176
+ """Convierte una cantidad de bytes a una unidad legible."""
177
+ if bytes_ < 0:
178
+ raise ValueError("bytes_ no puede ser negativo")
179
+ units = ["B", "KB", "MB", "GB", "TB", "PB"]
180
+ size = float(bytes_)
181
+ for unit in units:
182
+ if size < 1024 or unit == units[-1]:
183
+ return f"{size:.1f} {unit}"
184
+ size /= 1024
185
+ return f"{size:.1f} PB"
186
+
187
+
188
+ def read_lines_safe(path: Union[str, Path]) -> Iterator[str]:
189
+ """Lee un archivo UTF-8 línea por línea, reemplazando bytes inválidos."""
190
+ with Path(path).open("r", encoding="utf-8", errors="replace") as file:
191
+ for line in file:
192
+ yield line.rstrip("\r\n")
193
+
194
+
195
+ def ensure_dir(path: Union[str, Path]) -> Path:
196
+ """Crea un directorio y sus padres si no existen, y devuelve su ruta."""
197
+ directory = Path(path)
198
+ directory.mkdir(parents=True, exist_ok=True)
199
+ return directory
200
+
201
+
202
+ # ---------------------------------------------------------------------
203
+ # Creative utilities
204
+ # ---------------------------------------------------------------------
205
+ _SIGILS = "⛧⛥✧✦✩✶✷✸❂☽☾♆♇♄♅⛤"
206
+
207
+
208
+ def divine(question: str, seed: Union[int, None] = None) -> str:
209
+ """Genera una respuesta creativa; con la misma semilla es reproducible."""
210
+ rng = random.Random(seed if seed is not None else question)
211
+ answers = [
212
+ "sí, sin duda.", "es posible.", "los astros guardan silencio.",
213
+ "no cuentes con ello.", "sí, pero con esfuerzo.",
214
+ "pregunta de nuevo más tarde.", "definitivamente no.",
215
+ "las señales apuntan a que sí.",
216
+ ]
217
+ return f"Los astros susurran: {rng.choice(answers)}"
218
+
219
+
220
+ def sigil(text: str, length: int = 12) -> str:
221
+ """Genera un sigilo reproducible a partir de un texto."""
222
+ if length < 0:
223
+ raise ValueError("length no puede ser negativo")
224
+ digest = hashlib.sha256(text.encode("utf-8")).digest()
225
+ rng = random.Random(digest)
226
+ return "".join(rng.choice(_SIGILS) for _ in range(length))
227
+
228
+
229
+ def palindrome_magic(text: str) -> dict:
230
+ """Devuelve un análisis lúdico de una frase y su posible palíndromo."""
231
+ clean = re.sub(r"[^a-zA-Z0-9]", "", _strip_accents(text)).lower()
232
+ is_pal = clean == clean[::-1]
233
+ if is_pal:
234
+ verdict = f"{sigil(text)} Los ecos se repiten. Karma elevado."
235
+ else:
236
+ verdict = f"{sigil(text)} Los ecos se dispersan. Karma terrenal."
237
+ return {
238
+ "texto": text,
239
+ "limpio": clean,
240
+ "es_palindromo": is_pal,
241
+ "longitud": len(clean),
242
+ "karma": "elevado" if is_pal else "terrenal",
243
+ "veredicto": verdict,
244
+ }
245
+
246
+
247
+ def main() -> None:
248
+ """Ejecuta una demostración breve de las funciones principales."""
249
+ print(f"CHXLibrary v{__version__}\n")
250
+ print("slugify :", slugify("Hola Mundo Ñandú!"))
251
+ print("snake :", snake_case("HolaMundoCruel"))
252
+ print("camel :", camel_case("hola mundo cruel"))
253
+ print("truncate:", truncate("Chrotrixurum eterno", 10))
254
+ print("palindr :", is_palindrome("Anita lava la tina"))
255
+ print("clamp :", clamp(15, 0, 10))
256
+ print("lerp :", lerp(0, 10, 0.5))
257
+ print("primo97 :", is_prime(97))
258
+ print("fib(6) :", list(fibonacci(6)))
259
+ print("percent :", percent(1, 4))
260
+ print("size :", human_size(1536))
261
+ print("delta :", humanize_delta(timedelta(hours=3, minutes=20)))
262
+ print("weekend :", is_weekend(date(2024, 1, 6)))
263
+ print("divine :", divine("¿Aprobaré el examen?"))
264
+ print("sigil :", sigil("chxlibrary"))
265
+
266
+
267
+ if __name__ == "__main__":
268
+ main()
@@ -0,0 +1,129 @@
1
+ Metadata-Version: 2.4
2
+ Name: chxlibrary
3
+ Version: 0.1.0
4
+ Summary: Utilidades prácticas para Python: texto, números, fechas, archivos y funciones creativas.
5
+ Author: programador777lolxddd-dot
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/programador777lolxddd-dot/CHXlibrary
8
+ Project-URL: Repository, https://github.com/programador777lolxddd-dot/CHXlibrary
9
+ Project-URL: Issues, https://github.com/programador777lolxddd-dot/CHXlibrary/issues
10
+ Keywords: python,utilidades,strings,números,fechas,archivos
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Classifier: Topic :: Utilities
24
+ Requires-Python: >=3.8
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest>=7.0; extra == "dev"
29
+ Requires-Dist: build>=1.0; extra == "dev"
30
+ Requires-Dist: ruff>=0.4; extra == "dev"
31
+ Dynamic: license-file
32
+
33
+ # CHXLibrary
34
+
35
+ **CHXLibrary** es una pequeña colección de utilidades para Python, en español y sin dependencias externas de ejecución. Incluye funciones para trabajar con texto, números, fechas, archivos y herramientas creativas.
36
+
37
+ - **Distribución en PyPI:** `chxlibrary`
38
+ - **Módulo de importación:** `chrotrixurum`
39
+ - **Versión actual del proyecto:** `0.1.0`
40
+ - **Python:** 3.8 o superior
41
+ - **Licencia:** Apache-2.0
42
+
43
+ ## Instalación
44
+
45
+ Cuando la publicación esté disponible en PyPI:
46
+
47
+ ```bash
48
+ python -m pip install chxlibrary
49
+ ```
50
+
51
+ Para desarrollar desde este repositorio:
52
+
53
+ ```bash
54
+ git clone https://github.com/programador777lolxddd-dot/CHXlibrary.git
55
+ cd CHXlibrary
56
+ python -m pip install -e ".[dev]"
57
+ ```
58
+
59
+ ## Inicio rápido
60
+
61
+ ```python
62
+ import chrotrixurum as chx
63
+
64
+ print(chx.slugify("Hola Mundo Ñandú!")) # hola-mundo-nandu
65
+ print(chx.snake_case("HolaMundoCruel")) # hola_mundo_cruel
66
+ print(chx.clamp(15, 0, 10)) # 10
67
+ print(chx.is_prime(97)) # True
68
+ print(list(chx.fibonacci(6))) # [0, 1, 1, 2, 3, 5]
69
+ print(chx.human_size(1536)) # 1.5 KB
70
+ print(chx.is_weekend()) # True o False según la fecha actual
71
+ ```
72
+
73
+ ## Funciones disponibles
74
+
75
+ ### Texto
76
+ - `slugify(text)`: convierte texto en un slug para URLs y elimina acentos.
77
+ - `snake_case(text)`: convierte texto a `snake_case`.
78
+ - `camel_case(text)`: convierte texto a `CamelCase`.
79
+ - `truncate(text, length, suffix="…")`: limita la longitud de un texto.
80
+ - `is_palindrome(text, ignore_case=True)`: comprueba si un texto es palíndromo.
81
+
82
+ ### Números
83
+ - `clamp(value, lo, hi)`: limita un valor a un rango.
84
+ - `lerp(a, b, t)`: interpolación lineal con `t` limitado entre 0 y 1.
85
+ - `is_prime(n)`: comprueba si un entero es primo.
86
+ - `fibonacci(n)`: genera los primeros `n` números de Fibonacci.
87
+ - `percent(part, whole, decimals=1)`: devuelve un porcentaje formateado.
88
+
89
+ ### Fechas y tiempo
90
+ - `humanize_delta(delta)`: expresa una diferencia temporal en español.
91
+ - `days_between(a, b)`: calcula los días absolutos entre dos fechas.
92
+ - `is_weekend(d=None)`: comprueba si una fecha es sábado o domingo.
93
+
94
+ ### Archivos
95
+ - `human_size(bytes_)`: convierte bytes a una unidad legible.
96
+ - `read_lines_safe(path)`: lee un archivo UTF-8 línea por línea.
97
+ - `ensure_dir(path)`: crea un directorio y sus padres si hacen falta.
98
+
99
+ ### Herramientas creativas
100
+ - `divine(question, seed=None)`: genera una respuesta aleatoria reproducible con semilla.
101
+ - `sigil(text, length=12)`: genera un símbolo textual reproducible.
102
+ - `palindrome_magic(text)`: devuelve un análisis lúdico de una frase.
103
+
104
+ ## Ejecutar la demostración
105
+
106
+ ```bash
107
+ python -m chrotrixurum
108
+ ```
109
+
110
+ También puedes usar el comando instalado:
111
+
112
+ ```bash
113
+ chrotrixurum
114
+ ```
115
+
116
+ ## Pruebas
117
+
118
+ ```bash
119
+ python -m pip install -e ".[dev]"
120
+ python -m pytest
121
+ ```
122
+
123
+ ## Licencia
124
+
125
+ Este proyecto se distribuye bajo la licencia **Apache License 2.0**. Consulta el archivo [LICENSE](LICENSE) para ver el texto completo.
126
+
127
+ ## Autor y contribuciones
128
+
129
+ Creado por [programador777lolxddd-dot](https://github.com/programador777lolxddd-dot). Las sugerencias y reportes de errores se pueden enviar en [Issues](https://github.com/programador777lolxddd-dot/CHXlibrary/issues).
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ chrotrixurum.py
4
+ pyproject.toml
5
+ chxlibrary.egg-info/PKG-INFO
6
+ chxlibrary.egg-info/SOURCES.txt
7
+ chxlibrary.egg-info/dependency_links.txt
8
+ chxlibrary.egg-info/entry_points.txt
9
+ chxlibrary.egg-info/requires.txt
10
+ chxlibrary.egg-info/top_level.txt
11
+ tests/test_chrotrixurum.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ chrotrixurum = chrotrixurum:main
@@ -0,0 +1,5 @@
1
+
2
+ [dev]
3
+ pytest>=7.0
4
+ build>=1.0
5
+ ruff>=0.4
@@ -0,0 +1 @@
1
+ chrotrixurum
@@ -0,0 +1,53 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "chxlibrary"
7
+ version = "0.1.0"
8
+ description = "Utilidades prácticas para Python: texto, números, fechas, archivos y funciones creativas."
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = { text = "Apache-2.0" }
12
+ authors = [
13
+ { name = "programador777lolxddd-dot" },
14
+ ]
15
+ keywords = ["python", "utilidades", "strings", "números", "fechas", "archivos"]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Intended Audience :: Developers",
19
+ "License :: OSI Approved :: Apache Software License",
20
+ "Operating System :: OS Independent",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.8",
23
+ "Programming Language :: Python :: 3.9",
24
+ "Programming Language :: Python :: 3.10",
25
+ "Programming Language :: Python :: 3.11",
26
+ "Programming Language :: Python :: 3.12",
27
+ "Programming Language :: Python :: 3.13",
28
+ "Topic :: Software Development :: Libraries :: Python Modules",
29
+ "Topic :: Utilities",
30
+ ]
31
+
32
+ [project.urls]
33
+ Homepage = "https://github.com/programador777lolxddd-dot/CHXlibrary"
34
+ Repository = "https://github.com/programador777lolxddd-dot/CHXlibrary"
35
+ Issues = "https://github.com/programador777lolxddd-dot/CHXlibrary/issues"
36
+
37
+ [project.optional-dependencies]
38
+ dev = ["pytest>=7.0", "build>=1.0", "ruff>=0.4"]
39
+
40
+ [project.scripts]
41
+ chrotrixurum = "chrotrixurum:main"
42
+
43
+ [tool.setuptools]
44
+ py-modules = ["chrotrixurum"]
45
+
46
+ [tool.ruff]
47
+ line-length = 88
48
+ target-version = "py38"
49
+
50
+ [tool.pytest.ini_options]
51
+ minversion = "7.0"
52
+ addopts = "-ra"
53
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,82 @@
1
+ from datetime import date, datetime, timedelta
2
+
3
+ import pytest
4
+
5
+ import chrotrixurum as chx
6
+
7
+
8
+ def test_slugify_handles_accents_and_punctuation():
9
+ assert chx.slugify("¡Hola Mundo Ñandú!") == "hola-mundo-nandu"
10
+
11
+
12
+ def test_case_conversions():
13
+ assert chx.snake_case("HolaMundoCruel") == "hola_mundo_cruel"
14
+ assert chx.camel_case("hola mundo_cruel") == "HolaMundoCruel"
15
+
16
+
17
+ def test_truncate_includes_suffix_in_limit():
18
+ assert chx.truncate("Chrotrixurum eterno", 10) == "Chrotrixu…"
19
+ assert chx.truncate("corto", 10) == "corto"
20
+ assert chx.truncate("texto", 0) == ""
21
+ with pytest.raises(ValueError):
22
+ chx.truncate("texto", -1)
23
+
24
+
25
+ def test_palindrome_ignores_spaces_and_punctuation():
26
+ assert chx.is_palindrome("Anita lava la tina")
27
+ assert not chx.is_palindrome("Python")
28
+
29
+
30
+ def test_number_helpers():
31
+ assert chx.clamp(15, 0, 10) == 10
32
+ assert chx.clamp(5, 10, 0) == 5
33
+ assert chx.lerp(0, 10, 0.5) == 5
34
+ assert chx.is_prime(97)
35
+ assert not chx.is_prime(1)
36
+ assert list(chx.fibonacci(6)) == [0, 1, 1, 2, 3, 5]
37
+ with pytest.raises(ValueError):
38
+ list(chx.fibonacci(-1))
39
+
40
+
41
+ def test_percent():
42
+ assert chx.percent(1, 4) == "25.0%"
43
+ assert chx.percent(1, 0) == "0%"
44
+ with pytest.raises(ValueError):
45
+ chx.percent(1, 4, decimals=-1)
46
+
47
+
48
+ def test_dates():
49
+ assert chx.days_between(date(2024, 1, 1), date(2024, 1, 10)) == 9
50
+ assert chx.is_weekend(date(2024, 1, 6))
51
+ assert not chx.is_weekend(date(2024, 1, 8))
52
+ assert chx.humanize_delta(timedelta(hours=3)) == "dentro de 3 horas"
53
+ assert chx.humanize_delta(timedelta(hours=-3)) == "hace 3 horas"
54
+ assert chx.humanize_delta(timedelta(seconds=0)) == "ahora mismo"
55
+
56
+
57
+ def test_file_helpers(tmp_path):
58
+ assert chx.human_size(1536) == "1.5 KB"
59
+ with pytest.raises(ValueError):
60
+ chx.human_size(-1)
61
+
62
+ path = tmp_path / "nested" / "example.txt"
63
+ chx.ensure_dir(path.parent)
64
+ path.write_text("uno\ndos\n", encoding="utf-8")
65
+ assert list(chx.read_lines_safe(path)) == ["uno", "dos"]
66
+ assert chx.ensure_dir(path.parent) == path.parent
67
+
68
+
69
+ def test_creative_helpers_are_reproducible():
70
+ assert chx.divine("pregunta", seed=42) == chx.divine("pregunta", seed=42)
71
+ assert chx.sigil("texto", 8) == chx.sigil("texto", 8)
72
+ assert len(chx.sigil("texto", 8)) == 8
73
+ with pytest.raises(ValueError):
74
+ chx.sigil("texto", -1)
75
+ result = chx.palindrome_magic("Anita lava la tina")
76
+ assert result["es_palindromo"] is True
77
+ assert result["karma"] == "elevado"
78
+
79
+
80
+ def test_version_and_cli_entrypoint_exist():
81
+ assert chx.__version__ == "0.1.0"
82
+ assert callable(chx.main)