Metadata-Version: 2.4
Name: ArtinKit
Version: 0.4.1
Summary: Lightweight, dependency-free Python toolkit with caching, retries, environment parsing, and 100+ utilities.
Author: Artin Karimian
License-Expression: MIT
Project-URL: Homepage, https://pypi.org/project/ArtinKit/
Project-URL: Repository, https://github.com/artinkarimian2027/ArtinKit
Project-URL: Issues, https://github.com/artinkarimian2027/ArtinKit/issues
Project-URL: Changelog, https://github.com/artinkarimian2027/ArtinKit/releases
Keywords: utilities,toolkit,json,files,text,cli,dates,collections,encoding,numbers,cache,retry,environment,configuration
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == "dev"
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: bandit>=1.7; extra == "dev"
Requires-Dist: twine>=5; extra == "dev"
Dynamic: license-file

# ✨ ArtinKit

<p align="center">
  <img src="https://raw.githubusercontent.com/artinkarimian2027/ArtinKit/main/assets/artinkit-banner.png" alt="ArtinKit — Lightweight Python Toolkit" width="100%" />
</p>

<p align="center">
  <strong>Small tools. Cleaner code. Fewer dependencies.</strong><br>
  A practical, lightweight Python toolkit for everyday development.
</p>

<p align="center">
  <a href="https://pypi.org/project/ArtinKit/"><img src="https://img.shields.io/pypi/v/ArtinKit?style=for-the-badge&logo=pypi&logoColor=white&cacheSeconds=300" alt="PyPI version"></a>
  <a href="https://pypi.org/project/ArtinKit/"><img src="https://img.shields.io/pypi/pyversions/ArtinKit?style=for-the-badge&logo=python&logoColor=white" alt="Supported Python versions"></a>
  <a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-2ea44f?style=for-the-badge" alt="MIT License"></a>
  <a href="https://github.com/artinkarimian2027/ArtinKit/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/artinkarimian2027/ArtinKit/ci.yml?branch=online-test&style=for-the-badge&label=CI" alt="CI status"></a>
</p>

**ArtinKit** is a reusable collection of small Python utilities for common development tasks: text processing, filesystem operations, JSON storage, input checks, logging, and command-line helpers.

The goal is simple: make everyday tasks easier without forcing a large framework or a long list of dependencies into your project. ArtinKit is designed for scripts, learning projects, prototypes, desktop utilities, and Python applications that benefit from small, explicit helper functions.

- **Lightweight by design:** the runtime package uses Python's standard library.
- **Straightforward APIs:** small functions with familiar Python types.
- **Unicode-aware JSON:** preserve Persian and other non-ASCII characters when storing JSON.
- **Command-line helpers:** run simple tasks directly from a terminal.
- **Open source:** distributed under the MIT License.

> [!NOTE]
> ArtinKit is a Python utility library. It is **not** an AI model, chatbot, machine-learning system, or bundled language model.

## 📚 Table of contents

- [Get started](#-get-started)
- [Features](#-features)
- [100+ extra utilities](#-100-extra-utilities)
- [Installation](#-installation)
- [Quick start](#-quick-start)
- [Text utilities](#-text-utilities)
- [File utilities](#-file-utilities)
- [JSON storage](#-json-storage)
- [Validation helpers](#-validation-helpers)
- [Logging](#-logging)
- [Security utilities](#-security-utilities)
- [Command-line interface](#-command-line-interface)
- [Offline installation on Windows](#-offline-installation-on-windows)
- [Security and responsible use](#-security-and-responsible-use)
- [Compatibility and dependencies](#-compatibility-and-dependencies)
- [Development and quality checks](#-development-and-quality-checks)
- [Project structure](#-project-structure)
- [Roadmap ideas](#-roadmap-ideas)
- [Contributing](#-contributing)
- [License](#-license)

## 🚀 Get started

### Install from PyPI

The recommended installation command uses the official PyPI index with a longer timeout:

```bash
python -m pip install ArtinKit --index-url https://pypi.org/simple --timeout 60 --retries 3
```

If your computer has multiple Python installations, or you want to ensure that pip is associated with the Python interpreter you intend to use, prefer:

```bash
python -m pip install ArtinKit
```

On many Windows systems, this form is also convenient:

```bat
py -m pip install ArtinKit
```

Upgrade an existing installation:

```bash
python -m pip install --upgrade ArtinKit
```

Check package information after installation:

```bash
python -m pip show ArtinKit
```

**Package name:** `ArtinKit`  
**Python import name:** `artinkit`  
**Python requirement:** 3.10 or newer  
**Runtime dependencies:** no mandatory third-party dependencies

> [!TIP]
> Install the package into the same virtual environment or Python interpreter that runs your program. If an import fails after installation, check which interpreter your editor or terminal is using.

## 🌟 Features

| Component | Capabilities | Typical use |
| --- | --- | --- |
| `artinkit.text` | Whitespace normalization, word counting, truncation, slug creation, line counting, blank checks, prefix/suffix removal | Clean and transform text predictably |
| `artinkit.files` | UTF-8 text reading/writing, directory creation, file listing, file-size inspection | Small scripts, local tools, configuration files |
| `artinkit.jsonstore` | Read and write JSON with Unicode preserved | Settings files, lightweight local data, simple preferences |
| `artinkit.validation` | Check non-empty strings, integer values, finite numbers, and regex matches | Preliminary input checks before application-specific logic |
| `artinkit.security` | SHA-256 text/file hashes, constant-time string comparison, secure URL-safe tokens | File integrity checks and token generation using the standard library |
| `artinkit.get_logger` | Obtain a named standard-library logger | Organize log messages in scripts and applications |
| `artinkit` command | Normalize text, inspect a file, or calculate a file SHA-256 digest | Quick tasks without writing a separate script |

### What makes it useful?

- **No required runtime add-ons:** the package's ordinary use does not require third-party runtime libraries.
- **Small, focused utilities:** use only the functions you need instead of adopting a large framework.
- **Python-standard interfaces:** work with familiar strings, paths, dictionaries, lists, and numbers.
- **Persian and Unicode-friendly JSON:** JSON output uses UTF-8 and preserves non-ASCII text.
- **Explicit file operations:** the caller chooses the path and whether missing parent directories should be created.
- **Terminal-friendly:** common supported tasks can be run using the installed CLI.
- **Developer workflow:** the repository includes tests and GitHub Actions workflows for checking code and built distributions.

ArtinKit is intentionally a small utility toolkit rather than an all-in-one framework. Its current features are listed above; integrations and capabilities not described here should not be assumed to exist.

## 🧰 100+ extra utilities

ArtinKit 0.2.0 adds **100+ small helpers** in `artinkit.extras`, grouped into five practical areas:

- **Text:** Unicode normalization, accent removal, palindrome checks, line operations, text wrapping, masking, and basic email/URL extraction.
- **Numbers:** clamping, range mapping, percentages, averages, moving averages, prime checks, GCD/LCM, factorials, and Fibonacci sequences.
- **Collections:** chunking, de-duplication, frequency counts, pairwise items, partitioning, nested dictionary lookup/merge, grouping, and sliding windows.
- **Dates and time:** UTC timestamps, ISO date parsing, date arithmetic, weekday/month labels, duration formatting, business-day counts, and date ranges.
- **Encoding and data:** Base64, URL and HTML escaping, JSON helpers, hex/binary conversion, readable byte sizes, boolean/number parsing, CSV, INI, and query-string helpers.

Example:

```python
from artinkit import extras

print(extras.chunked([1, 2, 3, 4, 5], 2))
# [[1, 2], [3, 4], [5]]

print(extras.fibonacci(7))
# [0, 1, 1, 2, 3, 5, 8]

print(extras.bytes_to_size(1536))
# 1.50 KiB
```

These helpers use Python's standard library. Validate inputs and choose functions appropriate for your application's needs; convenience helpers do not replace domain-specific validation or security review.

## 📦 Installation

### Standard installation

```bash
python -m pip install ArtinKit
```

### Installation in a virtual environment

A virtual environment helps keep project dependencies separate from other Python projects.

Create one:

```bash
python -m venv .venv
```

Activate it on Windows Command Prompt:

```bat
.venv\Scripts\activate
```

Activate it on Windows PowerShell:

```powershell
.venv\Scripts\Activate.ps1
```

Activate it on macOS or Linux:

```bash
source .venv/bin/activate
```

Then install ArtinKit:

```bash
python -m pip install ArtinKit
```

### Verify installation

```bash
python -c "import artinkit; print('ArtinKit', artinkit.__version__)"
```

If your terminal says that `artinkit` cannot be imported, confirm that the installation succeeded and that your application is using the same Python environment.

## 💻 Quick start

This example uses text, JSON, and file helpers together:

```python
from artinkit import files, jsonstore, text

# Normalize a message.
message = text.normalize_whitespace("  Hello    from   ArtinKit!  ")
print(message)
# Hello from ArtinKit!

# Write a UTF-8 text file. Missing parent directories are created.
files.write_text(
    "example-output/hello.txt",
    "Hello from ArtinKit",
    create_parents=True,
)

# Store a small settings object as JSON.
settings = {
    "language": "fa",
    "message": "سلام از آرتین‌کیت",
    "enabled": True,
}
jsonstore.save_json(
    "example-output/settings.json",
    settings,
    create_parents=True,
)

# Read the JSON file back.
loaded = jsonstore.load_json("example-output/settings.json")
print(loaded["message"])
```

The paths in this example are relative to the directory from which you run the script. Change them to paths appropriate for your application.

## ✍️ Text utilities

Import the text module:

```python
from artinkit import text
```

### Normalize whitespace

Collapse repeated whitespace and remove whitespace at the beginning and end:

```python
text.normalize_whitespace("  one   two\nthree  ")
# 'one two three'
```

### Count words

Count whitespace-separated items:

```python
text.word_count("ArtinKit makes small tasks simpler")
# 5
```

This is a simple whitespace-based count, not a linguistic tokenizer. Languages and texts that require advanced word segmentation may need a specialized tool.

### Truncate text

Limit a string to a maximum number of characters, including the suffix when it fits:

```python
text.truncate("A longer message for a preview", 18)
# 'A longer messag...'
```

The maximum length must be a non-negative integer. If the text is already short enough, it is returned unchanged.

### Create a simple slug

```python
text.slugify("ArtinKit Utility Tools")
# 'artinkit-utility-tools'
```

The current slug helper creates a basic lowercase ASCII slug. It is suitable for simple English-oriented labels; it does **not** transliterate Persian text into Latin characters.

## 📁 File utilities

Import the filesystem helpers:

```python
from artinkit import files
```

Read UTF-8 text:

```python
content = files.read_text("notes.txt")
```

Write text and optionally create parent directories:

```python
files.write_text(
    "output/reports/summary.txt",
    "Report complete",
    create_parents=True,
)
```

Create a directory:

```python
directory = files.ensure_dir("output/reports")
```

List files in a directory:

```python
items = files.list_files("output")
for item in items:
    print(item)
```

List files recursively:

```python
all_files = files.list_files("output", recursive=True)
```

Get a file's size in bytes:

```python
size = files.file_size("output/reports/summary.txt")
print(f"{size} bytes")
```

### File-operation behavior

- Text is read and written as UTF-8 by default.
- Parent directories are created only when you explicitly pass `create_parents=True` to the supported write helper.
- `list_files()` expects an existing directory.
- `file_size()` expects an existing regular file.
- The caller is responsible for selecting a suitable path and handling expected filesystem errors.

These helpers are not a filesystem sandbox and should not be given untrusted paths without appropriate validation and permission controls.

## 🗃️ JSON storage

ArtinKit's JSON helpers use Python's built-in `json` module and UTF-8 text files.

```python
from artinkit import jsonstore

profile = {
    "name": "Example",
    "language": "fa",
    "welcome": "سلام!",
    "notifications": True,
}

jsonstore.save_json("settings.json", profile, indent=2)
loaded_profile = jsonstore.load_json("settings.json")

print(loaded_profile["welcome"])
# سلام!
```

To create parent directories automatically:

```python
jsonstore.save_json(
    "data/preferences.json",
    {"theme": "dark"},
    create_parents=True,
)
```

### JSON notes

- Non-ASCII characters are preserved instead of being forced into escaped Unicode sequences.
- The output is UTF-8 text and ends with a newline.
- Non-finite JSON numbers such as NaN and infinity are rejected during saving.
- Invalid JSON and missing files raise normal Python exceptions, so applications can handle them with `try/except`.
- JSON is a data format, not a database engine. Use a database when you need concurrent writes, transactions, indexing, or more advanced data management.

Example error handling:

```python
import json
from artinkit import jsonstore

try:
    settings = jsonstore.load_json("settings.json")
except FileNotFoundError:
    settings = {}
except json.JSONDecodeError:
    settings = {}
```

Choose an appropriate recovery strategy for your application; silently replacing invalid configuration may not be suitable for every use case.

## ✅ Validation helpers

The validation module provides small checks for common values:

```python
from artinkit import validation

print(validation.is_non_empty_string("hello"))  # True
print(validation.is_non_empty_string("   "))     # False

print(validation.is_integer(10))                 # True
print(validation.is_integer(True))               # False

print(validation.is_finite_number(3.14))         # True
print(validation.is_finite_number(float("inf"))) # False

print(validation.matches_pattern("ABC-123", r"[A-Z]{3}-\d{3}"))  # True
```

These functions help with basic checks. They do not automatically validate a full business rule, sanitize HTML, prevent SQL injection, validate every possible email address, or replace domain-specific security controls. Add the checks your application actually requires.

## 🪵 Logging

ArtinKit exposes a helper for obtaining a named standard-library logger:

```python
import logging
from artinkit import get_logger

logger = get_logger("my_application")
logger.setLevel(logging.INFO)

# Configure handlers in your application as appropriate.
logger.info("Application started")
logger.warning("This is a sample warning")
```

The helper does not configure the root logger or add output handlers for you. Applications can choose their own log format, destination, and level.

## ⌨️ Command-line interface

ArtinKit installs an `artinkit` command.

### Normalize text

```bash
artinkit normalize "  Hello    world  "
```

Expected output:

```text
Hello world
```

### Inspect a file

```bash
artinkit file-info README.md
```

The command displays the path and size of an existing file. These commands are intentionally small utilities, not a general-purpose shell or file manager.

If the command is unavailable, first check that the package was installed into the active environment. You can also use:

```bash
python -m pip show ArtinKit
```

## 📴 Offline installation on Windows

ArtinKit can be installed on a computer that has no internet connection if you transfer the built wheel file to it. The target computer still needs a compatible Python installation.

1. On a computer with internet access, open the [ArtinKit files page on PyPI](https://pypi.org/project/ArtinKit/#files).
2. Download the wheel for the desired published version.
3. Transfer the wheel to the offline computer using an approved method.
4. Open Command Prompt in the folder containing the wheel.
5. Install it with pip's package-index access disabled.

For version **0.4.1**, the wheel is named:

```text
artinkit-0.4.1-py3-none-any.whl
```

Run:

```bat
py -m pip install --no-index --no-deps artinkit-0.4.1-py3-none-any.whl
```

Verify it:

```bat
py -c "import artinkit; print(artinkit.__version__)"
```

The `--no-index` option prevents pip from querying package indexes. The `--no-deps` option skips dependency installation; this is appropriate because the package has no mandatory third-party runtime dependencies.

**Important:** this wheel installs ArtinKit, not Python. Python 3.10 or newer must already be installed. For more detail, see [OFFLINE_INSTALL.md](OFFLINE_INSTALL.md).

## 🔐 Security and responsible use

ArtinKit is intentionally small, but no utility library can make every calling application secure automatically.

- **Network behavior:** the documented core helpers do not need to contact a remote service to perform their local text, file, JSON, validation, or logging tasks.
- **JSON:** JSON is parsed as data; loading a JSON file does not execute it as Python code. Still, validate the contents before trusting them.
- **Filesystem access:** file helpers use paths supplied by the caller. They do not create a security boundary or prevent access to sensitive files.
- **Untrusted input:** validate and constrain user-provided values before using them in paths, configuration, or application logic.
- **Permissions:** run applications with only the filesystem and system permissions they need.
- **Secrets:** never commit passwords, access tokens, private keys, personal information, or confidential configuration to the repository.
- **Dependencies:** keep build and development dependencies separate from runtime dependencies and review tool output before publishing.
- **Security reports:** report potential vulnerabilities privately to the repository owner rather than publishing sensitive exploit details in a public issue.

The project uses automated checks in its development workflow, but passing a scanner or test suite is not a guarantee that software is free of defects. Review the code and test it in the context where you plan to use it.

## 🔐 Security utilities

ArtinKit includes small helpers built on Python's standard library:

```python
from artinkit import security

# Hash text or a file for integrity checks.
text_digest = security.sha256_text("سلام")
file_digest = security.sha256_file("archive.zip")

# Generate a random URL-safe token (at least 16 bytes of entropy requested).
token = security.generate_token()

# Compare secret-like strings without ordinary early-exit equality.
valid = security.constant_time_compare(provided_token, expected_token)
```

SHA-256 is a hash, not encryption. A file digest can help detect changes only when the expected digest is obtained through a trusted channel. `constant_time_compare` does not make the surrounding application automatically secure, and generated tokens should still be stored and handled carefully.

Use the CLI to hash a file:

```bash
artinkit hash-file path/to/file.zip
```

## 🧰 Compatibility and dependencies

- **Python:** 3.10 or newer.
- **Implementation:** pure Python.
- **Required runtime dependencies:** none beyond Python's standard library.
- **Operating systems:** intended for platforms supported by the declared Python versions; filesystem paths and command examples may behave differently across operating systems.
- **Development tools:** installed separately through the optional `dev` extra.

No AI model, API key, external service, or background service is required for the documented core features.

## 🧪 Development and quality checks

To work on the project from a local clone, use a supported Python interpreter.

Install the package in editable mode with its development tools:

```bash
python -m pip install -e ".[dev]"
```

Run the test suite:

```bash
python -m pytest
```

Run the static security scan:

```bash
python -m bandit -q -r src
```

Build the source distribution and wheel:

```bash
python -m build
```

Validate the distribution metadata:

```bash
python -m twine check dist/*
```

The optional `dev` extra installs tools used for development and release checks; it is not needed by ordinary users of the library.

GitHub Actions workflows are configured for tests, security scanning, build checks, and package validation. View the [Actions page](https://github.com/artinkarimian2027/ArtinKit/actions) to inspect actual workflow results. A workflow badge is a live status indicator, not a substitute for reviewing the logs.

## 🗂️ Project structure

```text
ArtinKit/
├── .github/workflows/    # Continuous integration and publishing workflows
├── src/artinkit/         # Library source code and CLI
│   └── security.py       # Hashing and token helpers
├── tests/                # Automated tests
├── CHANGELOG.md          # Project change history
├── OFFLINE_INSTALL.md    # Offline installation guide
├── LICENSE               # MIT license text
├── pyproject.toml        # Build configuration and package metadata
└── README.md             # Project guide and examples
```

## 🧭 Roadmap ideas

Possible future directions for the project may include additional focused utilities, expanded examples, more cross-platform tests, and improved documentation. These are ideas rather than promises or existing features. Check the [issue tracker](https://github.com/artinkarimian2027/ArtinKit/issues) for current discussion and planned work.

## 🐛 Troubleshooting

**Problem: pip reports `connection-timeout` or cannot download ArtinKit**

A configured package mirror may be slow or temporarily unavailable. Try the official PyPI index with a longer timeout:

```bat
python -m pip install ArtinKit --index-url https://pypi.org/simple --timeout 60 --retries 3
```

This command uses the official PyPI index for this installation only and does not permanently change your pip configuration. It still requires a working internet connection to `pypi.org`. If it fails, check your connection, proxy, or firewall and try again later.

**Problem: `No module named 'artinkit'`**

- Confirm that installation completed successfully.
- Install using the same interpreter that runs the script: `python -m pip install ArtinKit`.
- If using a virtual environment, activate it before installing and running the code.

**Problem: `artinkit` command is not found**

- Check that the package is installed in the active environment.
- Reopen the terminal after installation if necessary.
- Run the command in the same environment where you installed the package.

**Problem: file not found**

- Relative paths are resolved from the process's current working directory, which may differ from the directory containing your Python script.
- Confirm that the file exists at the path you passed.

**Problem: invalid JSON**

- Confirm that the file contains valid JSON syntax.
- Handle `json.JSONDecodeError` if the file may be edited or supplied externally.

## 🤝 Contributing

Bug reports, documentation corrections, and practical feature suggestions are welcome through [GitHub Issues](https://github.com/artinkarimian2027/ArtinKit/issues).

When filing an issue, please include:
- The Python version and operating system.
- The ArtinKit version you installed.
- A minimal example that reproduces the issue.
- The error message or traceback, with private paths or personal information removed where appropriate.

Do not include passwords, access tokens, private keys, personal data, or confidential files in a public issue. Keep reports focused and reproducible.

## 📜 License

ArtinKit is distributed under the [MIT License](LICENSE). You may use, modify, and distribute it according to the terms in that license.

## 🔗 Project links

- 📦 [Install or view ArtinKit on PyPI](https://pypi.org/project/ArtinKit/)
- 💻 [Source code on GitHub](https://github.com/artinkarimian2027/ArtinKit)
- 🧪 [GitHub Actions](https://github.com/artinkarimian2027/ArtinKit/actions)
- 🐛 [Report an issue or suggest an improvement](https://github.com/artinkarimian2027/ArtinKit/issues)
- 📝 [Published releases](https://github.com/artinkarimian2027/ArtinKit/releases)

---

<p align="center">
  <strong>ArtinKit — practical Python helpers, with a small footprint.</strong><br>
  <a href="https://pypi.org/project/ArtinKit/">PyPI</a> ·
  <a href="https://github.com/artinkarimian2027/ArtinKit">GitHub</a> ·
  <a href="https://github.com/artinkarimian2027/ArtinKit/issues">Issues</a>
</p>


## New in ArtinKit 0.4.0

Version 0.4.0 adds three dependency-free modules while keeping existing APIs:

- `artinkit.cache` — thread-safe bounded LRU cache with per-item TTL expiration.
- `artinkit.retry` — retry calls on selected exceptions with capped exponential backoff and optional jitter.
- `artinkit.env` — typed environment-variable readers for strings, booleans, integers, finite floats, and delimited lists.

### Cache example

```python
from artinkit.cache import TTLCache
cache = TTLCache(maxsize=256, ttl=60)
cache.set("language", "fa")
print(cache.get("language", "en"))
```

### Retry example

```python
from artinkit.retry import retry_call
result = retry_call(fetch_data, attempts=3, delay=0.2, backoff=2, max_delay=2)
```

### Environment settings example

```python
from artinkit import env
port = env.get_int("APP_PORT", 8000, minimum=1, maximum=65535)
debug = env.get_bool("APP_DEBUG", False)
allowed_languages = env.get_list("APP_LANGUAGES", ["en", "fa"])
```

Retry only operations that are safe to repeat; retrying a non-idempotent operation can duplicate side effects. TTLCache is process-local, not a shared or persistent cache. Environment values are parsed but are not automatically secret-managed.


## New in ArtinKit 0.4.1

Version 0.4.1 is a release and metadata correction following 0.4.0. It keeps the new `cache`, `retry`, and `env` modules and updates the package version to `0.4.1`. No mandatory third-party runtime dependencies are added.
