From d67df8171ada5cbe51a9edebe61d84dea1c07fe4 Mon Sep 17 00:00:00 2001 From: johanbeytell1 <107624055+johanbeytell1@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:14:14 +0000 Subject: [PATCH 1/2] Release v1.1.0: bug fixes, CIE LAB & WCAG features, tests, and PyPI Trusted Publishing Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- .github/workflows/build_and_publish.yml | 232 +- .github/workflows/ci.yml | 69 + .gitignore | 14 +- CHANGELOG.md | 45 + CONTRIBUTING.md | 60 +- Tests/test_analysis.py | 319 ++- Tests/test_colors.py | 200 +- Tests/test_conversions.py | 467 +++- Tests/test_palettes.py | 402 ++-- hued/__init__.py | 149 +- hued/analysis.py | 591 +++-- hued/colors.py | 2919 ++++++++++++----------- hued/conversions.py | 1233 ++++++---- hued/palettes.py | 715 +++--- hued/py.typed | 0 pyproject.toml | 84 + readme.md | 206 +- setup.py | 31 - 18 files changed, 4785 insertions(+), 2951 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 CHANGELOG.md create mode 100644 hued/py.typed create mode 100644 pyproject.toml delete mode 100644 setup.py diff --git a/.github/workflows/build_and_publish.yml b/.github/workflows/build_and_publish.yml index 4a9ec6b..f1cfb5c 100644 --- a/.github/workflows/build_and_publish.yml +++ b/.github/workflows/build_and_publish.yml @@ -1,34 +1,216 @@ name: Publish Python 🐍 distributions 📦 to PyPI +# Triggered by pushing a version tag such as `1.1.0` or `v1.1.0`. +# +# PyPI Trusted Publisher configuration (https://pypi.org/manage/project/hued/settings/publishing/): +# PyPI Project Name : hued +# Owner : Infinitode +# Repository name : Hued +# Workflow name : build_and_publish.yml +# Environment name : (leave blank) on: push: tags: - - '*' + - "[0-9]*.*" + - "v[0-9]*.*" + +# Strict least privilege at the workflow root; elevated permissions are granted +# only on the isolated jobs that require them. +permissions: + contents: read + +concurrency: + group: publish-${{ github.ref }} + cancel-in-progress: false jobs: - build-n-publish: - name: Build and publish Python 🐍 distributions 📦 to PyPI + build: + name: Build, test, and verify distributions runs-on: ubuntu-latest + timeout-minutes: 15 steps: - - uses: actions/checkout@master - - name: Set up Python 3.12 - uses: actions/setup-python@v3 - with: - python-version: '3.12' - - name: Install pypa/setuptools - run: >- - python -m - pip install setuptools wheel - - name: Extract tag name - id: tag - run: echo ::set-output name=TAG_NAME::$(echo $GITHUB_REF | cut -d / -f 3) - - name: Update version in setup.py - run: >- - sed -i "s/{{VERSION_PLACEHOLDER}}/${{ steps.tag.outputs.TAG_NAME }}/g" setup.py - - name: Build a binary wheel - run: >- - python setup.py sdist bdist_wheel - - name: Publish distribution 📦 to PyPI - uses: pypa/gh-action-pypi-publish@master - with: - password: ${{ secrets.PYPI_API_TOKEN }} \ No newline at end of file + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + fetch-depth: 0 + + - name: Verify the tagged commit is on main + env: + TAG_NAME: ${{ github.ref_name }} + TAG_SHA: ${{ github.sha }} + run: | + if ! git rev-parse --verify -q refs/remotes/origin/main >/dev/null; then + git fetch --no-tags origin +refs/heads/main:refs/remotes/origin/main || true + fi + if git rev-parse --verify -q refs/remotes/origin/main >/dev/null; then + if ! git merge-base --is-ancestor "$TAG_SHA" refs/remotes/origin/main; then + echo "::error::Tag $TAG_NAME ($TAG_SHA) is not on main. Merge into main before tagging." + exit 1 + fi + fi + echo "Tag $TAG_NAME is verified on main." + + - name: Set up Python 3.12 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.12" + + - name: Install build and test tooling + run: | + python -m pip install --upgrade pip build twine + python -m pip install -e ".[dev]" + + - name: Verify tag matches pyproject.toml and hued.__version__ + env: + TAG_NAME: ${{ github.ref_name }} + run: | + python - <<'PY' + import os, re, sys, tomllib + import hued + + raw_tag = os.environ["TAG_NAME"] + tag_version = raw_tag[1:] if raw_tag.startswith("v") else raw_tag + if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+((a|b|rc)[0-9]+|\.post[0-9]+|\.dev[0-9]+)?", tag_version): + sys.exit(f"Tag {raw_tag!r} is not a valid PEP 440 release version.") + + with open("pyproject.toml", "rb") as fh: + project_version = tomllib.load(fh)["project"]["version"] + + if tag_version != project_version or tag_version != hued.__version__: + sys.exit( + f"Version mismatch: tag={tag_version!r}, " + f"pyproject.toml={project_version!r}, " + f"hued.__version__={hued.__version__!r}" + ) + print(f"Verified release version: {tag_version} (from tag {raw_tag})") + PY + + - name: Lint and run test suite + run: | + ruff check . + python -m pytest -q + + - name: Build sdist and wheel + run: | + python -m build + python -m twine check --strict dist/* + + - name: Smoke-test built wheel in clean virtualenv + run: | + python -m venv /tmp/smoke-venv + /tmp/smoke-venv/bin/pip install --no-index --find-links=dist hued + /tmp/smoke-venv/bin/python -c "import hued; assert hued.rgb_to_hex(255, 0, 0) == '#FF0000'; print('Smoke test OK:', hued.__version__)" + + - name: Upload built distributions + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: python-package-distributions + path: dist/ + if-no-files-found: error + retention-days: 7 + + publish: + name: Publish to PyPI (OIDC Trusted Publishing) + needs: build + runs-on: ubuntu-latest + timeout-minutes: 15 + # NOTE: `environment` is intentionally omitted to match the blank environment + # configured in Hued's PyPI Trusted Publisher settings. + permissions: + id-token: write # Required for PyPI OIDC Trusted Publishing & PEP 740 provenance attestations + steps: + - name: Download built distributions + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: python-package-distributions + path: dist/ + + - name: Publish distributions and PEP 740 attestations to PyPI + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 + with: + packages-dir: dist/ + attestations: true + + - name: Write publish summary + env: + TAG_NAME: ${{ github.ref_name }} + run: | + VERSION="${TAG_NAME#v}" + { + echo "### Published to PyPI 📦" + echo "" + echo "| Field | Value |" + echo "| --- | --- |" + echo "| Package | \`hued\` |" + echo "| Version | \`${VERSION}\` |" + echo "| Tag | \`${TAG_NAME}\` |" + echo "| Auth | PyPI OIDC Trusted Publishing (blank environment) |" + echo "| Provenance | PEP 740 Digital Attestations (\`attestations: true\`) |" + echo "| PyPI URL | https://pypi.org/project/hued/${VERSION}/ |" + } >> "$GITHUB_STEP_SUMMARY" + + attest: + name: Attest SLSA build provenance + needs: publish + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + id-token: write + attestations: write + steps: + - name: Download built distributions + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: python-package-distributions + path: dist/ + + - name: Generate GitHub SLSA build provenance attestation + id: attest + uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 + with: + subject-path: "dist/*" + + - name: Write attestation summary + env: + ATTESTATION_URL: ${{ steps.attest.outputs.attestation-url }} + REPO: ${{ github.repository }} + run: | + { + echo "### SLSA Build Provenance 🔐" + echo "" + echo "- Attestation bundle: ${ATTESTATION_URL}" + echo "- All attestations: https://github.com/${REPO}/attestations" + echo "- Verify locally: \`gh attestation verify --repo ${REPO}\`" + } >> "$GITHUB_STEP_SUMMARY" + + release: + name: Create GitHub Release + needs: [publish, attest] + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: write + steps: + - name: Download built distributions + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: python-package-distributions + path: dist/ + + - name: Create GitHub Release (idempotent) + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + TAG_NAME: ${{ github.ref_name }} + REPO: ${{ github.repository }} + run: | + if gh release view "$TAG_NAME" --repo "$REPO" >/dev/null 2>&1; then + echo "Release $TAG_NAME already exists — leaving it untouched." + exit 0 + fi + gh release create "$TAG_NAME" dist/* \ + --repo "$REPO" \ + --verify-tag \ + --title "Hued ${TAG_NAME}" \ + --generate-notes diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..d1accbf --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,69 @@ +name: CI + +on: + push: + branches: [main, master] + pull_request: + branches: [main, master] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + lint: + name: Lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.12" + - name: Install ruff + run: python -m pip install "ruff>=0.6" + - name: Run ruff + run: ruff check . + + test: + name: Tests (Python ${{ matrix.python-version }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python-version: ${{ (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/master') && fromJSON('["3.9", "3.10", "3.11", "3.12", "3.13"]') || fromJSON('["3.9", "3.13"]') }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: ${{ matrix.python-version }} + - name: Install package and pytest + run: | + python -m pip install --upgrade pip + python -m pip install -e ".[dev]" + - name: Run tests + run: python -m pytest -q + + build: + name: Build and verify distributions + runs-on: ubuntu-latest + needs: [lint, test] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.12" + - name: Build sdist and wheel + run: | + python -m pip install --upgrade pip build twine + python -m build + python -m twine check --strict dist/* diff --git a/.gitignore b/.gitignore index 27ee28f..1e4738b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,13 @@ -__pycache__ -*.pyc +__pycache__/ +*.py[cod] +*$py.class +*.egg-info/ dist/ build/ -venv/ \ No newline at end of file +venv/ +.venv/ +.pytest_cache/ +.ruff_cache/ +.mypy_cache/ +.coverage +coverage/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..cccccce --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,45 @@ +# Changelog + +All notable changes to **Hued** are documented in this file. + +## [1.1.0] - 2026-11-18 + +A full correctness, color-science accuracy, performance, and supply-chain security release. + +### Fixed +- **`xyz_to_rgb` & all `xyz_to_*` conversions**: Fixed a `TypeError` crash caused by raising tiny negative linear channels (e.g. pure red `(255, 0, 0)` and pure green `(0, 255, 0)`) to a fractional power and producing `complex` numbers before clamping. Updated forward and inverse transformations to the standard IEC 61966-2-1 sRGB D65 matrix and companding curves for exact lossless round-trips across all sRGB colors. +- **`rgb_to_linear` & `get_luminance`**: Fixed a dead-code threshold bug (`c > 0.04045` compared against `[0, 255]` instead of normalized `c / 255`) and replaced the gamma `2.2` approximation with the exact IEC 61966-2-1 / WCAG 2.1 sRGB transfer function (`((s + 0.055) / 1.055) ** 2.4` above `0.04045`, `s / 12.92` otherwise). +- **`get_text_color_from_background`**: Fixed inverted accessibility recommendations that returned `"dark"` text on pure black `(0, 0, 0)` and charcoal backgrounds, and `"light"` text on pure yellow `(255, 255, 0)`, cyan `(0, 255, 255)`, lime `(0, 255, 0)`, and light silver `(180, 180, 180)`. Now always selects whichever of light or dark text maximizes WCAG 2.1 contrast. +- **`check_color_quality`**: Fixed a mathematical tautology where `is_good_quality` could never return `False` (`max(contrast_black, contrast_white) >= sqrt(21) ≈ 4.58 > 4.5` for all 16.7M RGB colors). Now defaults to WCAG AAA (`7.0`) when evaluating against black/white generically, and to WCAG AA (`4.5`) when evaluating against a specific `background`, while reporting explicit AA/AAA flags for both black and white. +- **`simulate_color_blindness`**: Fixed floating-point `int()` truncation and gamma drift that shifted neutral grays; updated achromatopsia weights to linear sRGB luminance (`0.2126, 0.7152, 0.0722`) and interpolated severity in linear sRGB space. +- **`get_temperature`, `is_pastel`, & `is_muted`**: + - `get_temperature` now correctly classifies yellow as `"Warm"`, cyan and teal as `"Cool"`, and near-grays as `"Neutral"`. + - `is_pastel` no longer misclassifies pure white `(255, 255, 255)` or light grays as pastel, and now recognizes soft pastels such as pastel green `(119, 221, 119)`. + - `is_muted` no longer misclassifies pure black `(0, 0, 0)` as muted, supports mid-lightness muted shades (e.g. sage green, dusty rose), and no longer shadows `brightness`. +- **`hex_to_rgb` & `rgb_to_hex`**: Fixed silent acceptance of malformed hex strings (`"##FF0000"`, `"#12345"`, `"#FF0000EXTRA"`, `"#+1+2+3"`) and out-of-range/boolean RGB values (`rgb_to_hex(-1, 0, 0)` → `"#-10000"`, `rgb_to_hex(256, 0, 0)` → `"#1000000"`). Added support for 3-digit shorthand hex codes (`"#FFF"`) and surrounding whitespace. +- **`hsl_to_hsv` & `hsv_to_hsl`**: Replaced lossy 8-bit RGB round-trips with direct analytical conversions, eliminating hue quantization drift. Enforced consistent input validation across all HSL, HSV, CMYK, XYZ, and LAB conversions, and prevented rounded hues from ever reaching `360.0`. +- **`blend_colors` & `ColorPalette.generate_gradient`**: Replaced `int()` truncation with `round()` so blending a color with itself always returns the exact input color, and added range validation for `ratio` and RGB channels. +- **`ColorPalette`**: + - Fixed `ZeroDivisionError` in `generate_monochromatic(shades=1)` and rejected `shades < 1`. + - Differentiated `generate_tetradic(angle=60)` (rectangular double-complementary) from `generate_square()` (`90°`). + - Fixed `TypeError` in `palette_to_hex()` when called after `generate_random_palette()`. + - Fixed `export_palette()` file-extension parsing (`os.path.splitext`) so extensionless filenames like `"json"` are rejected and dotted directory paths work; removed unsolicited `print()` output on errors. +- **`ColorManager` & named color catalog**: + - Removed a scraped Wikipedia vandalism entry and cleaned citation markers (`"Cinnamon[citation needed]"` → `"Cinnamon"`, `"Heidelberg Red[2]"` → `"Heidelberg Red"`). + - Disambiguated 7 duplicate color names that made secondary entries unreachable and normalized all hex strings to uppercase `#RRGGBB`. + - Preserved acronyms and apostrophes in `get_color_by_name()` (e.g. `"Air Force blue (RAF)"`, `"B'dazzled blue"`) instead of corrupting them with `.title()`. + - Added 21 missing W3C CSS named colors (`Green`, `Orange`, `Purple`, `Brown`, `Gold`, `Lavender`, `Lime`, `Maroon`, `Khaki`, `Chocolate`, `Chartreuse`, `Forest green`, `Olive drab`, `Dark gray`, and `Grey` spellings) plus hyphen/space-insensitive lookup so all 148 standard CSS Color Level 4 named colors resolve. +- **Packaging**: Migrated from broken `{{VERSION_PLACEHOLDER}}` `setup.py` to standards-compliant PEP 621 `pyproject.toml` (Python `>=3.9`), fixing local `pip install .` and `python -m build`. + +### Added +- **CIE 1976 L\*a\*b\* conversions**: `rgb_to_lab`, `lab_to_rgb`, `xyz_to_lab`, `lab_to_xyz`, `hex_to_lab`, `lab_to_hex`, `hsl_to_lab`, `lab_to_hsl`, `hsv_to_lab`, `lab_to_hsv`, `cmyk_to_lab`, `lab_to_cmyk`. +- **Color adjustment helpers**: `linear_to_rgb`, `invert_color`, `to_grayscale`, `adjust_lightness`, `adjust_saturation`, and gamma-correct `blend_colors(..., linear=True)`. +- **Perceptual difference & accessibility**: `delta_e(color1, color2, method="cie2000" | "cie76")` (validated against Sharma, Wu & Dalal 2005 CIEDE2000 test vectors) and `check_wcag_contrast(foreground, background)`. +- **Richer `ColorManager` API**: `closest_color_name(..., space="rgb" | "lab" | "cie2000")`, `get_color_by_hex`, `search_colors`, `get_random_color`, `add_color`, `remove_color`, plus module-level RGB/LAB caching. +- **Enhanced `ColorPalette` API**: Multi-space gradients (`space="rgb" | "linear" | "lab" | "hsl"`), `.css` custom-properties export, `pathlib.Path` support, and configurable `angle` on `generate_tetradic` and `generate_split_complementary`. +- **Static typing & metadata**: Full inline type annotations, PEP 561 `py.typed` marker, `hued.__version__`, and explicit `__all__` across all modules. +- **CI & Supply-Chain Provenance**: Multi-version GitHub Actions CI (`ci.yml`) and OIDC Trusted Publishing (`build_and_publish.yml`) with PEP 740 PyPI digital attestations and GitHub SLSA build provenance attestations. + +## [1.0.7] and earlier + +See `readme.md` and the [GitHub Releases](https://github.com/Infinitode/Hued/releases) history for versions `1.0.0` through `1.0.7`. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6b7c08b..5d2f329 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,49 +1,47 @@ # Contributing to Hued -Thank you for considering contributing to **Hued**! Contributions, whether they are bug fixes, new features, or improvements to the documentation, are always welcome. Before contributing, please read the following guidelines to ensure smooth collaboration. +Thank you for considering contributing to **Hued**! Contributions, whether they are bug fixes, new features, or documentation improvements, are always welcome. ## Getting Started -1. **Fork the Repository** - Create a fork of this repository to your GitHub account and clone it locally. +1. **Fork and Clone** + Fork this repository to your GitHub account and clone it locally. -2. **Set Up the Environment** - Ensure you have Python 3.6+ installed. You should also install compatible versions of the necessary dependencies for the project. +2. **Set Up a Development Environment** + Hued requires Python **3.9+** and has zero runtime dependencies. Install editable mode with development tools: -3. **Run Tests** - Before making changes, run tests to confirm that everything works. + ```bash + python -m venv .venv + source .venv/bin/activate # On Windows: .venv\Scripts\activate + pip install -e ".[dev]" + ``` -> [!TIP] -> We sometimes include testing scripts in our projects for easy testing. +3. **Run Linter and Tests** + + ```bash + ruff check . + pytest + ``` ## How to Contribute -1. **Report Issues** - Use the [GitHub Issues page](https://github.com/Infinitode/Hued/issues) to report bugs or suggest features. Please include: - - A clear description of the issue or suggestion. - - Steps to reproduce (for bugs). +1. **Report Issues** + Use the [GitHub Issues page](https://github.com/Infinitode/Hued/issues) to report bugs or suggest features with clear descriptions and reproduction steps. -2. **Make Changes** - - Use clear and descriptive commit messages. - - (Optional) Write tests to show new functionality. - - Ensure the code is **readable**. You can learn more about Python code readability here: https://peps.python.org/pep-0008/. +2. **Make Changes** + - Write clear, descriptive commit messages. + - Follow [PEP 8](https://peps.python.org/pep-0008/) and ensure `ruff check .` passes cleanly. + - Add or update unit tests in `Tests/` covering your changes. -3. **Submit a Pull Request** +3. **Submit a Pull Request** - Push your changes to a feature branch in your fork. - - Submit a pull request with a detailed explanation of what you've changed or added. - - Ensure your PR passes all automated tests and adheres to the contribution guidelines. + - Open a pull request explaining what changed and why. + - Ensure all CI checks pass. ## Community Guidelines -To maintain a positive and collaborative community, we ask that all contributors adhere to the following principles: - -1. **Be Respectful** - Treat others with respect, regardless of their background or expertise. - -2. **Provide Constructive Feedback** - Offer helpful and actionable suggestions during code reviews. - -3. **Follow Licensing Requirements** - Ensure that any derivative works comply with the [license](https://github.com/infinitode/Hued/blob/main/LICENSE). +1. **Be Respectful** — Treat everyone with respect, regardless of background or experience. +2. **Provide Constructive Feedback** — Offer helpful, actionable suggestions in code reviews. +3. **Follow Licensing Requirements** — Ensure derivative works comply with the [LICENSE](LICENSE). -By contributing, you agree to abide by these guidelines and this project's [license](https://github.com/infinitode/Hued/blob/main/LICENSE). Thank you for helping make **Hued** better! +By contributing, you agree to abide by these guidelines and this project's [LICENSE](LICENSE). Thank you for helping make **Hued** better! diff --git a/Tests/test_analysis.py b/Tests/test_analysis.py index a3a3634..2e86882 100644 --- a/Tests/test_analysis.py +++ b/Tests/test_analysis.py @@ -1,67 +1,256 @@ -from hued.analysis import is_neutral, brightness, is_pastel, is_muted, is_vibrant, color_contrast, get_text_color_from_background - -def test_is_neutral(): - print("Testing Neutral Color Check...") - neutral_color = (128, 128, 128) # Gray - non_neutral_color = (255, 0, 0) # Red - assert is_neutral(neutral_color) == True, "Expected neutral color to return True." - assert is_neutral(non_neutral_color) == False, "Expected non-neutral color to return False." - print(f"Neutral Color Test Passed: {neutral_color} is neutral.") - -def test_brightness(): - print("Testing Brightness Calculation...") - color = (255, 255, 255) # White - expected_brightness = 1.0 # Fully bright - result = brightness(color) - assert result == expected_brightness, f"Expected brightness {expected_brightness}, but got {result}." - print(f"Brightness of {color}: {result}") - -def test_is_pastel(): - print("Testing Pastel Color Check...") - pastel_color = (255, 200, 200) # Light red - non_pastel_color = (255, 0, 0) # Red - assert is_pastel(pastel_color) == True, "Expected pastel color to return True." - assert is_pastel(non_pastel_color) == False, "Expected non-pastel color to return False." - print(f"Pastel Color Test Passed: {pastel_color} is pastel.") - -def test_is_muted(): - print("Testing Muted Color Check...") - muted_color = (100, 100, 100) # Dark gray - non_muted_color = (255, 0, 0) # Red - assert is_muted(muted_color) == True, "Expected muted color to return True." - assert is_muted(non_muted_color) == False, "Expected non-muted color to return False." - print(f"Muted Color Test Passed: {muted_color} is muted.") - -def test_is_vibrant(): - print("Testing Vibrant Color Check...") - vibrant_color = (0, 255, 0) # Green - non_vibrant_color = (128, 128, 128) # Gray - assert is_vibrant(vibrant_color) == True, "Expected vibrant color to return True." - assert is_vibrant(non_vibrant_color) == False, "Expected non-vibrant color to return False." - print(f"Vibrant Color Test Passed: {vibrant_color} is vibrant.") - -def test_color_contrast(): - print("Testing Color Contrast...") - color1 = (0, 255, 0) # Green - color2 = (128, 128, 128) # Gray - assert color_contrast(color1, color2) == 2.839124370809266, "Expected a contrast ratio of 2.839124370809266." - print("Color Contrast Test Passed.") - -def test_text_mode(): - print("Testing Text Color, Based On A Background Color...") - background_color = (0, 0, 255) # Vibrant Blue - assert get_text_color_from_background(background_color) == "light", "Expected text color, to be `light`." - print("Text Background Color Test Passed.") - -def run_tests(): - test_is_neutral() - test_brightness() - test_is_pastel() - test_is_muted() - test_is_vibrant() - test_color_contrast() - test_text_mode() - print("All tests passed!") +"""Comprehensive unit tests for hued.analysis.""" + +from __future__ import annotations + +import pytest + +from hued.analysis import ( + _ciede2000, + brightness, + check_color_quality, + check_wcag_contrast, + color_contrast, + delta_e, + get_luminance, + get_temperature, + get_text_color_from_background, + get_vibrancy, + is_muted, + is_neutral, + is_pastel, + is_vibrant, + rgb_to_linear, + simulate_color_blindness, +) + + +class TestColorProperties: + @pytest.mark.parametrize( + ("rgb", "expected"), + [ + ((255, 0, 0), "Warm"), + ((255, 165, 0), "Warm"), + ((255, 255, 0), "Warm"), # regression: yellow was previously "Neutral" + ((255, 0, 64), "Warm"), + ((0, 0, 255), "Cool"), + ((0, 255, 255), "Cool"), # regression: cyan was previously "Neutral" + ((0, 128, 128), "Cool"), # regression: teal was previously "Neutral" + ((0, 180, 120), "Cool"), + ((128, 128, 128), "Neutral"), + ((0, 0, 0), "Neutral"), + ((255, 255, 255), "Neutral"), + ((130, 128, 128), "Neutral"), # regression: near-gray was previously "Warm" + ((0, 255, 0), "Neutral"), + ((255, 0, 255), "Neutral"), + ], + ) + def test_get_temperature(self, rgb: tuple[int, int, int], expected: str) -> None: + assert get_temperature(rgb) == expected + + def test_is_neutral(self) -> None: + assert is_neutral((128, 128, 128)) is True + assert is_neutral((140, 125, 130)) is True + assert is_neutral((255, 0, 0)) is False + assert is_neutral((140, 125, 130), tolerance=10) is False + with pytest.raises(ValueError): + is_neutral((128, 128, 128), tolerance=-1) + + def test_brightness(self) -> None: + assert brightness((255, 255, 255)) == pytest.approx(1.0) + assert brightness((0, 0, 0)) == 0.0 + assert brightness((255, 0, 0)) == pytest.approx(0.299) + assert brightness((0, 255, 0)) == pytest.approx(0.587) + assert brightness((0, 0, 255)) == pytest.approx(0.114) + + def test_is_pastel(self) -> None: + assert is_pastel((255, 200, 200)) is True + assert is_pastel((174, 198, 207)) is True # pastel blue + assert is_pastel((119, 221, 119)) is True # pastel green (channel <= 127) + assert is_pastel((230, 230, 250)) is True # lavender + assert is_pastel((253, 253, 150)) is True # pastel yellow + # Non-pastels (including regressions for white and light gray) + assert is_pastel((255, 255, 255)) is False + assert is_pastel((220, 220, 220)) is False + assert is_pastel((255, 0, 0)) is False + assert is_pastel((0, 255, 255)) is False + assert is_pastel((50, 50, 50)) is False + + def test_is_muted(self) -> None: + assert is_muted((100, 100, 100)) is True + assert is_muted((112, 128, 144)) is True # slate gray + assert is_muted((143, 151, 121)) is True # sage green + assert is_muted((180, 130, 140)) is True # dusty rose + # Non-muted + assert is_muted((0, 0, 0)) is False + assert is_muted((255, 255, 255)) is False + assert is_muted((255, 200, 200)) is False # pastel + assert is_muted((255, 0, 0)) is False + + def test_is_vibrant_and_get_vibrancy(self) -> None: + assert is_vibrant((0, 255, 0)) is True + assert is_vibrant((255, 80, 0)) is True + assert is_vibrant((128, 128, 128)) is False + assert is_vibrant((80, 0, 0)) is False + + assert get_vibrancy((0, 0, 0)) == 0.0 + assert get_vibrancy((255, 255, 255)) == 0.0 + assert get_vibrancy((255, 0, 0)) == 1.0 + + +class TestLuminanceAndWcag: + def test_rgb_to_linear_wcag_spec(self) -> None: + # Low-value linear branch s <= 0.04045 (c = 10 -> s = 10/255 = 0.039215686) + low = rgb_to_linear((10, 0, 255)) + assert low[0] == pytest.approx((10.0 / 255.0) / 12.92, rel=1e-12) + assert low[1] == 0.0 + assert low[2] == 1.0 + + # Gamma branch s > 0.04045 (c = 128) + mid = rgb_to_linear((128, 128, 128)) + expected_mid = ((128.0 / 255.0 + 0.055) / 1.055) ** 2.4 + assert mid == pytest.approx([expected_mid, expected_mid, expected_mid], rel=1e-12) + + def test_luminance_and_contrast_wcag(self) -> None: + assert get_luminance((0, 0, 0)) == 0.0 + assert get_luminance((255, 255, 255)) == pytest.approx(1.0) + assert get_luminance((255, 0, 0)) == pytest.approx(0.2126) + assert get_luminance((0, 255, 0)) == pytest.approx(0.7152) + assert get_luminance((0, 0, 255)) == pytest.approx(0.0722) + + assert color_contrast((0, 0, 0), (255, 255, 255)) == pytest.approx(21.0) + assert color_contrast((255, 255, 255), (0, 0, 0)) == pytest.approx(21.0) + assert color_contrast((100, 150, 200), (100, 150, 200)) == pytest.approx(1.0) + # WCAG 2.1 exact contrast between pure green and mid-gray (#808080) + assert color_contrast((0, 255, 0), (128, 128, 128)) == pytest.approx(2.8782, rel=1e-3) + + def test_check_wcag_contrast(self) -> None: + high = check_wcag_contrast((0, 0, 0), (255, 255, 255)) + assert high == { + "contrast_ratio": 21.0, + "aa_normal": True, + "aa_large": True, + "aaa_normal": True, + "aaa_large": True, + "ui_components": True, + } + low = check_wcag_contrast((200, 200, 200), (255, 255, 255)) + assert low["aa_normal"] is False + assert low["aa_large"] is False + assert low["ui_components"] is False + + @pytest.mark.parametrize( + ("bg", "expected"), + [ + ((0, 0, 0), "light"), # regression: previously returned "dark" + ((30, 30, 30), "light"), # regression: previously returned "dark" + ((0, 0, 255), "light"), + ((80, 20, 120), "light"), + ((255, 255, 255), "dark"), + ((255, 255, 0), "dark"), # regression: previously returned "light" + ((0, 255, 255), "dark"), # regression: previously returned "light" + ((0, 255, 0), "dark"), # regression: previously returned "light" + ((180, 180, 180), "dark"), # regression: previously returned "light" + ], + ) + def test_get_text_color_from_background(self, bg: tuple[int, int, int], expected: str) -> None: + assert get_text_color_from_background(bg) == expected + + def test_text_color_always_maximizes_wcag_contrast(self) -> None: + steps = [0, 32, 64, 96, 128, 160, 192, 224, 255] + for r in steps: + for g in (0, 85, 170, 255): + for b in (0, 85, 170, 255): + choice = get_text_color_from_background((r, g, b)) + chosen_rgb = (255, 255, 255) if choice == "light" else (0, 0, 0) + other_rgb = (0, 0, 0) if choice == "light" else (255, 255, 255) + assert color_contrast((r, g, b), chosen_rgb) >= color_contrast( + (r, g, b), other_rgb + ) + + def test_check_color_quality(self) -> None: + navy = check_color_quality((0, 0, 128)) + assert navy["is_good_quality"] is True + assert navy["best_background"] == "white" + assert navy["passes_aaa_on_white"] is True + + # Mid-gray lacks 7:1 contrast against both black (5.32) and white (3.95) + mid_gray = check_color_quality((128, 128, 128)) + assert mid_gray["is_good_quality"] is False + assert mid_gray["passes_aa_on_black"] is True + assert mid_gray["passes_aa_on_white"] is False + + # Against a specific background, defaults to WCAG AA (4.5:1) + on_white = check_color_quality((180, 180, 180), background=(255, 255, 255)) + assert on_white["is_good_quality"] is False + assert on_white["contrast_with_background"] < 4.5 + + on_black = check_color_quality((180, 180, 180), background=(0, 0, 0)) + assert on_black["is_good_quality"] is True + assert on_black["contrast_with_background"] >= 4.5 + + with pytest.raises(ValueError): + check_color_quality((0, 0, 0), min_contrast=0.5) + + +class TestColorBlindnessAndDeltaE: + @pytest.mark.parametrize( + "mode", ["protanopia", "deuteranopia", "tritanopia", "achromatopsia"] + ) + def test_neutral_grays_are_invariant(self, mode: str) -> None: + for v in (0, 1, 10, 29, 64, 128, 200, 255): + for intensity in (0.0, 0.3, 0.5, 1.0): + assert simulate_color_blindness((v, v, v), mode, intensity) == (v, v, v) + + def test_color_blindness_behavior_and_validation(self) -> None: + sample = (220, 50, 80) + assert simulate_color_blindness(sample, "PROTANOPIA", 0.0) == sample + + achro = simulate_color_blindness(sample, "achromatopsia", 1.0) + assert achro[0] == achro[1] == achro[2] + + with pytest.raises(ValueError): + simulate_color_blindness(sample, "unknown") + with pytest.raises(ValueError): + simulate_color_blindness(sample, "protanopia", 1.5) + with pytest.raises(TypeError): + simulate_color_blindness(sample, "protanopia", True) # type: ignore[arg-type] + + @pytest.mark.parametrize( + ("lab1", "lab2", "expected"), + [ + # Official Sharma, Wu & Dalal (2005) CIEDE2000 reference test vectors + ((50.0000, 2.6772, -79.7751), (50.0000, 0.0000, -82.7485), 2.0425), + ((50.0000, 3.1571, -77.2803), (50.0000, 0.0000, -82.7485), 2.8615), + ((50.0000, -1.3802, -84.2814), (50.0000, 0.0000, -82.7485), 1.0000), + ((50.0000, 0.0000, 0.0000), (50.0000, -1.0000, 2.0000), 2.3669), + ((50.0000, 2.5000, 0.0000), (73.0000, 25.0000, -18.0000), 27.1492), + ((60.2574, -34.0099, 36.2677), (60.4626, -34.1751, 39.4387), 1.2644), + ((2.0776, 0.0795, -1.1350), (0.9033, -0.0636, -0.5514), 0.9082), + ], + ) + def test_ciede2000_sharma_reference_vectors( + self, + lab1: tuple[float, float, float], + lab2: tuple[float, float, float], + expected: float, + ) -> None: + assert _ciede2000(lab1, lab2) == pytest.approx(expected, abs=1e-4) + + def test_delta_e_public_api(self) -> None: + assert delta_e((120, 80, 200), (120, 80, 200)) == 0.0 + assert delta_e((120, 80, 200), (120, 80, 200), method="cie76") == 0.0 + # Symmetry + d1 = delta_e((255, 0, 0), (0, 128, 255)) + d2 = delta_e((0, 128, 255), (255, 0, 0)) + assert d1 == pytest.approx(d2) + # Subtle difference << opposite colors + assert delta_e((100, 100, 100), (102, 100, 100)) < 2.0 + assert delta_e((0, 0, 0), (255, 255, 255)) == pytest.approx(100.0, abs=0.1) + assert delta_e((0, 0, 0), (255, 255, 255), method="cie76") == pytest.approx(100.0, abs=1e-3) + + with pytest.raises(ValueError): + delta_e((0, 0, 0), (255, 255, 255), method="invalid") + if __name__ == "__main__": - run_tests() \ No newline at end of file + raise SystemExit(pytest.main([__file__])) diff --git a/Tests/test_colors.py b/Tests/test_colors.py index 8d428ac..ea199f2 100644 --- a/Tests/test_colors.py +++ b/Tests/test_colors.py @@ -1,50 +1,158 @@ +"""Comprehensive unit tests for hued.colors.""" + +from __future__ import annotations + +import re + +import pytest + from hued.colors import ColorManager -# Initialize the ColorManager -color_manager = ColorManager() - -def test_hex_to_rgb(): - print("Testing HEX to RGB...") - hex_value = "#FF5733" # A sample hex color - expected_rgb = (255, 87, 51) - result = color_manager.hex_to_rgb(hex_value) - assert result == expected_rgb, f"Expected {expected_rgb}, but got {result}" - print(f"HEX {hex_value} -> RGB: {result}") - -def test_rgb_to_hex(): - print("Testing RGB to HEX...") - r, g, b = 0, 128, 0 # Green - expected_hex = "#008000" - result = color_manager.rgb_to_hex(r, g, b) - assert result == expected_hex, f"Expected {expected_hex}, but got {result}" - print(f"RGB({r}, {g}, {b}) -> HEX: {result}") - -def test_closest_color_name(): - print("Testing Closest Color Name...") - hex_value = "#FF0000" # Red - expected_name = "Red" - result = color_manager.closest_color_name(hex_value) - assert result == expected_name, f"Expected {expected_name}, but got {result}" - print(f"Closest color to {hex_value} is {result}") - -def test_get_color_by_name(): - print("Testing Get Color by Name...") - color_name = "Blue" - expected_result = { - 'Name': "Blue", - 'Hex': "#0000FF", - 'RGB': (0, 0, 255) - } - result = color_manager.get_color_by_name(color_name) - assert result == expected_result, f"Expected {expected_result}, but got {result}" - print(f"{color_name} -> {result}") - -def run_tests(): - test_hex_to_rgb() - test_rgb_to_hex() - test_closest_color_name() - test_get_color_by_name() - print("All tests passed!") +# All 148 standard W3C CSS Color Level 4 named colors. +CSS_NAMED_COLORS = [ + "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque", + "black", "blanchedalmond", "blue", "blueviolet", "brown", "burlywood", "cadetblue", + "chartreuse", "chocolate", "coral", "cornflowerblue", "cornsilk", "crimson", "cyan", + "darkblue", "darkcyan", "darkgoldenrod", "darkgray", "darkgreen", "darkgrey", + "darkkhaki", "darkmagenta", "darkolivegreen", "darkorange", "darkorchid", "darkred", + "darksalmon", "darkseagreen", "darkslateblue", "darkslategray", "darkslategrey", + "darkturquoise", "darkviolet", "deeppink", "deepskyblue", "dimgray", "dimgrey", + "dodgerblue", "firebrick", "floralwhite", "forestgreen", "fuchsia", "gainsboro", + "ghostwhite", "gold", "goldenrod", "gray", "green", "greenyellow", "grey", + "honeydew", "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", + "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", "lightcyan", + "lightgoldenrodyellow", "lightgray", "lightgreen", "lightgrey", "lightpink", + "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", "lightslategrey", + "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", "maroon", + "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen", + "mediumslateblue", "mediumspringgreen", "mediumturquoise", "mediumvioletred", + "midnightblue", "mintcream", "mistyrose", "moccasin", "navajowhite", "navy", + "oldlace", "olive", "olivedrab", "orange", "orangered", "orchid", "palegoldenrod", + "palegreen", "paleturquoise", "palevioletred", "papayawhip", "peachpuff", "peru", + "pink", "plum", "powderblue", "purple", "rebeccapurple", "red", "rosybrown", + "royalblue", "saddlebrown", "salmon", "sandybrown", "seagreen", "seashell", "sienna", + "silver", "skyblue", "slateblue", "slategray", "slategrey", "snow", "springgreen", + "steelblue", "tan", "teal", "thistle", "tomato", "turquoise", "violet", "wheat", + "white", "whitesmoke", "yellow", "yellowgreen", +] + + +class TestCatalogIntegrity: + def test_all_entries_clean_unique_and_uppercase(self) -> None: + cm = ColorManager() + assert len(cm.color_list) >= 1300 + + seen_names: set[str] = set() + hex_pattern = re.compile(r"^#[0-9A-F]{6}$") + + for entry in cm.color_list: + name = entry["name"] + hx = entry["hex"] + assert name == name.strip() and len(name) > 0 + assert "[" not in name and "]" not in name + assert "citation" not in name.lower() + assert "vomit" not in name.lower() + assert hex_pattern.match(hx), f"Non-canonical hex {hx!r} for {name!r}" + + lower = name.lower() + assert lower not in seen_names, f"Duplicate color name: {name!r}" + seen_names.add(lower) + + def test_all_148_css_named_colors_resolve(self) -> None: + cm = ColorManager() + missing = [name for name in CSS_NAMED_COLORS if cm.get_color_by_name(name) is None] + assert missing == [] + + +class TestColorManagerMethods: + def test_hex_rgb_helpers(self) -> None: + cm = ColorManager() + assert cm.hex_to_rgb("#FF5733") == (255, 87, 51) + assert cm.hex_to_rgb("#F0A") == (255, 0, 170) + assert cm.rgb_to_hex(0, 128, 0) == "#008000" + + def test_get_color_by_name_and_casing_preservation(self) -> None: + cm = ColorManager() + assert cm.get_color_by_name("Blue") == { + "Name": "Blue", + "Hex": "#0000FF", + "RGB": (0, 0, 255), + } + assert cm.get_color_by_name(" green ") == { + "Name": "Green", + "Hex": "#008000", + "RGB": (0, 128, 0), + } + # Regression: .title() previously corrupted acronyms and apostrophes + raf = cm.get_color_by_name("air force blue (raf)") + assert raf is not None and raf["Name"] == "Air Force blue (RAF)" + bdazzled = cm.get_color_by_name("b'dazzled blue") + assert bdazzled is not None and bdazzled["Name"] == "B'dazzled blue" + # Cleaned citation artifacts + assert cm.get_color_by_name("Cinnamon") == { + "Name": "Cinnamon", + "Hex": "#D2691E", + "RGB": (210, 105, 30), + } + assert cm.get_color_by_name("nonexistent color xyz") is None + assert cm.get_color_by_name(" ") is None + + def test_closest_color_name_modes(self) -> None: + cm = ColorManager() + assert cm.closest_color_name("#FF0000") == "Red" + assert cm.closest_color_name("#F00") == "Red" + assert cm.closest_color_name("#FF0000", space="lab") == "Red" + assert cm.closest_color_name("#FF0000", space="cie2000") == "Red" + + # Slightly perturbed color resolves consistently in all spaces + assert isinstance(cm.closest_color_name("#FE0502", space="rgb"), str) + assert isinstance(cm.closest_color_name("#FE0502", space="lab"), str) + assert isinstance(cm.closest_color_name("#FE0502", space="cie2000"), str) + + with pytest.raises(ValueError): + cm.closest_color_name("#FF0000", space="unknown") + + def test_get_color_by_hex_search_and_random(self) -> None: + cm = ColorManager() + assert cm.get_color_by_hex("#ff0000") == { + "Name": "Red", + "Hex": "#FF0000", + "RGB": (255, 0, 0), + } + assert cm.get_color_by_hex("#123456") is None + + matches = cm.search_colors("cerulean") + assert len(matches) >= 5 + assert all("cerulean" in m["Name"].lower() for m in matches) + assert cm.search_colors("") == [] + + rand = cm.get_random_color() + assert set(rand.keys()) == {"Name", "Hex", "RGB"} + + def test_add_remove_and_instance_isolation(self) -> None: + cm1 = ColorManager() + cm2 = ColorManager() + + added = cm1.add_color("Infinitode Violet", "#5d17eb") + assert added == { + "Name": "Infinitode Violet", + "Hex": "#5D17EB", + "RGB": (93, 23, 235), + } + assert cm1.get_color_by_name("infinitode violet") == added + assert cm2.get_color_by_name("infinitode violet") is None + + # Updating an existing custom color overwrites in place + updated = cm1.add_color("infinitode violet", "#6020F0") + assert updated["Hex"] == "#6020F0" + + assert cm1.remove_color("INFINITODE VIOLET") is True + assert cm1.remove_color("INFINITODE VIOLET") is False + assert cm1.get_color_by_name("infinitode violet") is None + + with pytest.raises(ValueError): + cm1.add_color(" ", "#FFFFFF") + if __name__ == "__main__": - run_tests() \ No newline at end of file + raise SystemExit(pytest.main([__file__])) diff --git a/Tests/test_conversions.py b/Tests/test_conversions.py index 40f0d21..fabc0a8 100644 --- a/Tests/test_conversions.py +++ b/Tests/test_conversions.py @@ -1,98 +1,373 @@ -from hued.conversions import * - -def test_rgb_to_hex(): - print("Testing RGB to HEX...") - r, g, b = 255, 0, 0 # Red - expected_hex = "#FF0000" - result = rgb_to_hex(r, g, b) - assert result == expected_hex, f"Expected {expected_hex}, but got {result}" - print(f"RGB({r}, {g}, {b}) -> HEX: {result}") - -def test_hex_to_rgb(): - print("Testing HEX to RGB...") - hex_value = "#00FF00" # Green - expected_rgb = (0, 255, 0) - result = hex_to_rgb(hex_value) - assert result == expected_rgb, f"Expected {expected_rgb}, but got {result}" - print(f"HEX {hex_value} -> RGB: {result}") - -def test_rgb_to_hsl(): - print("Testing RGB to HSL...") - r, g, b = 0, 0, 255 # Blue - expected_hsl = (240, 1, 0.5) - result = rgb_to_hsl(r, g, b) - assert result == expected_hsl, f"Expected {expected_hsl}, but got {result}" - print(f"RGB({r}, {g}, {b}) -> HSL: {result}") - -def test_hsl_to_rgb(): - print("Testing HSL to RGB...") - h, s, l = 240, 1, 0.5 # Blue in HSL - expected_rgb = (0, 0, 255) - result = hsl_to_rgb(h, s, l) - assert result == expected_rgb, f"Expected {expected_rgb}, but got {result}" - print(f"HSL({h}, {s}, {l}) -> RGB: {result}") - -def test_rgb_to_hsv(): - print("Testing RGB to HSV...") - r, g, b = 255, 255, 0 # Yellow - expected_hsv = (60, 1, 1) - result = rgb_to_hsv(r, g, b) - assert result == expected_hsv, f"Expected {expected_hsv}, but got {result}" - print(f"RGB({r}, {g}, {b}) -> HSV: {result}") - -def test_hsv_to_rgb(): - print("Testing HSV to RGB...") - h, s, v = 60, 1, 1 # Yellow in HSV - expected_rgb = (255, 255, 0) - result = hsv_to_rgb(h, s, v) - assert result == expected_rgb, f"Expected {expected_rgb}, but got {result}" - print(f"HSV({h}, {s}, {v}) -> RGB: {result}") - -def test_rgb_to_cmyk(): - print("Testing RGB to CMYK...") - r, g, b = 0, 255, 255 # Cyan - expected_cmyk = (1.0, 0.0, 0.0, 0.0) - result = rgb_to_cmyk(r, g, b) - assert result == expected_cmyk, f"Expected {expected_cmyk}, but got {result}" - print(f"RGB({r}, {g}, {b}) -> CMYK: {result}") - -def test_cmyk_to_rgb(): - print("Testing CMYK to RGB...") - c, m, y, k = 0, 1, 1, 0 # Red in CMYK - expected_rgb = (255, 0, 0) - result = cmyk_to_rgb(c, m, y, k) - assert result == expected_rgb, f"Expected {expected_rgb}, but got {result}" - print(f"CMYK({c}, {m}, {y}, {k}) -> RGB: {result}") - -def test_hsl_to_hex(): - hsl = (0, 1, 0.5) - result = hsl_to_hex(hsl) - assert result == "#FF0000", f"Expected '#FF0000', but got {result}" - print(f"HSL converted to HEX successfully: {result}") - -def test_blend_colors(): - print("Testing blend_colors...") - color1 = (255, 0, 0) # Red - color2 = (0, 0, 255) # Blue - ratio = 0.5 # Equal blend - expected_color = (127, 0, 127) # Purple (midpoint blend of red and blue) - result = blend_colors(color1, color2, ratio) - assert result == expected_color, f"Expected {expected_color}, but got {result}" - print(f"blend_colors({color1}, {color2}, {ratio}) -> RGB: {result}") - -def run_tests(): - test_rgb_to_hex() - test_hex_to_rgb() - test_rgb_to_hsl() - test_hsl_to_rgb() - test_rgb_to_hsv() - test_hsv_to_rgb() - test_rgb_to_cmyk() - test_cmyk_to_rgb() - test_hsl_to_hex() - test_blend_colors() - - print("All tests passed!") +"""Comprehensive unit tests for hued.conversions.""" + +from __future__ import annotations + +import math + +import pytest + +import hued +from hued.analysis import rgb_to_linear +from hued.conversions import ( + adjust_lightness, + adjust_saturation, + blend_colors, + cmyk_to_hex, + cmyk_to_hsl, + cmyk_to_hsv, + cmyk_to_lab, + cmyk_to_rgb, + cmyk_to_xyz, + hex_to_cmyk, + hex_to_hsl, + hex_to_hsv, + hex_to_lab, + hex_to_rgb, + hex_to_xyz, + hsl_to_cmyk, + hsl_to_hex, + hsl_to_hsv, + hsl_to_lab, + hsl_to_rgb, + hsl_to_xyz, + hsv_to_cmyk, + hsv_to_hex, + hsv_to_hsl, + hsv_to_lab, + hsv_to_rgb, + hsv_to_xyz, + invert_color, + lab_to_cmyk, + lab_to_hex, + lab_to_hsl, + lab_to_hsv, + lab_to_rgb, + lab_to_xyz, + linear_to_rgb, + rgb_to_cmyk, + rgb_to_hex, + rgb_to_hsl, + rgb_to_hsv, + rgb_to_lab, + rgb_to_xyz, + to_grayscale, + xyz_to_cmyk, + xyz_to_hex, + xyz_to_hsl, + xyz_to_hsv, + xyz_to_lab, + xyz_to_rgb, +) + + +class TestHexRgb: + @pytest.mark.parametrize( + ("rgb", "expected"), + [ + ((255, 0, 0), "#FF0000"), + ((0, 255, 0), "#00FF00"), + ((0, 0, 255), "#0000FF"), + ((0, 0, 0), "#000000"), + ((255, 255, 255), "#FFFFFF"), + ((15, 16, 171), "#0F10AB"), + ], + ) + def test_rgb_to_hex_valid(self, rgb: tuple[int, int, int], expected: str) -> None: + assert rgb_to_hex(*rgb) == expected + + @pytest.mark.parametrize("bad", [(-1, 0, 0), (256, 0, 0), (0, -5, 0), (0, 0, 999)]) + def test_rgb_to_hex_out_of_range(self, bad: tuple[int, int, int]) -> None: + with pytest.raises(ValueError): + rgb_to_hex(*bad) + + @pytest.mark.parametrize( + "bad", + [(12.5, 0, 0), (True, 0, 0), (0, False, 0), ("255", 0, 0)], # type: ignore[list-item] + ) + def test_rgb_to_hex_invalid_type(self, bad: tuple[object, object, object]) -> None: + with pytest.raises(TypeError): + rgb_to_hex(*bad) # type: ignore[arg-type] + + @pytest.mark.parametrize( + ("hex_str", "expected"), + [ + ("#00FF00", (0, 255, 0)), + ("FF0000", (255, 0, 0)), + ("#ff5733", (255, 87, 51)), + (" #0f10ab ", (15, 16, 171)), + ("#FFF", (255, 255, 255)), + ("#000", (0, 0, 0)), + ("f0a", (255, 0, 170)), + ], + ) + def test_hex_to_rgb_valid(self, hex_str: str, expected: tuple[int, int, int]) -> None: + assert hex_to_rgb(hex_str) == expected + + @pytest.mark.parametrize( + "bad_hex", + [ + "", + "#", + "##FF0000", + "#12", + "#1234", + "#12345", + "#FF000080", + "#FF0000EXTRA", + "#GGGGGG", + "#+1+2+3", + "#-10000", + "#12 345", + ], + ) + def test_hex_to_rgb_rejects_malformed(self, bad_hex: str) -> None: + with pytest.raises(ValueError): + hex_to_rgb(bad_hex) + + def test_hex_to_rgb_rejects_non_string(self) -> None: + with pytest.raises(TypeError): + hex_to_rgb(0xFF0000) # type: ignore[arg-type] + + +class TestHslHsvCmyk: + @pytest.mark.parametrize( + ("rgb", "hsl"), + [ + ((255, 0, 0), (0.0, 1.0, 0.5)), + ((255, 255, 0), (60.0, 1.0, 0.5)), + ((0, 255, 0), (120.0, 1.0, 0.5)), + ((0, 255, 255), (180.0, 1.0, 0.5)), + ((0, 0, 255), (240.0, 1.0, 0.5)), + ((255, 0, 255), (300.0, 1.0, 0.5)), + ((0, 0, 0), (0.0, 0.0, 0.0)), + ((255, 255, 255), (0.0, 0.0, 1.0)), + ((128, 128, 128), (0.0, 0.0, 0.5)), + ], + ) + def test_rgb_hsl_roundtrip_primaries( + self, rgb: tuple[int, int, int], hsl: tuple[float, float, float] + ) -> None: + assert rgb_to_hsl(*rgb) == hsl + if rgb != (128, 128, 128): + assert hsl_to_rgb(*hsl) == rgb + + def test_hue_never_rounds_to_360(self) -> None: + # Float RGB where raw hue is 359.9976...; rounding must wrap to 0.0, never 360.0. + h_hsl, _, _ = rgb_to_hsl(255, 0, 0.01) # type: ignore[arg-type] + h_hsv, _, _ = rgb_to_hsv(255, 0, 0.01) # type: ignore[arg-type] + assert h_hsl == 0.0 + assert h_hsv == 0.0 + assert hsl_to_hex((h_hsl, 1.0, 0.5)) == "#FF0000" + + @pytest.mark.parametrize( + "bad_hsl", + [(360, 1, 0.5), (-1, 1, 0.5), (120, 1.1, 0.5), (120, -0.1, 0.5), (120, 0.5, 1.2), (math.nan, 0.5, 0.5)], + ) + def test_hsl_validation(self, bad_hsl: tuple[float, float, float]) -> None: + with pytest.raises(ValueError): + hsl_to_rgb(*bad_hsl) + with pytest.raises(ValueError): + hsl_to_hex(bad_hsl) + with pytest.raises(ValueError): + hsl_to_xyz(bad_hsl) + + @pytest.mark.parametrize( + ("rgb", "hsv"), + [ + ((255, 0, 0), (0.0, 1.0, 1.0)), + ((255, 255, 0), (60.0, 1.0, 1.0)), + ((0, 255, 0), (120.0, 1.0, 1.0)), + ((0, 255, 255), (180.0, 1.0, 1.0)), + ((0, 0, 255), (240.0, 1.0, 1.0)), + ((255, 0, 255), (300.0, 1.0, 1.0)), + ((0, 0, 0), (0.0, 0.0, 0.0)), + ((255, 255, 255), (0.0, 0.0, 1.0)), + ], + ) + def test_rgb_hsv_roundtrip_primaries( + self, rgb: tuple[int, int, int], hsv: tuple[float, float, float] + ) -> None: + assert rgb_to_hsv(*rgb) == hsv + assert hsv_to_rgb(*hsv) == rgb + + @pytest.mark.parametrize( + "bad_hsv", + [(360, 1, 1), (-5, 1, 1), (0, 2, 1), (0, 1, -0.1), (math.inf, 0.5, 0.5)], + ) + def test_hsv_validation(self, bad_hsv: tuple[float, float, float]) -> None: + with pytest.raises(ValueError): + hsv_to_rgb(*bad_hsv) + with pytest.raises(ValueError): + hsv_to_hex(bad_hsv) + with pytest.raises(ValueError): + hsv_to_xyz(bad_hsv) + + def test_direct_hsl_hsv_preserves_hue(self) -> None: + # Very light pastel that would suffer heavy hue quantization via 8-bit RGB + hsv = hsl_to_hsv((213.45, 0.3, 0.96)) + assert hsv[0] == 213.45 + hsl_back = hsv_to_hsl(hsv) + assert hsl_back[0] == 213.45 + # Achromatic edge cases + assert hsl_to_hsv((180, 0.0, 0.5)) == (0.0, 0.0, 0.5) + assert hsl_to_hsv((180, 1.0, 0.0)) == (0.0, 0.0, 0.0) + assert hsv_to_hsl((180, 0.0, 1.0)) == (0.0, 0.0, 1.0) + assert hsv_to_hsl((180, 1.0, 0.0)) == (0.0, 0.0, 0.0) + + def test_cmyk_conversions_and_validation(self) -> None: + assert rgb_to_cmyk(0, 255, 255) == (1.0, 0.0, 0.0, 0.0) + assert rgb_to_cmyk(0, 0, 0) == (0.0, 0.0, 0.0, 1.0) + assert rgb_to_cmyk(255, 255, 255) == (0.0, 0.0, 0.0, 0.0) + assert cmyk_to_rgb(0, 1, 1, 0) == (255, 0, 0) + assert cmyk_to_rgb(0, 0, 0, 1) == (0, 0, 0) + with pytest.raises(ValueError): + cmyk_to_rgb(1.2, 0, 0, 0) + with pytest.raises(ValueError): + cmyk_to_xyz((0, -0.1, 0, 0)) + + +class TestXyzAndLab: + @pytest.mark.parametrize( + "rgb", + [ + (255, 0, 0), # previously crashed with complex TypeError + (0, 255, 0), # previously crashed with complex TypeError + (0, 0, 255), + (0, 255, 255), # previously drifted to (1, 255, 255) + (255, 255, 0), + (255, 0, 255), + (0, 0, 0), + (255, 255, 255), + (5, 10, 15), # exercises low-value sRGB linear segment (s <= 0.04045) + (128, 64, 192), + ], + ) + def test_rgb_xyz_lab_exact_roundtrip(self, rgb: tuple[int, int, int]) -> None: + xyz = rgb_to_xyz(*rgb) + assert xyz_to_rgb(*xyz) == rgb + + lab = rgb_to_lab(*rgb) + assert lab_to_rgb(*lab) == rgb + + def test_xyz_lab_grid_roundtrip(self) -> None: + values = [0, 1, 5, 10, 11, 32, 64, 128, 192, 240, 255] + for r in values: + for g in (0, 10, 128, 255): + for b in (0, 10, 128, 255): + assert xyz_to_rgb(*rgb_to_xyz(r, g, b)) == (r, g, b) + assert lab_to_rgb(*rgb_to_lab(r, g, b)) == (r, g, b) + + def test_d65_white_and_black_reference(self) -> None: + wx, wy, wz = rgb_to_xyz(255, 255, 255) + assert (wx, wy, wz) == pytest.approx((0.95047, 1.0, 1.08883), abs=1e-5) + assert rgb_to_xyz(0, 0, 0) == (0.0, 0.0, 0.0) + + wl, wa, wb = rgb_to_lab(255, 255, 255) + assert (wl, wa, wb) == pytest.approx((100.0, 0.0, 0.0), abs=1e-4) + assert rgb_to_lab(0, 0, 0) == pytest.approx((0.0, 0.0, 0.0), abs=1e-6) + + assert lab_to_xyz((100.0, 0.0, 0.0)) == pytest.approx((0.95047, 1.0, 1.08883), abs=1e-5) + assert xyz_to_lab((0.95047, 1.0, 1.08883)) == pytest.approx((100.0, 0.0, 0.0), abs=1e-5) + + def test_xyz_lab_validation(self) -> None: + with pytest.raises(ValueError): + rgb_to_xyz(-1, 0, 0) + with pytest.raises(ValueError): + xyz_to_rgb(-0.1, 0.0, 0.0) + with pytest.raises(ValueError): + lab_to_rgb(101.0, 0.0, 0.0) + with pytest.raises(ValueError): + lab_to_rgb(-1.0, 0.0, 0.0) + + def test_linear_rgb_roundtrip_all_256(self) -> None: + for v in range(256): + lin = rgb_to_linear((v, v, v)) + assert linear_to_rgb(lin) == (v, v, v) + with pytest.raises(ValueError): + linear_to_rgb((1.5, 0.0, 0.0)) + + +class TestCrossSpaceMatrix: + def test_all_cross_conversions_for_red(self) -> None: + assert hsl_to_hex((0, 1, 0.5)) == "#FF0000" + assert hsv_to_hex((0, 1, 1)) == "#FF0000" + assert cmyk_to_hex((0, 1, 1, 0)) == "#FF0000" + + assert hex_to_hsl("#FF0000") == (0.0, 1.0, 0.5) + assert hex_to_hsv("#FF0000") == (0.0, 1.0, 1.0) + assert hex_to_cmyk("#FF0000") == (0.0, 1.0, 1.0, 0.0) + assert hsl_to_cmyk((0, 1, 0.5)) == (0.0, 1.0, 1.0, 0.0) + assert hsv_to_cmyk((0, 1, 1)) == (0.0, 1.0, 1.0, 0.0) + assert cmyk_to_hsl((0, 1, 1, 0)) == (0.0, 1.0, 0.5) + assert cmyk_to_hsv((0, 1, 1, 0)) == (0.0, 1.0, 1.0) + + xyz = hex_to_xyz("#FF0000") + assert xyz_to_hex(xyz) == "#FF0000" + assert xyz_to_hsl(xyz) == (0.0, 1.0, 0.5) + assert xyz_to_hsv(xyz) == (0.0, 1.0, 1.0) + assert xyz_to_cmyk(xyz) == (0.0, 1.0, 1.0, 0.0) + assert hsl_to_xyz((0, 1, 0.5)) == pytest.approx(xyz) + assert hsv_to_xyz((0, 1, 1)) == pytest.approx(xyz) + assert cmyk_to_xyz((0, 1, 1, 0)) == pytest.approx(xyz) + + lab = hex_to_lab("#FF0000") + assert lab_to_hex(lab) == "#FF0000" + assert lab_to_hsl(lab) == (0.0, 1.0, 0.5) + assert lab_to_hsv(lab) == (0.0, 1.0, 1.0) + assert lab_to_cmyk(lab) == (0.0, 1.0, 1.0, 0.0) + assert hsl_to_lab((0, 1, 0.5)) == pytest.approx(lab) + assert hsv_to_lab((0, 1, 1)) == pytest.approx(lab) + assert cmyk_to_lab((0, 1, 1, 0)) == pytest.approx(lab) + + +class TestBlendingAndAdjustments: + def test_blend_colors_srgb_and_linear(self) -> None: + assert blend_colors((255, 0, 0), (0, 0, 255), 0.5) == (128, 0, 128) + assert blend_colors((255, 0, 0), (0, 0, 255), 0.0) == (255, 0, 0) + assert blend_colors((255, 0, 0), (0, 0, 255), 1.0) == (0, 0, 255) + + # Linear blending is brighter than naive sRGB blending for complementary primaries + lin_mix = blend_colors((255, 0, 0), (0, 255, 0), 0.5, linear=True) + assert lin_mix == (188, 188, 0) + + def test_blend_self_identity_all_values(self) -> None: + # Regression: int() truncation previously turned blend_colors((3,3,3),(3,3,3),0.3) -> (2,2,2) + for v in range(256): + for ratio in (0.0, 0.1, 0.3, 0.5, 0.7, 0.9, 1.0): + assert blend_colors((v, v, v), (v, v, v), ratio) == (v, v, v) + + def test_blend_validation(self) -> None: + with pytest.raises(ValueError): + blend_colors((255, 0, 0), (0, 0, 255), 1.5) + with pytest.raises(ValueError): + blend_colors((255, 0, 0), (0, 0, 255), -0.1) + with pytest.raises(ValueError): + blend_colors((300, 0, 0), (0, 0, 255), 0.5) + + def test_invert_grayscale_and_hsl_adjustments(self) -> None: + assert invert_color((255, 0, 128)) == (0, 255, 127) + assert invert_color((0, 0, 0)) == (255, 255, 255) + + gray = to_grayscale((255, 0, 0)) + assert gray[0] == gray[1] == gray[2] + assert to_grayscale((120, 120, 120)) == (120, 120, 120) + + lighter = adjust_lightness((255, 0, 0), 0.25) + assert lighter == (255, 128, 128) + assert adjust_lightness((255, 0, 0), 1.0) == (255, 255, 255) + assert adjust_lightness((255, 0, 0), -1.0) == (0, 0, 0) + + desaturated = adjust_saturation((255, 0, 0), -1.0) + assert desaturated == (128, 128, 128) + with pytest.raises(ValueError): + adjust_lightness((255, 0, 0), 1.5) + with pytest.raises(ValueError): + adjust_saturation((255, 0, 0), -1.5) + + def test_top_level_reexports(self) -> None: + assert hued.rgb_to_hex(255, 0, 0) == "#FF0000" + assert hued.hex_to_rgb("#F00") == (255, 0, 0) + if __name__ == "__main__": - run_tests() \ No newline at end of file + raise SystemExit(pytest.main([__file__])) diff --git a/Tests/test_palettes.py b/Tests/test_palettes.py index cc9b0ab..9b3d181 100644 --- a/Tests/test_palettes.py +++ b/Tests/test_palettes.py @@ -1,208 +1,202 @@ -import os +"""Comprehensive unit tests for hued.palettes and package metadata.""" + +from __future__ import annotations + +import csv +import json +from pathlib import Path + +import pytest + +import hued from hued.palettes import ColorPalette -def test_generate_complementary(): - print("Testing Complementary Palette...") - base_color = (255, 60, 52) # Red - palette = ColorPalette(base_color) - expected_complementary = [(255, 60, 52), (51, 247, 255)] # Adjust as needed - result = palette.generate_complementary() - assert result == expected_complementary, f"Expected {expected_complementary}, but got {result}" - print(f"Complementary Palette: {result}") - -def test_generate_analogous(): - print("Testing Analogous Palette...") - base_color = (255, 60, 52) # Red - palette = ColorPalette(base_color) - expected_analogous = [(255, 51, 145), (255, 60, 52), (255, 161, 51)] # Adjust as needed - result = palette.generate_analogous() - assert result == expected_analogous, f"Expected {expected_analogous}, but got {result}" - print(f"Analogous Palette: {result}") - -def test_generate_triadic(): - print("Testing Triadic Palette...") - base_color = (255, 60, 52) # Red - palette = ColorPalette(base_color) - expected_triadic = [(255, 60, 52), (51, 255, 59), (59, 51, 255)] # Adjust as needed - result = palette.generate_triadic() - assert result == expected_triadic, f"Expected {expected_triadic}, but got {result}" - print(f"Triadic Palette: {result}") - -def test_generate_monochromatic(): - print("Testing Monochromatic Palette...") - base_color = (255, 60, 52) # Red - palette = ColorPalette(base_color) - expected_monochromatic = [(51, 2, 0), (73, 3, 0), (95, 4, 0), (118, 5, 0), - (140, 5, 0), (162, 6, 0), (184, 7, 0), (206, 8, 0), - (228, 9, 0), (251, 10, 0), (255, 27, 18), (255, 48, 40), - (255, 70, 62), (255, 91, 84), (255, 112, 106), - (255, 134, 129), (255, 155, 151), (255, 176, 173), - (255, 197, 195), (255, 219, 217), (255, 240, 239), - (255, 255, 255)] # Adjust as needed - result = palette.generate_monochromatic() - assert result == expected_monochromatic, f"Expected {expected_monochromatic}, but got {result}" - print(f"Monochromatic Palette: {result}") - -def test_generate_tetradic(): - print("Testing Tetradic Palette...") - base_color = (255, 60, 52) # Example base color (Red) - palette = ColorPalette(base_color) - expected_tetradic = [ - (255, 60, 52), # Base color - (145, 255, 51), # Tetradic 1 - (51, 247, 255), # Tetradic 2 - (161, 51, 255) # Tetradic 3 - ] - result = palette.generate_tetradic() - assert result == expected_tetradic, f"Expected {expected_tetradic}, but got {result}" - print(f"Tetradic Palette: {result}") - -def test_generate_square(): - print("Testing Square Palette...") - base_color = (255, 60, 52) # Example base color (Red) - palette = ColorPalette(base_color) - expected_square = [ - (255, 60, 52), # Base color - (145, 255, 51), # Square 1 - (51, 247, 255), # Square 2 - (161, 51, 255) # Square 3 - ] - result = palette.generate_square() - assert result == expected_square, f"Expected {expected_square}, but got {result}" - print(f"Square Palette: {result}") - -def test_generate_split_complementary(): - print("Testing Split-Complementary Palette...") - base_color = (255, 60, 52) # Example base color (Red) - palette = ColorPalette(base_color) - expected_split_complementary = [ - (255, 60, 52), # Base color - (51, 255, 161), # Split Complementary 1 - (51, 145, 255) # Split Complementary 2 - ] - result = palette.generate_split_complementary() - assert result == expected_split_complementary, f"Expected {expected_split_complementary}, but got {result}" - print(f"Split-Complementary Palette: {result}") - -def test_palette_to_hex(): - print("Testing Palette to HEX conversion...") - base_color = (255, 60, 52) # Red - palette = ColorPalette(base_color) - palette.generate_monochromatic() # Generate to test conversion - expected_hex = ['#330200', '#490300', '#5F0400', '#760500', - '#8C0500', '#A20600', '#B80700', '#CE0800', - '#E40900', '#FB0A00', '#FF1B12', '#FF3028', - '#FF463E', '#FF5B54', '#FF706A', '#FF8681', - '#FF9B97', '#FFB0AD', '#FFC5C3', '#FFDBD9', - '#FFF0EF', '#FFFFFF'] # Adjust as needed - result = palette.palette_to_hex() - assert result == expected_hex, f"Expected {expected_hex}, but got {result}" - print(f"Palette in HEX: {result}") - -def test_generate_random_palette(): - print("Testing Random Palette Generation...") - palette = ColorPalette((0, 0, 0)) # Base color not used in random generation - result = palette.generate_random_palette() - assert isinstance(result, dict), "Expected a dictionary for the random palette." - print("Random Palette:", result) - -def test_generate_random_color(): - print("Testing Random Color Generation...") - palette = ColorPalette((0, 0, 0)) - result = palette.generate_random_color() - assert isinstance(result, dict), "Expected a dictionary for the random color." - print("Random Color:", result) - -def test_generate_random_hex_colors(): - print("Testing Random HEX Colors Generation...") - palette = ColorPalette((0, 0, 0)) - result = palette.generate_random_hex_colors() - assert isinstance(result, list), "Expected a list for the random HEX colors." - print("Random HEX Colors:", result) - -def test_generate_gradient(): - print("Testing Gradient Generation...") - base_color = (255, 60, 52) # Example base color (Red) - palette = ColorPalette(base_color) - start_color = (255, 60, 52) # Start color (Red) - end_color = (51, 247, 255) # End color (Cyan) - expected_gradient = [ - (255, 60, 52), - (214, 97, 92), - (173, 134, 133), - (132, 172, 173), - (91, 209, 214), - (51, 247, 255) - ] - result = palette.generate_gradient(start_color, end_color, steps=5) - assert result == expected_gradient, f"Expected {expected_gradient}, but got {result}" - print(f"Gradient: {result}") - -def test_export_palette(): - print("Testing Palette Export...") - base = (255, 60, 52) # Red - cp = ColorPalette(base) - - # 1. Export a simple list palette (e.g., complementary) - print("Generating Complementary...") - comp_palette = cp.generate_complementary() # self.palette is now the complementary list - print(f"Current Palette (Complementary List): {cp.palette}") - try: - cp.export_palette("complementary_palette.json") - cp.export_palette("complementary_palette.txt") - cp.export_palette("complementary_palette.csv") - print("Exported complementary list palette.") - except Exception as e: - print(f"Error exporting complementary: {e}") - - - # 2. Generate and export a complex dictionary palette - print("\nGenerating Random Palette Dictionary...") - # Generate the dict and set it as the current palette - random_palette_dict = cp.generate_random_palette() - print(f"Current Palette (Random Dict): Keys = {cp.palette.keys()}") - try: - cp.export_palette("random_palette_structure.json") - cp.export_palette("random_palette_structure.txt") - cp.export_palette("random_palette_structure.csv") - print("Exported random dictionary palette.") - except Exception as e: - print(f"Error exporting random dict: {e}") - - # 3. Generate a gradient (doesn't modify self.palette) and export it separately - print("\nGenerating Gradient...") - gradient = cp.generate_gradient((255, 0, 0), (0, 0, 255), steps=5) - # To export the gradient, temporarily set it as the palette - original_palette = cp.palette # Save current palette - cp.palette = gradient - print(f"Current Palette (Gradient List): {cp.palette}") - try: - cp.export_palette("gradient_palette.json") - cp.export_palette("gradient_palette.txt") - cp.export_palette("gradient_palette.csv") - print("Exported gradient list palette.") - except Exception as e: - print(f"Error exporting gradient: {e}") - finally: - cp.palette = original_palette # Restore previous palette - - print("\nExporting complete.") - -def run_tests(): - test_generate_complementary() - test_generate_analogous() - test_generate_triadic() - test_generate_monochromatic() - test_generate_tetradic() - test_generate_square() - test_generate_split_complementary() - test_palette_to_hex() - test_generate_random_palette() - test_generate_random_color() - test_generate_random_hex_colors() - test_generate_gradient() - test_export_palette() - print("All tests passed!") + +class TestHarmonySchemes: + BASE = (255, 60, 52) + + def test_init_validation(self) -> None: + p = ColorPalette([255, 60, 52]) + assert p.base_color == (255, 60, 52) + assert p.palette == [(255, 60, 52)] + + with pytest.raises(ValueError): + ColorPalette((256, 0, 0)) + with pytest.raises(ValueError): + ColorPalette((255, 0)) + with pytest.raises(TypeError): + ColorPalette("#FF0000") # type: ignore[arg-type] + + def test_complementary_analogous_triadic_split(self) -> None: + palette = ColorPalette(self.BASE) + assert palette.generate_complementary() == [(255, 60, 52), (51, 247, 255)] + assert palette.generate_analogous() == [(255, 51, 145), (255, 60, 52), (255, 161, 51)] + assert palette.generate_triadic() == [(255, 60, 52), (51, 255, 59), (59, 51, 255)] + assert palette.generate_split_complementary() == [ + (255, 60, 52), + (51, 255, 161), + (51, 145, 255), + ] + + def test_tetradic_distinct_from_square(self) -> None: + palette = ColorPalette(self.BASE) + square = palette.generate_square() + assert square == [(255, 60, 52), (145, 255, 51), (51, 247, 255), (161, 51, 255)] + + tetradic = palette.generate_tetradic() # default angle=60 (rectangular) + assert len(tetradic) == 4 + assert tetradic != square + assert palette.generate_tetradic(angle=90) == square + + def test_monochromatic_and_edge_cases(self) -> None: + palette = ColorPalette(self.BASE) + expected = [ + (51, 2, 0), (73, 3, 0), (95, 4, 0), (118, 5, 0), + (140, 5, 0), (162, 6, 0), (184, 7, 0), (206, 8, 0), + (228, 9, 0), (251, 10, 0), (255, 27, 18), (255, 48, 40), + (255, 70, 62), (255, 91, 84), (255, 112, 106), + (255, 134, 129), (255, 155, 151), (255, 176, 173), + (255, 197, 195), (255, 219, 217), (255, 240, 239), + (255, 255, 255), + ] + assert palette.generate_monochromatic() == expected + assert palette.palette_to_hex() == [ + "#330200", "#490300", "#5F0400", "#760500", + "#8C0500", "#A20600", "#B80700", "#CE0800", + "#E40900", "#FB0A00", "#FF1B12", "#FF3028", + "#FF463E", "#FF5B54", "#FF706A", "#FF8681", + "#FF9B97", "#FFB0AD", "#FFC5C3", "#FFDBD9", + "#FFF0EF", "#FFFFFF", + ] + + # Regression: shades=1 previously raised ZeroDivisionError + assert palette.generate_monochromatic(shades=1) == [self.BASE] + with pytest.raises(ValueError): + palette.generate_monochromatic(shades=0) + with pytest.raises(TypeError): + palette.generate_monochromatic(shades=True) # type: ignore[arg-type] + + +class TestMutationRandomAndGradients: + def test_random_palette_and_dict_palette_to_hex(self) -> None: + palette = ColorPalette((10, 20, 30)) + + # set_as_current=False preserves base_color and palette + preview = palette.generate_random_palette(set_as_current=False) + assert isinstance(preview, dict) + assert palette.base_color == (10, 20, 30) + assert palette.palette == [(10, 20, 30)] + + # set_as_current=True sets dict palette, and palette_to_hex() works on it + current = palette.generate_random_palette(set_as_current=True) + assert palette.palette is current + hex_dict = palette.palette_to_hex() + assert isinstance(hex_dict, dict) + assert set(hex_dict.keys()) == set(current.keys()) + assert isinstance(hex_dict["Base Color"], str) and hex_dict["Base Color"].startswith("#") + assert all(h.startswith("#") for h in hex_dict["Triadic Palette"]) + + # add_color / remove_color raise clear TypeError on dict palettes + with pytest.raises(TypeError): + palette.add_color((1, 2, 3)) + with pytest.raises(TypeError): + palette.remove_color((1, 2, 3)) + + def test_add_remove_and_random_colors(self) -> None: + palette = ColorPalette((0, 0, 0)) + palette.add_color((255, 255, 255)) + assert palette.palette == [(0, 0, 0), (255, 255, 255)] + palette.remove_color((0, 0, 0)) + assert palette.palette == [(255, 255, 255)] + + color = palette.generate_random_color() + assert set(color.keys()) == {"RGB Color", "HEX Color", "HSL Color"} + hexes = palette.generate_random_hex_colors(5) + assert len(hexes) == 5 and all(len(h) == 7 and h.startswith("#") for h in hexes) + assert palette.generate_random_hex_colors(0) == [] + with pytest.raises(ValueError): + palette.generate_random_hex_colors(-1) + + @pytest.mark.parametrize("space", ["rgb", "linear", "lab", "hsl"]) + def test_generate_gradient_spaces(self, space: str) -> None: + palette = ColorPalette((255, 60, 52)) + start, end = (255, 60, 52), (51, 247, 255) + grad = palette.generate_gradient(start, end, steps=5, space=space) + assert len(grad) == 6 + assert grad[0] == start + assert grad[-1] == end + # Does not mutate self.palette + assert palette.palette == [(255, 60, 52)] + + # Self-gradient identity (regression for int() truncation on (3, 3, 3)) + assert palette.generate_gradient((3, 3, 3), (3, 3, 3), steps=5, space=space) == [ + (3, 3, 3) + ] * 6 + + def test_generate_gradient_validation(self) -> None: + palette = ColorPalette((0, 0, 0)) + with pytest.raises(ValueError): + palette.generate_gradient((0, 0, 0), (255, 255, 255), steps=0) + with pytest.raises(ValueError): + palette.generate_gradient((0, 0, 0), (255, 255, 255), steps=3, space="cmyk") + + +class TestExportAndMetadata: + def test_export_list_and_dict_all_formats(self, tmp_path: Path) -> None: + sub = tmp_path / "dir.with.dots" + sub.mkdir() + + cp = ColorPalette((255, 60, 52)) + cp.generate_complementary() + + json_path = sub / "comp.json" + txt_path = sub / "comp.txt" + csv_path = sub / "comp.csv" + css_path = sub / "comp.css" + + cp.export_palette(json_path) + cp.export_palette(str(txt_path)) + cp.export_palette(csv_path) + cp.export_palette(css_path) + + data = json.loads(json_path.read_text(encoding="utf-8")) + assert data == [ + {"rgb": [255, 60, 52], "hex": "#FF3C34"}, + {"rgb": [51, 247, 255], "hex": "#33F7FF"}, + ] + assert "#FF3C34" in txt_path.read_text(encoding="utf-8") + with csv_path.open(encoding="utf-8") as fh: + rows = list(csv.reader(fh)) + assert rows[0] == ["Type", "Index", "Hex", "R", "G", "B"] + assert rows[1] == ["Simple Palette", "0", "#FF3C34", "255", "60", "52"] + css_text = css_path.read_text(encoding="utf-8") + assert "--palette-color-0: #FF3C34;" in css_text + + # Dictionary export + cp.generate_random_palette() + for ext in (".json", ".txt", ".csv", ".css"): + out = sub / f"random{ext}" + cp.export_palette(out) + assert out.stat().st_size > 0 + + # Regression: extensionless filename named "json" must be rejected + with pytest.raises(ValueError): + cp.export_palette(sub / "json") + with pytest.raises(ValueError): + cp.export_palette(sub / "palette.xml") + + cp.palette = [] + with pytest.raises(ValueError): + cp.export_palette(sub / "empty.json") + + def test_package_version_and_typing_marker(self) -> None: + repo_root = Path(__file__).resolve().parent.parent + pyproject_text = (repo_root / "pyproject.toml").read_text(encoding="utf-8") + assert f'version = "{hued.__version__}"' in pyproject_text + assert (Path(hued.__file__).resolve().parent / "py.typed").is_file() + for symbol in hued.__all__: + assert hasattr(hued, symbol), f"Missing export: {symbol}" + if __name__ == "__main__": - run_tests() + raise SystemExit(pytest.main([__file__])) diff --git a/hued/__init__.py b/hued/__init__.py index b8b4154..f7e77fb 100644 --- a/hued/__init__.py +++ b/hued/__init__.py @@ -1,4 +1,147 @@ +"""Hued — zero-dependency Python library for color conversion, analysis, palettes, and named colors.""" + +from __future__ import annotations + +from hued.analysis import ( + brightness, + check_color_quality, + check_wcag_contrast, + color_contrast, + delta_e, + get_luminance, + get_temperature, + get_text_color_from_background, + get_vibrancy, + is_muted, + is_neutral, + is_pastel, + is_vibrant, + rgb_to_linear, + simulate_color_blindness, +) from hued.colors import ColorManager -from hued.analysis import get_temperature, is_neutral, brightness, is_pastel, is_muted, is_vibrant, rgb_to_linear, get_luminance, get_vibrancy, color_contrast, get_text_color_from_background, check_color_quality, simulate_color_blindness -from hued.conversions import rgb_to_hex, hex_to_rgb, rgb_to_hsl, hsl_to_rgb, rgb_to_hsv, hsv_to_rgb, rgb_to_cmyk, cmyk_to_rgb, blend_colors, hex_to_cmyk, hex_to_hsl, hex_to_hsv, hsv_to_cmyk, hsv_to_hex, hsv_to_hsl, hsl_to_cmyk, hsl_to_hex, hsl_to_hsv, cmyk_to_hex, cmyk_to_hsl, cmyk_to_hsv, rgb_to_xyz, xyz_to_rgb, xyz_to_cmyk, xyz_to_hex, xyz_to_hsl, xyz_to_hsv, hex_to_xyz, hsl_to_xyz, hsv_to_xyz, cmyk_to_xyz -from hued.palettes import ColorPalette \ No newline at end of file +from hued.conversions import ( + adjust_lightness, + adjust_saturation, + blend_colors, + cmyk_to_hex, + cmyk_to_hsl, + cmyk_to_hsv, + cmyk_to_lab, + cmyk_to_rgb, + cmyk_to_xyz, + hex_to_cmyk, + hex_to_hsl, + hex_to_hsv, + hex_to_lab, + hex_to_rgb, + hex_to_xyz, + hsl_to_cmyk, + hsl_to_hex, + hsl_to_hsv, + hsl_to_lab, + hsl_to_rgb, + hsl_to_xyz, + hsv_to_cmyk, + hsv_to_hex, + hsv_to_hsl, + hsv_to_lab, + hsv_to_rgb, + hsv_to_xyz, + invert_color, + lab_to_cmyk, + lab_to_hex, + lab_to_hsl, + lab_to_hsv, + lab_to_rgb, + lab_to_xyz, + linear_to_rgb, + rgb_to_cmyk, + rgb_to_hex, + rgb_to_hsl, + rgb_to_hsv, + rgb_to_lab, + rgb_to_xyz, + to_grayscale, + xyz_to_cmyk, + xyz_to_hex, + xyz_to_hsl, + xyz_to_hsv, + xyz_to_lab, + xyz_to_rgb, +) +from hued.palettes import ColorPalette + +__version__ = "1.1.0" + +__all__ = [ + "__version__", + # Named colors & palettes + "ColorManager", + "ColorPalette", + # Analysis & accessibility + "get_temperature", + "is_neutral", + "brightness", + "is_pastel", + "is_muted", + "is_vibrant", + "rgb_to_linear", + "get_luminance", + "get_vibrancy", + "color_contrast", + "check_wcag_contrast", + "get_text_color_from_background", + "check_color_quality", + "simulate_color_blindness", + "delta_e", + # Conversions & adjustments + "rgb_to_hex", + "hex_to_rgb", + "rgb_to_hsl", + "hsl_to_rgb", + "rgb_to_hsv", + "hsv_to_rgb", + "rgb_to_cmyk", + "cmyk_to_rgb", + "hex_to_cmyk", + "hex_to_hsl", + "hex_to_hsv", + "hsv_to_cmyk", + "hsv_to_hex", + "hsv_to_hsl", + "hsl_to_cmyk", + "hsl_to_hex", + "hsl_to_hsv", + "cmyk_to_hex", + "cmyk_to_hsl", + "cmyk_to_hsv", + "rgb_to_xyz", + "xyz_to_rgb", + "xyz_to_cmyk", + "xyz_to_hex", + "xyz_to_hsl", + "xyz_to_hsv", + "hex_to_xyz", + "hsl_to_xyz", + "hsv_to_xyz", + "cmyk_to_xyz", + "rgb_to_lab", + "lab_to_rgb", + "xyz_to_lab", + "lab_to_xyz", + "hex_to_lab", + "lab_to_hex", + "hsl_to_lab", + "lab_to_hsl", + "hsv_to_lab", + "lab_to_hsv", + "cmyk_to_lab", + "lab_to_cmyk", + "linear_to_rgb", + "blend_colors", + "invert_color", + "to_grayscale", + "adjust_lightness", + "adjust_saturation", +] diff --git a/hued/analysis.py b/hued/analysis.py index c890056..c49604b 100644 --- a/hued/analysis.py +++ b/hued/analysis.py @@ -1,294 +1,515 @@ -from hued.conversions import rgb_to_hsv - -def get_temperature(rgb): - """ - Determine the temperature of a color based on its RGB values. +"""Color analysis, accessibility (WCAG 2.1), perceptual difference, and vision simulation.""" + +from __future__ import annotations + +import math +from collections.abc import Sequence +from typing import Any + +from hued.conversions import ( + _linear_to_srgb_channel, + _rgb_to_hsl_exact, + _rgb_to_hsv_exact, + _srgb_to_linear_channel, + _validate_real, + _validate_rgb_number_tuple, + rgb_to_lab, +) + +__all__ = [ + "get_temperature", + "is_neutral", + "brightness", + "is_pastel", + "is_muted", + "is_vibrant", + "rgb_to_linear", + "get_luminance", + "get_vibrancy", + "color_contrast", + "check_wcag_contrast", + "get_text_color_from_background", + "check_color_quality", + "simulate_color_blindness", + "delta_e", +] + +# Color-vision deficiency simulation matrices operating on linear sRGB. +# Row sums equal 1.0 so neutral grays preserve exact luminance. +_CVD_MATRICES: dict[str, tuple[tuple[float, float, float], ...]] = { + "protanopia": ( + (0.567, 0.433, 0.0), + (0.558, 0.442, 0.0), + (0.0, 0.242, 0.758), + ), + "deuteranopia": ( + (0.625, 0.375, 0.0), + (0.7, 0.3, 0.0), + (0.0, 0.3, 0.7), + ), + "tritanopia": ( + (0.95, 0.05, 0.0), + (0.0, 0.433, 0.567), + (0.0, 0.475, 0.525), + ), + "achromatopsia": ( + (0.2126, 0.7152, 0.0722), + (0.2126, 0.7152, 0.0722), + (0.2126, 0.7152, 0.0722), + ), +} + + +def get_temperature(rgb: Sequence[int]) -> str: + """Classify the perceptual color temperature of an RGB color. + + Achromatic and very low-saturation colors return ``"Neutral"``. Chromatic + colors are classified by hue into ``"Warm"`` (reds, oranges, yellows, and + warm roses: ``0°–75°`` and ``330°–360°``), ``"Cool"`` (cool greens, teals, + cyans, blues, and indigos: ``135°–270°``), or ``"Neutral"`` (transitional + yellow-greens/greens and purples/magentas). Parameters: - rgb (tuple): A tuple containing the RGB values (r, g, b). + rgb (tuple): RGB color ``(r, g, b)`` in ``[0, 255]``. Returns: - str: "Warm" if the color is warm, "Cool" if cool, or "Neutral" if neither. + str: ``"Warm"``, ``"Cool"``, or ``"Neutral"``. """ - r, g, b = rgb - if r > g and r > b: + r, g, b = _validate_rgb_number_tuple(rgb) + chroma = max(r, g, b) - min(r, g, b) + h, s, _ = _rgb_to_hsv_exact(r, g, b) + + if chroma < 15.0 or s < 0.1: + return "Neutral" + if h <= 75.0 or h >= 330.0: return "Warm" - elif b > r and b > g: + if 135.0 <= h <= 270.0: return "Cool" - else: - return "Neutral" + return "Neutral" -def is_neutral(rgb): - """ - Check if a color is neutral. + +def is_neutral(rgb: Sequence[int], tolerance: float = 30) -> bool: + """Check whether an RGB color is neutral (near-gray). Parameters: - rgb (tuple): A tuple containing the RGB values (r, g, b). + rgb (tuple): RGB color ``(r, g, b)`` in ``[0, 255]``. + tolerance (float): Exclusive maximum pairwise channel difference + (default ``30``). Must be non-negative. Returns: - bool: True if the color is neutral, False otherwise. + bool: ``True`` if all pairwise channel differences are below ``tolerance``. """ - r, g, b = rgb - return abs(r - g) < 30 and abs(g - b) < 30 and abs(r - b) < 30 + r, g, b = _validate_rgb_number_tuple(rgb) + tol = _validate_real(tolerance, "tolerance") + if tol < 0.0: + raise ValueError(f"tolerance must be non-negative, got {tolerance}.") + return abs(r - g) < tol and abs(g - b) < tol and abs(r - b) < tol -def brightness(rgb): - """ - Calculate the brightness of a color. + +def brightness(rgb: Sequence[int]) -> float: + """Calculate the perceived brightness (ITU-R BT.601 luma) of an RGB color. Parameters: - rgb (tuple): A tuple containing the RGB values (r, g, b). + rgb (tuple): RGB color ``(r, g, b)`` in ``[0, 255]``. Returns: - float: The brightness of the color as a value between 0 and 1. + float: Brightness value in ``[0.0, 1.0]``. """ - r, g, b = rgb - return (0.299 * r + 0.587 * g + 0.114 * b) / 255 + r, g, b = _validate_rgb_number_tuple(rgb) + return (0.299 * r + 0.587 * g + 0.114 * b) / 255.0 -def is_pastel(rgb): - """ - Check if a color is pastel. + +def is_pastel(rgb: Sequence[int]) -> bool: + """Check whether an RGB color is a pastel shade. + + Pastel colors combine high lightness/value with soft, non-zero saturation, + excluding pure white, achromatic grays, dark shades, and vivid neons. Parameters: - rgb (tuple): A tuple containing the RGB values (r, g, b). + rgb (tuple): RGB color ``(r, g, b)`` in ``[0, 255]``. Returns: - bool: True if the color is pastel, False otherwise. + bool: ``True`` if the color is pastel, ``False`` otherwise. """ - r, g, b = rgb - return all(value > 127 for value in rgb) and brightness(rgb) > 0.5 + r, g, b = _validate_rgb_number_tuple(rgb) + _, s_hsv, v = _rgb_to_hsv_exact(r, g, b) + _, _, l = _rgb_to_hsl_exact(r, g, b) + return l >= 0.65 and v >= 0.75 and 0.05 <= s_hsv <= 0.55 -def is_muted(rgb): - """ - Check if a color is muted. + +def is_muted(rgb: Sequence[int]) -> bool: + """Check whether an RGB color is muted (low saturation, mid/low brightness). + + Excludes pure/near-black and very bright shades (such as white and pastels). Parameters: - rgb (tuple): A tuple containing the RGB values (r, g, b). + rgb (tuple): RGB color ``(r, g, b)`` in ``[0, 255]``. Returns: - bool: True if the color is muted, False otherwise. + bool: ``True`` if the color is muted, ``False`` otherwise. """ - r, g, b = rgb - # Calculate brightness - brightness = (0.299 * r + 0.587 * g + 0.114 * b) / 255 - # Calculate saturation (simple approach) - max_rgb = max(r, g, b) - min_rgb = min(r, g, b) - saturation = (max_rgb - min_rgb) / max_rgb if max_rgb > 0 else 0 + r, g, b = _validate_rgb_number_tuple(rgb) + luma = (0.299 * r + 0.587 * g + 0.114 * b) / 255.0 + _, s_hsv, _ = _rgb_to_hsv_exact(r, g, b) + return 0.1 <= luma <= 0.75 and s_hsv < 0.5 - return brightness < 0.5 and saturation < 0.5 # Adjust thresholds as needed -def is_vibrant(rgb): - """ - Check if a color is vibrant. +def is_vibrant(rgb: Sequence[int]) -> bool: + """Check whether an RGB color is vibrant (high HSV saturation and value). Parameters: - rgb (tuple): A tuple containing the RGB values (r, g, b). + rgb (tuple): RGB color ``(r, g, b)`` in ``[0, 255]``. Returns: - bool: True if the color is vibrant, False otherwise. + bool: ``True`` if HSV saturation ``> 0.5`` and value ``> 0.7``. """ - r, g, b = rgb + r, g, b = _validate_rgb_number_tuple(rgb) + _, s, v = _rgb_to_hsv_exact(r, g, b) + return s > 0.5 and v > 0.7 - _, s, v = rgb_to_hsv(r, g, b) - # Define thresholds for vibrancy - saturation_threshold = 0.5 - value_threshold = 0.7 - # Check if the color is vibrant - return s > saturation_threshold and v > value_threshold +def rgb_to_linear(rgb: Sequence[int]) -> list[float]: + """Convert sRGB values ``[0, 255]`` to linear sRGB ``[0.0, 1.0]``. -def rgb_to_linear(rgb): - """Convert RGB values to linear RGB. - - The input RGB values should be in the range [0, 255]. This function - applies the sRGB transfer function to convert each RGB component - to its linear equivalent, which is useful for various color - calculations, including luminance and color mixing. + Applies the standard IEC 61966-2-1 / WCAG 2.1 sRGB inverse transfer + function: ``s / 12.92`` for ``s <= 0.04045``, and + ``((s + 0.055) / 1.055) ** 2.4`` otherwise, where ``s = c / 255``. Parameters: - rgb (tuple): A tuple of three integers representing the RGB - values (r, g, b), each in the range [0, 255]. + rgb (tuple): RGB color ``(r, g, b)`` in ``[0, 255]``. Returns: - list: A list of three floats representing the linear RGB values. + list[float]: Three linear RGB floats in ``[0.0, 1.0]``. """ - r, g, b = rgb + r, g, b = _validate_rgb_number_tuple(rgb) return [ - (c / 255) ** 2.2 if c > 0.04045 else c / 255 / 12.92 for c in (r, g, b) + _srgb_to_linear_channel(r), + _srgb_to_linear_channel(g), + _srgb_to_linear_channel(b), ] -def get_luminance(rgb): - """Calculate the relative luminance of an RGB color. - This function converts the input RGB color to linear RGB and - then computes the relative luminance using the standard - formula based on the RGB color's linear components. - The coefficients used are based on the sRGB color space. +def get_luminance(rgb: Sequence[int]) -> float: + """Calculate the WCAG 2.1 relative luminance of an sRGB color. Parameters: - rgb (tuple): A tuple of three integers representing the RGB - values (r, g, b), each in the range [0, 255]. + rgb (tuple): RGB color ``(r, g, b)`` in ``[0, 255]``. Returns: - float: The calculated relative luminance of the RGB color. + float: Relative luminance in ``[0.0, 1.0]`` (``0.0`` for black, ``1.0`` for white). """ r_linear, g_linear, b_linear = rgb_to_linear(rgb) return 0.2126 * r_linear + 0.7152 * g_linear + 0.0722 * b_linear -def get_vibrancy(rgb): - """Calculate the vibrancy of an RGB color. - This function computes vibrancy based on the chromaticity of the RGB values. - A higher value indicates a more vibrant color. +def get_vibrancy(rgb: Sequence[int]) -> float: + """Calculate the HSV chroma vibrancy ratio ``(max - min) / max`` of an RGB color. Parameters: - rgb (tuple): A tuple of three integers representing the RGB - values (r, g, b), each in the range [0, 255]. + rgb (tuple): RGB color ``(r, g, b)`` in ``[0, 255]``. Returns: - float: The calculated vibrancy of the RGB color. + float: Vibrancy score in ``[0.0, 1.0]``. """ - r, g, b = rgb + r, g, b = _validate_rgb_number_tuple(rgb) max_color = max(r, g, b) + if max_color == 0.0: + return 0.0 min_color = min(r, g, b) - if max_color == 0: - return 0 # Avoid division by zero; neutral color - - vibrancy = (max_color - min_color) / max_color # A simple measure of vibrancy - return vibrancy + return (max_color - min_color) / max_color -def color_contrast(color1, color2): - """ - Calculates the contrast ratio between two colors using their RGB values. - The contrast ratio is calculated based on the relative luminance of each color - and is used to determine the readability of text on different background colors. - The result is a number between 1 and 21, where a higher value indicates better - contrast. +def color_contrast(color1: Sequence[int], color2: Sequence[int]) -> float: + """Calculate the WCAG 2.1 contrast ratio between two RGB colors. Parameters: - color1 (tuple): The first RGB color as a tuple of three integers (R, G, B). - color2 (tuple): The second RGB color as a tuple of three integers (R, G, B). + color1 (tuple): First RGB color ``(r, g, b)`` in ``[0, 255]``. + color2 (tuple): Second RGB color ``(r, g, b)`` in ``[0, 255]``. Returns: - float: The contrast ratio between the two colors. + float: Contrast ratio in ``[1.0, 21.0]`` (higher means stronger contrast). """ + l1 = get_luminance(color1) + l2 = get_luminance(color2) + lighter, darker = (l1, l2) if l1 >= l2 else (l2, l1) + return (lighter + 0.05) / (darker + 0.05) - L1 = get_luminance(color1) - L2 = get_luminance(color2) - if L1 > L2: - return (L1 + 0.05) / (L2 + 0.05) - else: - return (L2 + 0.05) / (L1 + 0.05) -def get_text_color_from_background(background_color): - """Determines whether the text should be "light" or "dark" based on the background color. +def check_wcag_contrast( + foreground: Sequence[int], + background: Sequence[int], +) -> dict[str, Any]: + """Evaluate a foreground/background color pair against WCAG 2.1 thresholds. Parameters: - background_color (tuple): The background RGB color as a tuple of three integers (R, G, B). + foreground (tuple): Foreground/text RGB color ``(r, g, b)`` in ``[0, 255]``. + background (tuple): Background RGB color ``(r, g, b)`` in ``[0, 255]``. Returns: - str: "light" if the background is dark and vibrant, "dark" if the background is bright and muted. + dict: Dictionary containing: + - ``contrast_ratio`` (float): Contrast ratio rounded to 2 decimals. + - ``aa_normal`` (bool): Meets WCAG AA for normal text (``>= 4.5``). + - ``aa_large`` (bool): Meets WCAG AA for large text (``>= 3.0``). + - ``aaa_normal`` (bool): Meets WCAG AAA for normal text (``>= 7.0``). + - ``aaa_large`` (bool): Meets WCAG AAA for large text (``>= 4.5``). + - ``ui_components`` (bool): Meets WCAG AA for UI/graphics (``>= 3.0``). """ - # Calculate luminance and vibrancy of the background color - luminance_value = get_luminance(background_color) - vibrancy_value = get_vibrancy(background_color) - - # Enhanced decision logic based on luminance and vibrancy - if luminance_value < 0.3: # Dark background - if vibrancy_value > 0.4: # Vibrant dark colors - return "light" # Use light text for better readability - else: - return "dark" # Use dark text if it's a muted dark color - elif luminance_value < 0.6: # Medium background (transition zone) - if vibrancy_value > 0.5: # Bright but vibrant - return "dark" # Use dark text for readability - else: - return "light" # Use light text if the color is less vibrant - else: # Bright background - if vibrancy_value < 0.4: # Muted bright colors - return "dark" # Use dark text for readability - else: - return "light" # Use light text for vibrant bright colors + ratio = color_contrast(foreground, background) + return { + "contrast_ratio": round(ratio, 2), + "aa_normal": ratio >= 4.5, + "aa_large": ratio >= 3.0, + "aaa_normal": ratio >= 7.0, + "aaa_large": ratio >= 4.5, + "ui_components": ratio >= 3.0, + } -def check_color_quality(rgb): - """ - Evaluates if a color is of 'good quality' for UI/text usage. - This function simulates a color visibility tester by checking the color's - contrast ratio against standard black and white backgrounds. A color is - considered 'good quality' if it meets the WCAG AA standard (contrast ratio >= 4.5) - against at least one of the backgrounds. +def get_text_color_from_background(background_color: Sequence[int]) -> str: + """Return ``"light"`` or ``"dark"`` text for maximum WCAG contrast on a background. + + Compares the WCAG 2.1 contrast ratio of pure white ``(255, 255, 255)`` and + pure black ``(0, 0, 0)`` against ``background_color`` and picks whichever + yields greater readability (equivalent to relative luminance threshold + ``sqrt(1.05 * 0.05) - 0.05 ~= 0.1791``). Parameters: - rgb (tuple): A tuple containing the RGB values (r, g, b). + background_color (tuple): Background RGB color ``(r, g, b)`` in ``[0, 255]``. Returns: - dict: A dictionary containing: - - 'contrast_with_black' (float): Contrast ratio with black. - - 'contrast_with_white' (float): Contrast ratio with white. - - 'is_good_quality' (bool): True if legible on black or white. + str: ``"light"`` when white text has higher contrast, otherwise ``"dark"``. """ - black = (0, 0, 0) - white = (255, 255, 255) + lum = get_luminance(background_color) + contrast_with_white = 1.05 / (lum + 0.05) + contrast_with_black = (lum + 0.05) / 0.05 + return "light" if contrast_with_white >= contrast_with_black else "dark" + + +def check_color_quality( + rgb: Sequence[int], + background: Sequence[int] | None = None, + min_contrast: float | None = None, +) -> dict[str, Any]: + """Evaluate a color's visibility and contrast quality for UI and text usage. + + Always computes contrast ratios and WCAG AA/AAA compliance against black + ``(0, 0, 0)`` and white ``(255, 255, 255)``. + + Note: + For any color, ``contrast_with_black * contrast_with_white == 21``, so + ``max(contrast_with_black, contrast_with_white) >= sqrt(21) ~= 4.58``. + Because a 4.5 threshold against "black or white" can never be ``False``, + when ``background`` is omitted ``min_contrast`` defaults to ``7.0`` + (WCAG AAA) so mid-luminance colors with weak contrast on both light and + dark surfaces are properly flagged. When a specific ``background`` is + given, ``min_contrast`` defaults to ``4.5`` (WCAG AA). + + Parameters: + rgb (tuple): RGB color ``(r, g, b)`` in ``[0, 255]``. + background (tuple | None): Optional target background RGB color. + min_contrast (float | None): Optional custom contrast threshold in ``[1, 21]``. - contrast_black = color_contrast(rgb, black) - contrast_white = color_contrast(rgb, white) + Returns: + dict: Contrast metrics and compliance flags including + ``contrast_with_black``, ``contrast_with_white``, ``passes_aa_on_black``, + ``passes_aa_on_white``, ``passes_aaa_on_black``, ``passes_aaa_on_white``, + ``best_background``, ``is_good_quality``, and (when ``background`` is + supplied) ``contrast_with_background``. + """ + contrast_black = color_contrast(rgb, (0, 0, 0)) + contrast_white = color_contrast(rgb, (255, 255, 255)) - # WCAG AA requires 4.5:1 for normal text - is_good = contrast_black >= 4.5 or contrast_white >= 4.5 + if min_contrast is not None: + threshold = _validate_real(min_contrast, "min_contrast") + if not 1.0 <= threshold <= 21.0: + raise ValueError(f"min_contrast must be in the range [1, 21], got {min_contrast}.") + else: + threshold = 4.5 if background is not None else 7.0 - return { + result: dict[str, Any] = { "contrast_with_black": round(contrast_black, 2), "contrast_with_white": round(contrast_white, 2), - "is_good_quality": is_good + "passes_aa_on_black": contrast_black >= 4.5, + "passes_aa_on_white": contrast_white >= 4.5, + "passes_aaa_on_black": contrast_black >= 7.0, + "passes_aaa_on_white": contrast_white >= 7.0, + "best_background": "black" if contrast_black >= contrast_white else "white", } -def simulate_color_blindness(rgb, blindness_type="protanopia", intensity=1.0): - """ - Simulates color blindness on a given RGB color. + if background is not None: + contrast_bg = color_contrast(rgb, background) + result["contrast_with_background"] = round(contrast_bg, 2) + result["is_good_quality"] = contrast_bg >= threshold + else: + result["is_good_quality"] = contrast_black >= threshold or contrast_white >= threshold - Parameters: - rgb (tuple): A tuple containing the RGB values (r, g, b). - blindness_type (str): The type of color blindness to simulate. - Options: 'protanopia', 'deuteranopia', 'tritanopia', 'achromatopsia'. - Default is 'protanopia'. - intensity (float): The intensity of the simulation (0.0 to 1.0). - Default is 1.0 (full simulation). + return result - Returns: - tuple: A tuple representing the simulated RGB values. - """ - if not (0 <= intensity <= 1): - raise ValueError("Intensity must be between 0 and 1.") - blindness_type = blindness_type.lower() +def simulate_color_blindness( + rgb: Sequence[int], + blindness_type: str = "protanopia", + intensity: float = 1.0, +) -> tuple[int, int, int]: + """Simulate color-vision deficiency on an RGB color. - # Matrices for color blindness simulation (approximate for sRGB/Linear) - matrices = { - "protanopia": [[0.567, 0.433, 0.0], [0.558, 0.442, 0.0], [0.0, 0.242, 0.758]], - "deuteranopia": [[0.625, 0.375, 0.0], [0.7, 0.3, 0.0], [0.0, 0.3, 0.7]], - "tritanopia": [[0.95, 0.05, 0.0], [0.0, 0.433, 0.567], [0.0, 0.475, 0.525]], - "achromatopsia": [[0.299, 0.587, 0.114], [0.299, 0.587, 0.114], [0.299, 0.587, 0.114]] - } + Performs the matrix transformation and severity interpolation in linear sRGB + space and re-encodes using the exact IEC 61966-2-1 sRGB transfer function. - if blindness_type not in matrices: - raise ValueError(f"Unknown blindness type: {blindness_type}") + Parameters: + rgb (tuple): RGB color ``(r, g, b)`` in ``[0, 255]``. + blindness_type (str): One of ``"protanopia"``, ``"deuteranopia"``, + ``"tritanopia"``, or ``"achromatopsia"`` (case-insensitive). + intensity (float): Simulation severity in ``[0.0, 1.0]`` (default ``1.0``). - matrix = matrices[blindness_type] + Returns: + tuple[int, int, int]: Simulated RGB tuple in ``[0, 255]``. + + Raises: + TypeError: If arguments have invalid types. + ValueError: If ``blindness_type`` is unknown or ``intensity`` is outside ``[0, 1]``. + """ r_lin, g_lin, b_lin = rgb_to_linear(rgb) + if not isinstance(blindness_type, str): + raise TypeError(f"blindness_type must be a string, got {type(blindness_type).__name__}.") + key = blindness_type.strip().lower() + if key not in _CVD_MATRICES: + supported = ", ".join(sorted(_CVD_MATRICES)) + raise ValueError(f"Unknown blindness type: {blindness_type!r}. Supported: {supported}.") + + t = _validate_real(intensity, "intensity") + if not 0.0 <= t <= 1.0: + raise ValueError("Intensity must be between 0 and 1.") + + matrix = _CVD_MATRICES[key] r_sim = r_lin * matrix[0][0] + g_lin * matrix[0][1] + b_lin * matrix[0][2] g_sim = r_lin * matrix[1][0] + g_lin * matrix[1][1] + b_lin * matrix[1][2] b_sim = r_lin * matrix[2][0] + g_lin * matrix[2][1] + b_lin * matrix[2][2] - # Convert back to sRGB (using simplified gamma 2.2 to match rgb_to_linear) - def lin_to_srgb(c): return c ** (1 / 2.2) - r_final, g_final, b_final = lin_to_srgb(max(0, r_sim)) * 255, lin_to_srgb(max(0, g_sim)) * 255, lin_to_srgb(max(0, b_sim)) * 255 + inv = 1.0 - t + r_mix = r_lin * inv + r_sim * t + g_mix = g_lin * inv + g_sim * t + b_mix = b_lin * inv + b_sim * t return ( - max(0, min(255, int(rgb[0] * (1 - intensity) + r_final * intensity))), - max(0, min(255, int(rgb[1] * (1 - intensity) + g_final * intensity))), - max(0, min(255, int(rgb[2] * (1 - intensity) + b_final * intensity))) + max(0, min(255, round(_linear_to_srgb_channel(r_mix) * 255.0))), + max(0, min(255, round(_linear_to_srgb_channel(g_mix) * 255.0))), + max(0, min(255, round(_linear_to_srgb_channel(b_mix) * 255.0))), + ) + + +def _ciede2000( + lab1: tuple[float, float, float], + lab2: tuple[float, float, float], +) -> float: + """Compute exact CIEDE2000 color difference (Sharma, Wu & Dalal 2005).""" + l1, a1, b1 = lab1 + l2, a2, b2 = lab2 + + c1 = math.hypot(a1, b1) + c2 = math.hypot(a2, b2) + c_bar = 0.5 * (c1 + c2) + c_bar7 = c_bar**7 + pow25_7 = 6103515625.0 # 25 ** 7 + g = 0.5 * (1.0 - math.sqrt(c_bar7 / (c_bar7 + pow25_7))) + + a1p = (1.0 + g) * a1 + a2p = (1.0 + g) * a2 + c1p = math.hypot(a1p, b1) + c2p = math.hypot(a2p, b2) + + h1p = 0.0 if (a1p == 0.0 and b1 == 0.0) else math.degrees(math.atan2(b1, a1p)) % 360.0 + h2p = 0.0 if (a2p == 0.0 and b2 == 0.0) else math.degrees(math.atan2(b2, a2p)) % 360.0 + + dlp = l2 - l1 + dcp = c2p - c1p + + c_prod = c1p * c2p + if c_prod == 0.0: + dhp = 0.0 + else: + diff = h2p - h1p + if abs(diff) <= 180.0: + dhp = diff + elif diff > 180.0: + dhp = diff - 360.0 + else: + dhp = diff + 360.0 + + dhp_term = 2.0 * math.sqrt(c_prod) * math.sin(math.radians(0.5 * dhp)) + + lp_bar = 0.5 * (l1 + l2) + cp_bar = 0.5 * (c1p + c2p) + + if c_prod == 0.0: + hp_bar = h1p + h2p + elif abs(h1p - h2p) <= 180.0: + hp_bar = 0.5 * (h1p + h2p) + elif h1p + h2p < 360.0: + hp_bar = 0.5 * (h1p + h2p + 360.0) + else: + hp_bar = 0.5 * (h1p + h2p - 360.0) + + t_factor = ( + 1.0 + - 0.17 * math.cos(math.radians(hp_bar - 30.0)) + + 0.24 * math.cos(math.radians(2.0 * hp_bar)) + + 0.32 * math.cos(math.radians(3.0 * hp_bar + 6.0)) + - 0.20 * math.cos(math.radians(4.0 * hp_bar - 63.0)) ) - \ No newline at end of file + + d_theta = 30.0 * math.exp(-(((hp_bar - 275.0) / 25.0) ** 2)) + cp_bar7 = cp_bar**7 + rc = 2.0 * math.sqrt(cp_bar7 / (cp_bar7 + pow25_7)) + lp_minus_50_sq = (lp_bar - 50.0) ** 2 + sl = 1.0 + (0.015 * lp_minus_50_sq) / math.sqrt(20.0 + lp_minus_50_sq) + sc = 1.0 + 0.045 * cp_bar + sh = 1.0 + 0.015 * cp_bar * t_factor + rt = -math.sin(math.radians(2.0 * d_theta)) * rc + + l_term = dlp / sl + c_term = dcp / sc + h_term = dhp_term / sh + sq = l_term * l_term + c_term * c_term + h_term * h_term + rt * c_term * h_term + return math.sqrt(max(0.0, sq)) + + +def delta_e( + color1: Sequence[int], + color2: Sequence[int], + method: str = "cie2000", +) -> float: + """Calculate the perceptual color difference (Delta E) between two RGB colors. + + A Delta E below ~``1.0`` is typically imperceptible to the human eye; + ``1–2`` is noticeable only on close inspection; ``2–10`` is perceptible at a + glance; ``100`` represents completely opposite colors. + + Parameters: + color1 (tuple): First RGB color ``(r, g, b)`` in ``[0, 255]``. + color2 (tuple): Second RGB color ``(r, g, b)`` in ``[0, 255]``. + method (str): ``"cie2000"`` (default, CIEDE2000 standard) or ``"cie76"`` + (Euclidean distance in CIE 1976 L*a*b*). + + Returns: + float: Non-negative Delta E perceptual color difference. + """ + r1, g1, b1 = _validate_rgb_number_tuple(color1, "color1") + r2, g2, b2 = _validate_rgb_number_tuple(color2, "color2") + if not isinstance(method, str): + raise TypeError(f"method must be a string, got {type(method).__name__}.") + + lab1 = rgb_to_lab(r1, g1, b1) # type: ignore[arg-type] + lab2 = rgb_to_lab(r2, g2, b2) # type: ignore[arg-type] + + mode = method.strip().lower() + if mode == "cie2000": + return _ciede2000(lab1, lab2) + if mode == "cie76": + return math.sqrt( + (lab2[0] - lab1[0]) ** 2 + + (lab2[1] - lab1[1]) ** 2 + + (lab2[2] - lab1[2]) ** 2 + ) + raise ValueError(f"Unknown Delta E method: {method!r}. Use 'cie2000' or 'cie76'.") diff --git a/hued/colors.py b/hued/colors.py index 6f5bca4..96f62d4 100644 --- a/hued/colors.py +++ b/hued/colors.py @@ -1,1399 +1,1580 @@ +"""Named color database and lookup utilities.""" + +from __future__ import annotations + +import random +import re +from typing import Any + +from hued.analysis import _ciede2000 +from hued.conversions import hex_to_rgb as _hex_to_rgb +from hued.conversions import rgb_to_hex as _rgb_to_hex +from hued.conversions import rgb_to_lab as _rgb_to_lab + +__all__ = ["ColorManager"] + +_NORMALIZE_SEP_RE = re.compile(r"[\s\-_]+") + +# Predefined catalog of named colors (canonical name, uppercase #RRGGBB). +_DEFAULT_COLORS: tuple[tuple[str, str], ...] = ( + ('Absolute zero', '#0048BA'), + ('Acid green', '#B0BF1A'), + ('Aero', '#7CB9E8'), + ('Aero blue', '#C9FFE5'), + ('African violet', '#B284BE'), + ('Air Force blue (RAF)', '#5D8AA8'), + ('Air Force blue (USAF)', '#00308F'), + ('Air superiority blue', '#72A0C1'), + ('Alabama crimson', '#AF002A'), + ('Alabaster', '#F2F0E6'), + ('Alice blue', '#F0F8FF'), + ('Alien Armpit', '#84DE02'), + ('Alizarin crimson', '#E32636'), + ('Alloy orange', '#C46210'), + ('Almond', '#EFDECD'), + ('Amaranth', '#E52B50'), + ('Amaranth deep purple', '#9F2B68'), + ('Amaranth pink', '#F19CBB'), + ('Amaranth purple', '#AB274F'), + ('Amaranth red', '#D3212D'), + ('Amazon', '#3B7A57'), + ('Amazonite', '#00C4B0'), + ('Amber', '#FFBF00'), + ('Amber (SAE/ECE)', '#FF7E00'), + ('American rose', '#FF033E'), + ('Amethyst', '#9966CC'), + ('Android green', '#A4C639'), + ('Anti-flash white', '#F2F3F4'), + ('Antique brass', '#CD9575'), + ('Antique bronze', '#665D1E'), + ('Antique fuchsia', '#915C83'), + ('Antique ruby', '#841B2D'), + ('Antique white', '#FAEBD7'), + ('Ao (English)', '#008000'), + ('Apple green', '#8DB600'), + ('Apricot', '#FBCEB1'), + ('Aqua', '#00FFFF'), + ('Aquamarine', '#7FFFD4'), + ('Arctic lime', '#D0FF14'), + ('Army green', '#4B5320'), + ('Arsenic', '#3B444B'), + ('Artichoke', '#8F9779'), + ('Arylide yellow', '#E9D66B'), + ('Ash grey', '#B2BEB5'), + ('Asparagus', '#87A96B'), + ('Atomic tangerine', '#FF9966'), + ('Auburn', '#A52A2A'), + ('Aureolin', '#FDEE00'), + ('AuroMetalSaurus', '#6E7F80'), + ('Avocado', '#568203'), + ('Awesome', '#FF2052'), + ('Aztec Gold', '#C39953'), + ('Azure', '#007FFF'), + ('Azure (web color)', '#F0FFFF'), + ('Azure mist', '#F0FFFF'), + ('Azureish white', '#DBE9F4'), + ("B'dazzled blue", '#2E5894'), + ('Baby blue', '#89CFF0'), + ('Baby blue eyes', '#A1CAF1'), + ('Baby pink', '#F4C2C2'), + ('Baby powder', '#FEFEFA'), + ('Baker-Miller pink', '#FF91AF'), + ('Ball blue', '#21ABCD'), + ('Banana Mania', '#FAE7B5'), + ('Banana yellow', '#FFE135'), + ('Bangladesh green', '#006A4E'), + ('Barbie pink', '#E0218A'), + ('Barn red', '#7C0A02'), + ('Battery Charged Blue', '#1DACD6'), + ('Battleship grey', '#848482'), + ('Bazaar', '#98777B'), + ('Beau blue', '#BCD4E6'), + ('Beaver', '#9F8170'), + ('Begonia', '#FA6E79'), + ('Beige', '#F5F5DC'), + ('Big dip o’ruby', '#9C2542'), + ('Big Foot Feet', '#E88E5A'), + ('Bisque', '#FFE4C4'), + ('Bistre', '#3D2B1F'), + ('Bistre brown', '#967117'), + ('Bitter lemon', '#CAE00D'), + ('Bitter lime', '#BFFF00'), + ('Bittersweet', '#FE6F5E'), + ('Bittersweet shimmer', '#BF4F51'), + ('Black', '#000000'), + ('Black bean', '#3D0C02'), + ('Black Coral', '#54626F'), + ('Black leather jacket', '#253529'), + ('Black olive', '#3B3C36'), + ('Black Shadows', '#BFAFB2'), + ('Blanched almond', '#FFEBCD'), + ('Blast-off bronze', '#A57164'), + ('Bleu de France', '#318CE7'), + ('Blizzard Blue', '#ACE5EE'), + ('Blond', '#FAF0BE'), + ('Blue', '#0000FF'), + ('Blue (Crayola)', '#1F75FE'), + ('Blue (Munsell)', '#0093AF'), + ('Blue (NCS)', '#0087BD'), + ('Blue (Pantone)', '#0018A8'), + ('Blue (pigment)', '#333399'), + ('Blue (RYB)', '#0247FE'), + ('Blue Bell', '#A2A2D0'), + ('Blue Bolt', '#00B9FB'), + ('Blue Jeans', '#5DADEC'), + ('Blue Lagoon', '#ACE5EE'), + ('Blue sapphire', '#126180'), + ('Blue yonder', '#5072A7'), + ('Blue-gray', '#6699CC'), + ('Blue-green', '#0D98BA'), + ('Blue-magenta violet', '#553592'), + ('Blue-violet', '#8A2BE2'), + ('Blueberry', '#4F86F7'), + ('Bluebonnet', '#1C1CF0'), + ('Blush', '#DE5D83'), + ('Bole', '#79443B'), + ('Bondi blue', '#0095B6'), + ('Bone', '#E3DAC9'), + ('Booger Buster', '#DDE26A'), + ('Boston University Red', '#CC0000'), + ('Bottle green', '#006A4E'), + ('Boysenberry', '#873260'), + ('Brandeis blue', '#0070FF'), + ('Brass', '#B5A642'), + ('Brick red', '#CB4154'), + ('Bright cerulean', '#1DACD6'), + ('Bright green', '#66FF00'), + ('Bright lavender', '#BF94E4'), + ('Bright lilac', '#D891EF'), + ('Bright maroon', '#C32148'), + ('Bright navy blue', '#1974D2'), + ('Bright pink', '#FF007F'), + ('Bright turquoise', '#08E8DE'), + ('Bright ube', '#D19FE8'), + ('Bright Yellow (Crayola)', '#FFAA1D'), + ('Brilliant azure', '#3399FF'), + ('Brilliant lavender', '#F4BBFF'), + ('Brilliant rose', '#FF55A3'), + ('Brink pink', '#FB607F'), + ('British racing green', '#004225'), + ('Bronze', '#CD7F32'), + ('Bronze Yellow', '#737000'), + ('Brown', '#A52A2A'), + ('Brown (traditional)', '#964B00'), + ('Brown (web)', '#A52A2A'), + ('Brown Sugar', '#AF6E4D'), + ('Brown Yellow', '#CC9966'), + ('Brown-nose', '#6B4423'), + ('Brunswick green', '#1B4D3E'), + ('Bubble gum', '#FFC1CC'), + ('Bubbles', '#E7FEFF'), + ('Bud green', '#7BB661'), + ('Buff', '#F0DC82'), + ('Bulgarian rose', '#480607'), + ('Burgundy', '#800020'), + ('Burlywood', '#DEB887'), + ('Burnished Brown', '#A17A74'), + ('Burnt orange', '#CC5500'), + ('Burnt sienna', '#E97451'), + ('Burnt umber', '#8A3324'), + ('Byzantine', '#BD33A4'), + ('Byzantium', '#702963'), + ('Cadet', '#536872'), + ('Cadet blue', '#5F9EA0'), + ('Cadet grey', '#91A3B0'), + ('Cadmium green', '#006B3C'), + ('Cadmium orange', '#ED872D'), + ('Cadmium red', '#E30022'), + ('Cadmium yellow', '#FFF600'), + ('Café au lait', '#A67B5B'), + ('Café noir', '#4B3621'), + ('Cal Poly Pomona green', '#1E4D2B'), + ('Cambridge Blue', '#A3C1AD'), + ('Camel', '#C19A6B'), + ('Cameo pink', '#EFBBCC'), + ('Camouflage green', '#78866B'), + ('Canary', '#FFFF99'), + ('Canary yellow', '#FFEF00'), + ('Candy apple red', '#FF0800'), + ('Candy pink', '#E4717A'), + ('Capri', '#00BFFF'), + ('Caput mortuum', '#592720'), + ('Cardinal', '#C41E3A'), + ('Caribbean green', '#00CC99'), + ('Carmine', '#960018'), + ('Carmine (M&P)', '#D70040'), + ('Carmine pink', '#EB4C42'), + ('Carmine red', '#FF0038'), + ('Carnation pink', '#FFA6C9'), + ('Carnelian', '#B31B1B'), + ('Carolina blue', '#56A0D3'), + ('Carrot orange', '#ED9121'), + ('Castleton green', '#00563F'), + ('Catalina blue', '#062A78'), + ('Catawba', '#703642'), + ('Cedar Chest', '#C95A49'), + ('Ceil', '#92A1CF'), + ('Celadon', '#ACE1AF'), + ('Celadon blue', '#007BA7'), + ('Celadon green', '#2F847C'), + ('Celeste', '#B2FFFF'), + ('Celestial blue', '#4997D0'), + ('Cerise', '#DE3163'), + ('Cerise pink', '#EC3B83'), + ('Cerulean', '#007BA7'), + ('Cerulean blue', '#2A52BE'), + ('Cerulean frost', '#6D9BC3'), + ('CG Blue', '#007AA5'), + ('CG Red', '#E03C31'), + ('Chamoisee', '#A0785A'), + ('Champagne', '#F7E7CE'), + ('Champagne pink', '#F1DDCF'), + ('Charcoal', '#36454F'), + ('Charleston green', '#232B2B'), + ('Charm pink', '#E68FAC'), + ('Chartreuse', '#7FFF00'), + ('Chartreuse (traditional)', '#DFFF00'), + ('Chartreuse (web)', '#7FFF00'), + ('Cherry', '#DE3163'), + ('Cherry blossom pink', '#FFB7C5'), + ('Chestnut', '#954535'), + ('China pink', '#DE6FA1'), + ('China rose', '#A8516E'), + ('Chinese red', '#AA381E'), + ('Chinese violet', '#856088'), + ('Chlorophyll green', '#4AFF00'), + ('Chocolate', '#D2691E'), + ('Chocolate (traditional)', '#7B3F00'), + ('Chocolate (web)', '#D2691E'), + ('Chrome yellow', '#FFA700'), + ('Cinereous', '#98817B'), + ('Cinnabar', '#E34234'), + ('Cinnamon', '#D2691E'), + ('Cinnamon Satin', '#CD607E'), + ('Citrine', '#E4D00A'), + ('Citron', '#9FA91F'), + ('Claret', '#7F1734'), + ('Classic rose', '#FBCCE7'), + ('Cobalt Blue', '#0047AB'), + ('Cocoa brown', '#D2691E'), + ('Coconut', '#965A3E'), + ('Coffee', '#6F4E37'), + ('Columbia Blue', '#C4D8E2'), + ('Congo pink', '#F88379'), + ('Cool Black', '#002E63'), + ('Cool grey', '#8C92AC'), + ('Copper', '#B87333'), + ('Copper (Crayola)', '#DA8A67'), + ('Copper penny', '#AD6F69'), + ('Copper red', '#CB6D51'), + ('Copper rose', '#996666'), + ('Coquelicot', '#FF3800'), + ('Coral', '#FF7F50'), + ('Coral pink', '#F88379'), + ('Coral red', '#FF4040'), + ('Coral Reef', '#FD7C6E'), + ('Cordovan', '#893F45'), + ('Corn', '#FBEC5D'), + ('Cornell Red', '#B31B1B'), + ('Cornflower blue', '#6495ED'), + ('Cornsilk', '#FFF8DC'), + ('Cosmic Cobalt', '#2E2D88'), + ('Cosmic latte', '#FFF8E7'), + ('Cotton candy', '#FFBCD9'), + ('Coyote brown', '#81613C'), + ('Cream', '#FFFDD0'), + ('Crimson', '#DC143C'), + ('Crimson glory', '#BE0032'), + ('Crimson red', '#990000'), + ('Cultured', '#F5F5F5'), + ('Cyan', '#00FFFF'), + ('Cyan (process)', '#00B7EB'), + ('Cyan azure', '#4E82B4'), + ('Cyan cobalt blue', '#28589C'), + ('Cyan cornflower blue', '#188BC2'), + ('Cyan-blue azure', '#4682BF'), + ('Cyber grape', '#58427C'), + ('Cyber yellow', '#FFD300'), + ('Cyclamen', '#F56FA1'), + ('Daffodil', '#FFFF31'), + ('Dandelion', '#F0E130'), + ('Dark blue', '#00008B'), + ('Dark blue-gray', '#666699'), + ('Dark brown', '#654321'), + ('Dark brown-tangelo', '#88654E'), + ('Dark byzantium', '#5D3954'), + ('Dark candy apple red', '#A40000'), + ('Dark cerulean', '#08457E'), + ('Dark chestnut', '#986960'), + ('Dark coral', '#CD5B45'), + ('Dark cyan', '#008B8B'), + ('Dark electric blue', '#536878'), + ('Dark goldenrod', '#B8860B'), + ('Dark gray', '#A9A9A9'), + ('Dark gray (X11)', '#A9A9A9'), + ('Dark green', '#013220'), + ('Dark green (X11)', '#006400'), + ('Dark grey', '#A9A9A9'), + ('Dark gunmetal', '#1F262A'), + ('Dark imperial blue', '#00416A'), + ('Dark imperial blue (electric)', '#00147E'), + ('Dark jungle green', '#1A2421'), + ('Dark khaki', '#BDB76B'), + ('Dark lava', '#483C32'), + ('Dark lavender', '#734F96'), + ('Dark liver', '#534B4F'), + ('Dark liver (horses)', '#543D37'), + ('Dark magenta', '#8B008B'), + ('Dark medium gray', '#A9A9A9'), + ('Dark midnight blue', '#003366'), + ('Dark moss green', '#4A5D23'), + ('Dark olive green', '#556B2F'), + ('Dark orange', '#FF8C00'), + ('Dark orchid', '#9932CC'), + ('Dark pastel blue', '#779ECB'), + ('Dark pastel green', '#03C03C'), + ('Dark pastel purple', '#966FD6'), + ('Dark pastel red', '#C23B22'), + ('Dark pink', '#E75480'), + ('Dark powder blue', '#003399'), + ('Dark puce', '#4F3A3C'), + ('Dark purple', '#301934'), + ('Dark raspberry', '#872657'), + ('Dark red', '#8B0000'), + ('Dark salmon', '#E9967A'), + ('Dark scarlet', '#560319'), + ('Dark sea green', '#8FBC8F'), + ('Dark sienna', '#3C1414'), + ('Dark sky blue', '#8CBED6'), + ('Dark slate blue', '#483D8B'), + ('Dark slate gray', '#2F4F4F'), + ('Dark slate grey', '#2F4F4F'), + ('Dark spring green', '#177245'), + ('Dark tan', '#918151'), + ('Dark tangerine', '#FFA812'), + ('Dark taupe', '#483C32'), + ('Dark terra cotta', '#CC4E5C'), + ('Dark turquoise', '#00CED1'), + ('Dark vanilla', '#D1BEA8'), + ('Dark violet', '#9400D3'), + ('Dark yellow', '#9B870C'), + ('Dartmouth green', '#00703C'), + ("Davy's grey", '#555555'), + ('Debian red', '#D70A53'), + ('Deep aquamarine', '#40826D'), + ('Deep carmine', '#A9203E'), + ('Deep carmine pink', '#EF3038'), + ('Deep carrot orange', '#E9692C'), + ('Deep cerise', '#DA3287'), + ('Deep champagne', '#FAD6A5'), + ('Deep chestnut', '#B94E48'), + ('Deep coffee', '#704241'), + ('Deep fuchsia', '#C154C1'), + ('Deep Green', '#056608'), + ('Deep green-cyan turquoise', '#0E7C61'), + ('Deep jungle green', '#004B49'), + ('Deep koamaru', '#333366'), + ('Deep lemon', '#F5C71A'), + ('Deep lilac', '#9955BB'), + ('Deep magenta', '#CC00CC'), + ('Deep maroon', '#820000'), + ('Deep mauve', '#D473D4'), + ('Deep moss green', '#355E3B'), + ('Deep peach', '#FFCBA4'), + ('Deep pink', '#FF1493'), + ('Deep puce', '#A95C68'), + ('Deep Red', '#850101'), + ('Deep ruby', '#843F5B'), + ('Deep saffron', '#FF9933'), + ('Deep sky blue', '#00BFFF'), + ('Deep Space Sparkle', '#4A646C'), + ('Deep spring bud', '#556B2F'), + ('Deep Taupe', '#7E5E60'), + ('Deep Tuscan red', '#66424D'), + ('Deep violet', '#330066'), + ('Deer', '#BA8759'), + ('Denim', '#1560BD'), + ('Denim Blue', '#2243B6'), + ('Desaturated cyan', '#669999'), + ('Desert', '#C19A6B'), + ('Desert sand', '#EDC9AF'), + ('Desire', '#EA3C53'), + ('Diamond', '#B9F2FF'), + ('Dim gray', '#696969'), + ('Dim grey', '#696969'), + ('Dingy Dungeon', '#C53151'), + ('Dirt', '#9B7653'), + ('Dodger blue', '#1E90FF'), + ('Dogwood rose', '#D71868'), + ('Dollar bill', '#85BB65'), + ('Dolphin Gray', '#828E84'), + ('Donkey brown', '#664C28'), + ('Drab', '#967117'), + ('Duke blue', '#00009C'), + ('Dust storm', '#E5CCC9'), + ('Dutch white', '#EFDFBB'), + ('Earth yellow', '#E1A95F'), + ('Ebony', '#555D50'), + ('Ecru', '#C2B280'), + ('Eerie black', '#1B1B1B'), + ('Eggplant', '#614051'), + ('Eggshell', '#F0EAD6'), + ('Egyptian blue', '#1034A6'), + ('Electric blue', '#7DF9FF'), + ('Electric crimson', '#FF003F'), + ('Electric cyan', '#00FFFF'), + ('Electric green', '#00FF00'), + ('Electric indigo', '#6F00FF'), + ('Electric lavender', '#F4BBFF'), + ('Electric lime', '#CCFF00'), + ('Electric purple', '#BF00FF'), + ('Electric ultramarine', '#3F00FF'), + ('Electric violet', '#8F00FF'), + ('Electric yellow', '#FFFF33'), + ('Emerald', '#50C878'), + ('Eminence', '#6C3082'), + ('English green', '#1B4D3E'), + ('English lavender', '#B48395'), + ('English red', '#AB4B52'), + ('English vermillion', '#CC474B'), + ('English violet', '#563C5C'), + ('Eton blue', '#96C8A2'), + ('Eucalyptus', '#44D7A8'), + ('Fallow', '#C19A6B'), + ('Falu red', '#801818'), + ('Fandango', '#B53389'), + ('Fandango pink', '#DE5285'), + ('Fashion fuchsia', '#F400A1'), + ('Fawn', '#E5AA70'), + ('Feldgrau', '#4D5D53'), + ('Feldspar', '#FDD5B1'), + ('Fern green', '#4F7942'), + ('Ferrari Red', '#FF2800'), + ('Field drab', '#6C541E'), + ('Fiery Rose', '#FF5470'), + ('Fire engine red', '#CE2029'), + ('Firebrick', '#B22222'), + ('Flame', '#E25822'), + ('Flamingo pink', '#FC8EAC'), + ('Flattery', '#6B4423'), + ('Flavescent', '#F7E98E'), + ('Flax', '#EEDC82'), + ('Flirt', '#A2006D'), + ('Floral white', '#FFFAF0'), + ('Fluorescent orange', '#FFBF00'), + ('Fluorescent pink', '#FF1493'), + ('Fluorescent yellow', '#CCFF00'), + ('Folly', '#FF004F'), + ('Forest green', '#228B22'), + ('Forest green (traditional)', '#014421'), + ('Forest green (web)', '#228B22'), + ('French beige', '#A67B5B'), + ('French bistre', '#856D4D'), + ('French blue', '#0072BB'), + ('French fuchsia', '#FD3F92'), + ('French lilac', '#86608E'), + ('French lime', '#9EFD38'), + ('French mauve', '#D473D4'), + ('French pink', '#FD6C9E'), + ('French plum', '#811453'), + ('French puce', '#4E1609'), + ('French raspberry', '#C72C48'), + ('French rose', '#F64A8A'), + ('French sky blue', '#77B5FE'), + ('French violet', '#8806CE'), + ('French wine', '#AC1E44'), + ('Fresh Air', '#A6E7FF'), + ('Frostbite', '#E936A7'), + ('Fuchsia', '#FF00FF'), + ('Fuchsia (Crayola)', '#C154C1'), + ('Fuchsia pink', '#FF77FF'), + ('Fuchsia purple', '#CC397B'), + ('Fuchsia rose', '#C74375'), + ('Fulvous', '#E48400'), + ('Fuzzy Wuzzy', '#CC6666'), + ('Gainsboro', '#DCDCDC'), + ('Gamboge', '#E49B0F'), + ('Gamboge orange (brown)', '#996600'), + ('Gargoyle Gas', '#FFDF46'), + ('Generic viridian', '#007F66'), + ('Ghost white', '#F8F8FF'), + ("Giant's Club", '#B05C52'), + ('Giants orange', '#FE5A1D'), + ('Ginger', '#B06500'), + ('Glaucous', '#6082B6'), + ('Glitter', '#E6E8FA'), + ('Glossy Grape', '#AB92B3'), + ('GO green', '#00AB66'), + ('Gold', '#FFD700'), + ('Gold (metallic)', '#D4AF37'), + ('Gold (web) (Golden)', '#FFD700'), + ('Gold Fusion', '#85754E'), + ('Golden brown', '#996515'), + ('Golden poppy', '#FCC200'), + ('Golden yellow', '#FFDF00'), + ('Goldenrod', '#DAA520'), + ('Granite Gray', '#676767'), + ('Granny Smith Apple', '#A8E4A0'), + ('Grape', '#6F2DA8'), + ('Gray', '#808080'), + ('Gray (HTML/CSS gray)', '#808080'), + ('Gray (X11 gray)', '#BEBEBE'), + ('Gray-asparagus', '#465945'), + ('Gray-blue', '#8C92AC'), + ('Green', '#008000'), + ('Green (Color Wheel) (X11 green)', '#00FF00'), + ('Green (Crayola)', '#1CAC78'), + ('Green (HTML/CSS color)', '#008000'), + ('Green (Munsell)', '#00A877'), + ('Green (NCS)', '#009F6B'), + ('Green (Pantone)', '#00AD43'), + ('Green (pigment)', '#00A550'), + ('Green (RYB)', '#66B032'), + ('Green Lizard', '#A7F432'), + ('Green Sheen', '#6EAEA1'), + ('Green-blue', '#1164B4'), + ('Green-cyan', '#009966'), + ('Green-yellow', '#ADFF2F'), + ('Grey', '#808080'), + ('Grizzly', '#885818'), + ('Grullo', '#A99A86'), + ('Gunmetal', '#2A3439'), + ('Guppie green', '#00FF7F'), + ('Halayà úbe', '#663854'), + ('Han blue', '#446CCF'), + ('Han purple', '#5218FA'), + ('Hansa yellow', '#E9D66B'), + ('Harlequin', '#3FFF00'), + ('Harlequin green', '#46CB18'), + ('Harvard crimson', '#C90016'), + ('Harvest gold', '#DA9100'), + ('Heart Gold', '#808000'), + ('Heat Wave', '#FF7A00'), + ('Heidelberg Red', '#960018'), + ('Heliotrope', '#DF73FF'), + ('Heliotrope gray', '#AA98A9'), + ('Heliotrope magenta', '#AA00BB'), + ('Hollywood cerise', '#F400A1'), + ('Honeydew', '#F0FFF0'), + ('Honolulu blue', '#006DB0'), + ("Hooker's green", '#49796B'), + ('Hot magenta', '#FF1DCE'), + ('Hot pink', '#FF69B4'), + ('Hunter green', '#355E3B'), + ('Iceberg', '#71A6D2'), + ('Icterine', '#FCF75E'), + ('Iguana Green', '#71BC78'), + ('Illuminating Emerald', '#319177'), + ('Imperial', '#602F6B'), + ('Imperial blue', '#002395'), + ('Imperial purple', '#66023C'), + ('Imperial red', '#ED2939'), + ('Inchworm', '#B2EC5D'), + ('Independence', '#4C516D'), + ('India green', '#138808'), + ('Indian red', '#CD5C5C'), + ('Indian yellow', '#E3A857'), + ('Indigo', '#4B0082'), + ('Indigo (web)', '#4B0082'), + ('Indigo dye', '#091F92'), + ('Infra Red', '#FF496C'), + ('Interdimensional Blue', '#360CCC'), + ('International Klein Blue', '#002FA7'), + ('International orange (aerospace)', '#FF4F00'), + ('International orange (engineering)', '#BA160C'), + ('International orange (Golden Gate Bridge)', '#C0362C'), + ('Iris', '#5A4FCF'), + ('Irresistible', '#B3446C'), + ('Isabelline', '#F4F0EC'), + ('Islamic green', '#009000'), + ('Italian sky blue', '#B2FFFF'), + ('Ivory', '#FFFFF0'), + ('Jade', '#00A86B'), + ('Japanese carmine', '#9D2933'), + ('Japanese indigo', '#264348'), + ('Japanese violet', '#5B3256'), + ('Jasmine', '#F8DE7E'), + ('Jasper', '#D73B3E'), + ('Jazzberry jam', '#A50B5E'), + ('Jelly Bean', '#DA614E'), + ('Jet', '#343434'), + ('Jonquil', '#F4CA16'), + ('Jordy blue', '#8AB9F1'), + ('June bud', '#BDDA57'), + ('Jungle green', '#29AB87'), + ('Kelly green', '#4CBB17'), + ('Kenyan copper', '#7C1C05'), + ('Keppel', '#3AB09E'), + ('Key Lime', '#E8F48C'), + ('Khaki', '#F0E68C'), + ('Khaki (HTML/CSS) (Khaki)', '#C3B091'), + ('Khaki (X11) (Light khaki)', '#F0E68C'), + ('Kiwi', '#8EE53F'), + ('Kobe', '#882D17'), + ('Kobi', '#E79FC4'), + ('Kobicha', '#6B4423'), + ('Kombu green', '#354230'), + ('KSU Purple', '#512888'), + ('KU Crimson', '#E8000D'), + ('La Salle Green', '#087830'), + ('Languid lavender', '#D6CADD'), + ('Lapis lazuli', '#26619C'), + ('Laser Lemon', '#FFFF66'), + ('Laurel green', '#A9BA9D'), + ('Lava', '#CF1020'), + ('Lavender', '#E6E6FA'), + ('Lavender (floral)', '#B57EDC'), + ('Lavender (web)', '#E6E6FA'), + ('Lavender blue', '#CCCCFF'), + ('Lavender blush', '#FFF0F5'), + ('Lavender gray', '#C4C3D0'), + ('Lavender indigo', '#9457EB'), + ('Lavender magenta', '#EE82EE'), + ('Lavender mist', '#E6E6FA'), + ('Lavender pink', '#FBAED2'), + ('Lavender purple', '#967BB6'), + ('Lavender rose', '#FBA0E3'), + ('Lawn green', '#7CFC00'), + ('Lemon', '#FFF700'), + ('Lemon chiffon', '#FFFACD'), + ('Lemon curry', '#CCA01D'), + ('Lemon glacier', '#FDFF00'), + ('Lemon lime', '#E3FF00'), + ('Lemon meringue', '#F6EABE'), + ('Lemon yellow', '#FFF44F'), + ('Liberty', '#545AA7'), + ('Licorice', '#1A1110'), + ('Light apricot', '#FDD5B1'), + ('Light blue', '#ADD8E6'), + ('Light brown', '#B5651D'), + ('Light carmine pink', '#E66771'), + ('Light cobalt blue', '#88ACE0'), + ('Light coral', '#F08080'), + ('Light cornflower blue', '#93CCEA'), + ('Light crimson', '#F56991'), + ('Light cyan', '#E0FFFF'), + ('Light deep pink', '#FF5CCD'), + ('Light French beige', '#C8AD7F'), + ('Light fuchsia pink', '#F984EF'), + ('Light goldenrod yellow', '#FAFAD2'), + ('Light gray', '#D3D3D3'), + ('Light grayish magenta', '#CC99CC'), + ('Light green', '#90EE90'), + ('Light grey', '#D3D3D3'), + ('Light hot pink', '#FFB3DE'), + ('Light khaki', '#F0E68C'), + ('Light medium orchid', '#D39BCB'), + ('Light moss green', '#ADDFAD'), + ('Light orchid', '#E6A8D7'), + ('Light pastel purple', '#B19CD9'), + ('Light pink', '#FFB6C1'), + ('Light red ochre', '#E97451'), + ('Light salmon', '#FFA07A'), + ('Light salmon pink', '#FF9999'), + ('Light sea green', '#20B2AA'), + ('Light sky blue', '#87CEFA'), + ('Light slate gray', '#778899'), + ('Light slate grey', '#778899'), + ('Light steel blue', '#B0C4DE'), + ('Light taupe', '#B38B6D'), + ('Light Thulian pink', '#E68FAC'), + ('Light yellow', '#FFFFE0'), + ('Lilac', '#C8A2C8'), + ('Lilac Luster', '#AE98AA'), + ('Lime', '#00FF00'), + ('Lime (color wheel)', '#BFFF00'), + ('Lime (web) (X11 green)', '#00FF00'), + ('Lime green', '#32CD32'), + ('Limerick', '#9DC209'), + ('Lincoln green', '#195905'), + ('Linen', '#FAF0E6'), + ('Liseran Purple', '#DE6FA1'), + ('Little boy blue', '#6CA0DC'), + ('Liver', '#674C47'), + ('Liver (dogs)', '#B86D29'), + ('Liver (organ)', '#6C2E1F'), + ('Liver chestnut', '#987456'), + ('Livid', '#6699CC'), + ('Lumber', '#FFE4CD'), + ('Lust', '#E62020'), + ('Maastricht Blue', '#001C3D'), + ('Macaroni and Cheese', '#FFBD88'), + ('Madder Lake', '#CC3336'), + ('Magenta', '#FF00FF'), + ('Magenta (Crayola)', '#FF55A3'), + ('Magenta (dye)', '#CA1F7B'), + ('Magenta (Pantone)', '#D0417E'), + ('Magenta (process)', '#FF0090'), + ('Magenta haze', '#9F4576'), + ('Magenta-pink', '#CC338B'), + ('Magic mint', '#AAF0D1'), + ('Magic Potion', '#FF4466'), + ('Magnolia', '#F8F4FF'), + ('Mahogany', '#C04000'), + ('Maize', '#FBEC5D'), + ('Majorelle Blue', '#6050DC'), + ('Malachite', '#0BDA51'), + ('Manatee', '#979AAA'), + ('Mandarin', '#F37A48'), + ('Mango Tango', '#FF8243'), + ('Mantis', '#74C365'), + ('Mardi Gras', '#880085'), + ('Marigold', '#EAA221'), + ('Maroon', '#800000'), + ('Maroon (Crayola)', '#C32148'), + ('Maroon (HTML/CSS)', '#800000'), + ('Maroon (X11)', '#B03060'), + ('Mauve', '#E0B0FF'), + ('Mauve taupe', '#915F6D'), + ('Mauvelous', '#EF98AA'), + ('Maximum Blue', '#47ABCC'), + ('Maximum Blue Green', '#30BFBF'), + ('Maximum Blue Purple', '#ACACE6'), + ('Maximum Green', '#5E8C31'), + ('Maximum Green Yellow', '#D9E650'), + ('Maximum Purple', '#733380'), + ('Maximum Red', '#D92121'), + ('Maximum Red Purple', '#A63A79'), + ('Maximum Yellow', '#FAFA37'), + ('Maximum Yellow Red', '#F2BA49'), + ('May green', '#4C9141'), + ('Maya blue', '#73C2FB'), + ('Meat brown', '#E5B73B'), + ('Medium aquamarine', '#66DDAA'), + ('Medium blue', '#0000CD'), + ('Medium candy apple red', '#E2062C'), + ('Medium carmine', '#AF4035'), + ('Medium champagne', '#F3E5AB'), + ('Medium electric blue', '#035096'), + ('Medium jungle green', '#1C352D'), + ('Medium lavender magenta', '#DDA0DD'), + ('Medium orchid', '#BA55D3'), + ('Medium Persian blue', '#0067A5'), + ('Medium purple', '#9370DB'), + ('Medium red-violet', '#BB3385'), + ('Medium ruby', '#AA4069'), + ('Medium sea green', '#3CB371'), + ('Medium sky blue', '#80DAEB'), + ('Medium slate blue', '#7B68EE'), + ('Medium spring bud', '#C9DC87'), + ('Medium spring green', '#00FA9A'), + ('Medium taupe', '#674C47'), + ('Medium turquoise', '#48D1CC'), + ('Medium Tuscan red', '#79443B'), + ('Medium vermilion', '#D9603B'), + ('Medium violet-red', '#C71585'), + ('Mellow apricot', '#F8B878'), + ('Mellow yellow', '#F8DE7E'), + ('Melon', '#FDBCB4'), + ('Metallic Seaweed', '#0A7E8C'), + ('Metallic Sunburst', '#9C7C38'), + ('Mexican pink', '#E4007C'), + ('Middle Blue', '#7ED4E6'), + ('Middle Blue Green', '#8DD9CC'), + ('Middle Blue Purple', '#8B72BE'), + ('Middle Green', '#4D8C57'), + ('Middle Green Yellow', '#ACBF60'), + ('Middle Purple', '#D982B5'), + ('Middle Red', '#E58E73'), + ('Middle Red Purple', '#A55353'), + ('Middle red purple (Munsell)', '#210837'), + ('Middle Yellow', '#FFEB00'), + ('Middle Yellow Red', '#ECB176'), + ('Midnight', '#702670'), + ('Midnight blue', '#191970'), + ('Midnight green (eagle green)', '#004953'), + ('Mikado yellow', '#FFC40C'), + ('Milk', '#FDFFF5'), + ('Mimi Pink', '#FFDAE9'), + ('Mindaro', '#E3F988'), + ('Ming', '#36747D'), + ('Minion Yellow', '#F5E050'), + ('Mint', '#3EB489'), + ('Mint cream', '#F5FFFA'), + ('Mint green', '#98FF98'), + ('Misty Moss', '#BBB477'), + ('Misty rose', '#FFE4E1'), + ('Moccasin', '#FAEBD7'), + ('Mode beige', '#967117'), + ('Moonstone blue', '#73A9C2'), + ('Mordant red 19', '#AE0C00'), + ('Moss green', '#8A9A5B'), + ('Mountain Meadow', '#30BA8F'), + ('Mountbatten pink', '#997A8D'), + ('MSU Green', '#18453B'), + ('Mughal green', '#306030'), + ('Mulberry', '#C54B8C'), + ("Mummy's Tomb", '#828E84'), + ('Mustard', '#FFDB58'), + ('Myrtle green', '#317873'), + ('Mystic', '#D65282'), + ('Mystic Maroon', '#AD4379'), + ('Nadeshiko pink', '#F6ADC6'), + ('Napier green', '#2A8000'), + ('Naples yellow', '#FADA5E'), + ('Navajo white', '#FFDEAD'), + ('Navy', '#000080'), + ('Navy purple', '#9457EB'), + ('Neon Carrot', '#FFA343'), + ('Neon fuchsia', '#FE4164'), + ('Neon green', '#39FF14'), + ('New Car', '#214FC6'), + ('New York pink', '#D7837F'), + ('Nickel', '#727472'), + ('Non-photo blue', '#A4DDED'), + ('North Texas Green', '#059033'), + ('Nyanza', '#E9FFDB'), + ('Ocean Blue', '#4F42B5'), + ('Ocean Boat Blue', '#0077BE'), + ('Ocean Green', '#48BF91'), + ('Ochre', '#CC7722'), + ('Office green', '#008000'), + ('Ogre Odor', '#FD5240'), + ('Old burgundy', '#43302E'), + ('Old gold', '#CFB53B'), + ('Old heliotrope', '#563C5C'), + ('Old lace', '#FDF5E6'), + ('Old lavender', '#796878'), + ('Old mauve', '#673147'), + ('Old moss green', '#867E36'), + ('Old rose', '#C08081'), + ('Old silver', '#848482'), + ('Olive', '#808000'), + ('Olive drab', '#6B8E23'), + ('Olive Drab #7', '#3C341F'), + ('Olive Drab (#3)', '#6B8E23'), + ('Olivine', '#9AB973'), + ('Onyx', '#353839'), + ('Opera mauve', '#B784A7'), + ('Orange', '#FFA500'), + ('Orange (color wheel)', '#FF7F00'), + ('Orange (Crayola)', '#FF7538'), + ('Orange (Pantone)', '#FF5800'), + ('Orange (RYB)', '#FB9902'), + ('Orange (web)', '#FFA500'), + ('Orange peel', '#FF9F00'), + ('Orange Soda', '#FA5B3D'), + ('Orange-red', '#FF4500'), + ('Orange-yellow', '#F8D568'), + ('Orchid', '#DA70D6'), + ('Orchid pink', '#F2BDCD'), + ('Orioles orange', '#FB4F14'), + ('Otter brown', '#654321'), + ('OU Crimson Red', '#990000'), + ('Outer Space', '#414A4C'), + ('Outrageous Orange', '#FF6E4A'), + ('Oxford Blue', '#002147'), + ('Pacific Blue', '#1CA9C9'), + ('Pakistan green', '#006600'), + ('Palatinate blue', '#273BE2'), + ('Palatinate purple', '#682860'), + ('Pale aqua', '#BCD4E6'), + ('Pale blue', '#AFEEEE'), + ('Pale brown', '#987654'), + ('Pale carmine', '#AF4035'), + ('Pale cerulean', '#9BC4E2'), + ('Pale chestnut', '#DDADAF'), + ('Pale copper', '#DA8A67'), + ('Pale cornflower blue', '#ABCDEF'), + ('Pale cyan', '#87D3F8'), + ('Pale gold', '#E6BE8A'), + ('Pale goldenrod', '#EEE8AA'), + ('Pale green', '#98FB98'), + ('Pale lavender', '#DCD0FF'), + ('Pale magenta', '#F984E5'), + ('Pale magenta-pink', '#FF99CC'), + ('Pale pink', '#FADADD'), + ('Pale plum', '#DDA0DD'), + ('Pale red-violet', '#DB7093'), + ('Pale robin egg blue', '#96DED1'), + ('Pale silver', '#C9C0BB'), + ('Pale spring bud', '#ECEBBD'), + ('Pale taupe', '#BC987E'), + ('Pale turquoise', '#AFEEEE'), + ('Pale violet', '#CC99FF'), + ('Pale violet-red', '#DB7093'), + ('Palm Leaf', '#6F9940'), + ('Pansy purple', '#78184A'), + ('Paolo Veronese green', '#009B7D'), + ('Papaya whip', '#FFEFD5'), + ('Paradise pink', '#E63E62'), + ('Paris Green', '#50C878'), + ('Parrot Pink', '#D998A0'), + ('Pastel blue', '#AEC6CF'), + ('Pastel brown', '#836953'), + ('Pastel gray', '#CFCFC4'), + ('Pastel green', '#77DD77'), + ('Pastel magenta', '#F49AC2'), + ('Pastel orange', '#FFB347'), + ('Pastel pink', '#DEA5A4'), + ('Pastel purple', '#B39EB5'), + ('Pastel red', '#FF6961'), + ('Pastel violet', '#CB99C9'), + ('Pastel yellow', '#FDFD96'), + ('Patriarch', '#800080'), + ("Payne's grey", '#536878'), + ('Peach', '#FFE5B4'), + ('Peach (Crayola)', '#FFCBA4'), + ('Peach puff', '#FFDAB9'), + ('Peach-orange', '#FFCC99'), + ('Peach-yellow', '#FADFAD'), + ('Pear', '#D1E231'), + ('Pearl', '#EAE0C8'), + ('Pearl Aqua', '#88D8C0'), + ('Pearly purple', '#B768A2'), + ('Peridot', '#E6E200'), + ('Periwinkle', '#CCCCFF'), + ('Permanent Geranium Lake', '#E12C2C'), + ('Persian blue', '#1C39BB'), + ('Persian green', '#00A693'), + ('Persian indigo', '#32127A'), + ('Persian orange', '#D99058'), + ('Persian pink', '#F77FBE'), + ('Persian plum', '#701C1C'), + ('Persian red', '#CC3333'), + ('Persian rose', '#FE28A2'), + ('Persimmon', '#EC5800'), + ('Peru', '#CD853F'), + ('Pewter Blue', '#8BA8B7'), + ('Phlox', '#DF00FF'), + ('Phthalo blue', '#000F89'), + ('Phthalo green', '#123524'), + ('Picton blue', '#45B1E8'), + ('Pictorial carmine', '#C30B4E'), + ('Piggy pink', '#FDDDE6'), + ('Pine green', '#01796F'), + ('Pineapple', '#563C5C'), + ('Pink', '#FFC0CB'), + ('Pink (Pantone)', '#D74894'), + ('Pink Flamingo', '#FC74FD'), + ('Pink lace', '#FFDDF4'), + ('Pink lavender', '#D8B2D1'), + ('Pink pearl', '#E7ACCF'), + ('Pink raspberry', '#980036'), + ('Pink Sherbet', '#F78FA7'), + ('Pink-orange', '#FF9966'), + ('Pistachio', '#93C572'), + ('Pixie Powder', '#391285'), + ('Platinum', '#E5E4E2'), + ('Plum', '#8E4585'), + ('Plum (web)', '#DDA0DD'), + ('Plump Purple', '#5946B2'), + ('Polished Pine', '#5DA493'), + ('Pomp and Power', '#86608E'), + ('Popstar', '#BE4F62'), + ('Portland Orange', '#FF5A36'), + ('Powder blue', '#B0E0E6'), + ('Princess Perfume', '#FF85CF'), + ('Princeton orange', '#F58025'), + ('Prune', '#701C1C'), + ('Prussian blue', '#003153'), + ('Psychedelic purple', '#DF00FF'), + ('Puce', '#CC8899'), + ('Puce red', '#722F37'), + ('Pullman Brown (UPS Brown)', '#644117'), + ('Pullman Green', '#3B331C'), + ('Pumpkin', '#FF7518'), + ('Purple', '#800080'), + ('Purple (HTML)', '#800080'), + ('Purple (Munsell)', '#9F00C5'), + ('Purple (X11)', '#A020F0'), + ('Purple Heart', '#69359C'), + ('Purple mountain majesty', '#9678B6'), + ('Purple navy', '#4E5180'), + ('Purple pizzazz', '#FE4EDA'), + ('Purple Plum', '#9C51B6'), + ('Purple taupe', '#50404D'), + ('Purpureus', '#9A4EAE'), + ('Quartz', '#51484F'), + ('Queen blue', '#436B95'), + ('Queen pink', '#E8CCD7'), + ('Quick Silver', '#A6A6A6'), + ('Quinacridone magenta', '#8E3A59'), + ('Rackley', '#5D8AA8'), + ('Radical Red', '#FF355E'), + ('Raisin black', '#242124'), + ('Rajah', '#FBAB60'), + ('Raspberry', '#E30B5D'), + ('Raspberry glace', '#915F6D'), + ('Raspberry pink', '#E25098'), + ('Raspberry rose', '#B3446C'), + ('Raw Sienna', '#D68A59'), + ('Raw umber', '#826644'), + ('Razzle dazzle rose', '#FF33CC'), + ('Razzmatazz', '#E3256B'), + ('Razzmic Berry', '#8D4E85'), + ('Rebecca Purple', '#663399'), + ('Red', '#FF0000'), + ('Red (Crayola)', '#EE204D'), + ('Red (Munsell)', '#F2003C'), + ('Red (NCS)', '#C40233'), + ('Red (Pantone)', '#ED2939'), + ('Red (pigment)', '#ED1C24'), + ('Red (RYB)', '#FE2712'), + ('Red devil', '#860111'), + ('Red Salsa', '#FD3A4A'), + ('Red-brown', '#A52A2A'), + ('Red-orange', '#FF5349'), + ('Red-purple', '#E40078'), + ('Red-violet', '#C71585'), + ('Redwood', '#A45A52'), + ('Regalia', '#522D80'), + ('Registration black', '#000000'), + ('Resolution blue', '#002387'), + ('Rhythm', '#777696'), + ('Rich black', '#004040'), + ('Rich black (FOGRA29)', '#010B13'), + ('Rich black (FOGRA39)', '#010203'), + ('Rich brilliant lavender', '#F1A7FE'), + ('Rich carmine', '#D70040'), + ('Rich electric blue', '#0892D0'), + ('Rich lavender', '#A76BCF'), + ('Rich lilac', '#B666D2'), + ('Rich maroon', '#B03060'), + ('Rifle green', '#444C38'), + ('Roast coffee', '#704241'), + ('Robin egg blue', '#00CCCC'), + ('Rocket metallic', '#8A7F80'), + ('Roman silver', '#838996'), + ('Rose', '#FF007F'), + ('Rose bonbon', '#F9429E'), + ('Rose Dust', '#9E5E6F'), + ('Rose ebony', '#674846'), + ('Rose gold', '#B76E79'), + ('Rose madder', '#E32636'), + ('Rose pink', '#FF66CC'), + ('Rose quartz', '#AA98A9'), + ('Rose red', '#C21E56'), + ('Rose taupe', '#905D5D'), + ('Rose vale', '#AB4E52'), + ('Rosewood', '#65000B'), + ('Rosso corsa', '#D40000'), + ('Rosy brown', '#BC8F8F'), + ('Royal azure', '#0038A8'), + ('Royal blue', '#4169E1'), + ('Royal blue (traditional)', '#002366'), + ('Royal fuchsia', '#CA2C92'), + ('Royal purple', '#7851A9'), + ('Royal yellow', '#FADA5E'), + ('Ruber', '#CE4676'), + ('Rubine red', '#D10056'), + ('Ruby', '#E0115F'), + ('Ruby red', '#9B111E'), + ('Ruddy', '#FF0028'), + ('Ruddy brown', '#BB6528'), + ('Ruddy pink', '#E18E96'), + ('Rufous', '#A81C07'), + ('Russet', '#80461B'), + ('Russian green', '#679267'), + ('Russian violet', '#32174D'), + ('Rust', '#B7410E'), + ('Rusty red', '#DA2C43'), + ('Sacramento State green', '#00563F'), + ('Saddle brown', '#8B4513'), + ('Safety orange', '#FF7800'), + ('Safety orange (blaze orange)', '#FF6700'), + ('Safety yellow', '#EED202'), + ('Saffron', '#F4C430'), + ('Sage', '#BCB88A'), + ('Salmon', '#FA8072'), + ('Salmon pink', '#FF91A4'), + ('Sand', '#C2B280'), + ('Sand dune', '#967117'), + ('Sandstorm', '#ECD540'), + ('Sandy brown', '#F4A460'), + ('Sandy Tan', '#FDD9B5'), + ('Sandy taupe', '#967117'), + ('Sangria', '#92000A'), + ('Sap green', '#507D2A'), + ('Sapphire', '#0F52BA'), + ('Sapphire blue', '#0067A5'), + ('Sasquatch Socks', '#FF4681'), + ('Satin sheen gold', '#CBA135'), + ('Scarlet', '#FF2400'), + ('Scarlet (Crayola)', '#FD0E35'), + ('Schauss pink', '#FF91AF'), + ('School bus yellow', '#FFD800'), + ("Screamin' Green", '#66FF66'), + ('Sea blue', '#006994'), + ('Sea Foam Green', '#9FE2BF'), + ('Sea green', '#2E8B57'), + ('Sea Serpent', '#4BC7CF'), + ('Seal brown', '#59260B'), + ('Seashell', '#FFF5EE'), + ('Selective yellow', '#FFBA00'), + ('Sepia', '#704214'), + ('Shadow', '#8A795D'), + ('Shadow blue', '#778BA5'), + ('Shampoo', '#FFCFF1'), + ('Shamrock green', '#009E60'), + ('Sheen Green', '#8FD400'), + ('Shimmering Blush', '#D98695'), + ('Shiny Shamrock', '#5FA778'), + ('Shocking pink', '#FC0FC0'), + ('Shocking pink (Crayola)', '#FF6FFF'), + ('Sienna', '#882D17'), + ('Silver', '#C0C0C0'), + ('Silver chalice', '#ACACAC'), + ('Silver Lake blue', '#5D89BA'), + ('Silver pink', '#C4AEAD'), + ('Silver sand', '#BFC1C2'), + ('Sinopia', '#CB410B'), + ('Sizzling Red', '#FF3855'), + ('Sizzling Sunrise', '#FFDB00'), + ('Skobeloff', '#007474'), + ('Sky blue', '#87CEEB'), + ('Sky magenta', '#CF71AF'), + ('Slate blue', '#6A5ACD'), + ('Slate gray', '#708090'), + ('Slate grey', '#708090'), + ('Slimy Green', '#299617'), + ('Smalt (Dark powder blue)', '#003399'), + ('Smashed Pumpkin', '#FF6D3A'), + ('Smitten', '#C84186'), + ('Smoke', '#738276'), + ('Smokey Topaz', '#832A0D'), + ('Smoky black', '#100C08'), + ('Smoky Topaz', '#933D41'), + ('Snow', '#FFFAFA'), + ('Soap', '#CEC8EF'), + ('Solid pink', '#893843'), + ('Sonic silver', '#757575'), + ('Space cadet', '#1D2951'), + ('Spanish bistre', '#807532'), + ('Spanish blue', '#0070B8'), + ('Spanish carmine', '#D10047'), + ('Spanish crimson', '#E51A4C'), + ('Spanish gray', '#989898'), + ('Spanish green', '#009150'), + ('Spanish orange', '#E86100'), + ('Spanish pink', '#F7BFBE'), + ('Spanish red', '#E60026'), + ('Spanish sky blue', '#00FFFF'), + ('Spanish violet', '#4C2882'), + ('Spanish viridian', '#007F5C'), + ('Spartan Crimson', '#9E1316'), + ('Spicy mix', '#8B5F4D'), + ('Spiro Disco Ball', '#0FC0FC'), + ('Spring bud', '#A7FC00'), + ('Spring Frost', '#87FF2A'), + ('Spring green', '#00FF7F'), + ("St. Patrick's blue", '#23297A'), + ('Star command blue', '#007BB8'), + ('Steel blue', '#4682B4'), + ('Steel pink', '#CC33CC'), + ('Steel Teal', '#5F8A8B'), + ('Stil de grain yellow', '#FADA5E'), + ('Stizza', '#990000'), + ('Stormcloud', '#4F666A'), + ('Straw', '#E4D96F'), + ('Strawberry', '#FC5A8D'), + ('Sugar Plum', '#914E75'), + ('Sunburnt Cyclops', '#FF404C'), + ('Sunglow', '#FFCC33'), + ('Sunny', '#F2F27A'), + ('Sunray', '#E3AB57'), + ('Sunset', '#FAD6A5'), + ('Sunset orange', '#FD5E53'), + ('Super pink', '#CF6BA9'), + ('Sweet Brown', '#A83731'), + ('Tan', '#D2B48C'), + ('Tangelo', '#F94D00'), + ('Tangerine', '#F28500'), + ('Tangerine yellow', '#FFCC00'), + ('Tango pink', '#E4717A'), + ('Tart Orange', '#FB4D46'), + ('Taupe', '#483C32'), + ('Taupe gray', '#8B8589'), + ('Tea green', '#D0F0C0'), + ('Tea rose', '#F88379'), + ('Tea rose (rose)', '#F4C2C2'), + ('Teal', '#008080'), + ('Teal blue', '#367588'), + ('Teal deer', '#99E6B3'), + ('Teal green', '#00827F'), + ('Telemagenta', '#CF3476'), + ('Tenné (tawny)', '#CD5700'), + ('Terra cotta', '#E2725B'), + ('Thistle', '#D8BFD8'), + ('Thulian pink', '#DE6FA1'), + ('Tickle Me Pink', '#FC89AC'), + ('Tiffany Blue', '#0ABAB5'), + ("Tiger's eye", '#E08D3C'), + ('Timberwolf', '#DBD7D2'), + ('Titanium yellow', '#EEE600'), + ('Tomato', '#FF6347'), + ('Toolbox', '#746CC0'), + ('Topaz', '#FFC87C'), + ('Tractor red', '#FD0E35'), + ('Trolley Grey', '#808080'), + ('Tropical rain forest', '#00755E'), + ('Tropical violet', '#CDA4DE'), + ('True Blue', '#0073CF'), + ('Tufts Blue', '#3E8EDE'), + ('Tulip', '#FF878D'), + ('Tumbleweed', '#DEAA88'), + ('Turkish rose', '#B57281'), + ('Turquoise', '#40E0D0'), + ('Turquoise blue', '#00FFEF'), + ('Turquoise green', '#A0D6B4'), + ('Turquoise Surf', '#00C5CD'), + ('Turtle green', '#8A9A5B'), + ('Tuscan', '#FAD6A5'), + ('Tuscan brown', '#6F4E37'), + ('Tuscan red', '#7C4848'), + ('Tuscan tan', '#A67B5B'), + ('Tuscany', '#C09999'), + ('Twilight lavender', '#8A496B'), + ('Tyrian purple', '#66023C'), + ('UA blue', '#0033AA'), + ('UA red', '#D9004C'), + ('Ube', '#8878C3'), + ('UCLA Blue', '#536895'), + ('UCLA Gold', '#FFB300'), + ('UFO Green', '#3CD070'), + ('Ultra pink', '#FF6FFF'), + ('Ultra red', '#FC6C85'), + ('Ultramarine', '#3F00FF'), + ('Ultramarine blue', '#4166F5'), + ('Umber', '#635147'), + ('Unbleached silk', '#FFDDCA'), + ('United Nations blue', '#5B92E5'), + ('University of California Gold', '#B78727'), + ('University of Tennessee Orange', '#F77F00'), + ('Unmellow yellow', '#FFFF66'), + ('UP Forest green', '#014421'), + ('UP Maroon', '#7B1113'), + ('Upsdell red', '#AE2029'), + ('Urobilin', '#E1AD21'), + ('USAFA blue', '#004F98'), + ('USC Cardinal', '#990000'), + ('USC Gold', '#FFCC00'), + ('Utah Crimson', '#D3003F'), + ('Van Dyke Brown', '#664228'), + ('Vanilla', '#F3E5AB'), + ('Vanilla ice', '#F38FA9'), + ('Vegas gold', '#C5B358'), + ('Venetian red', '#C80815'), + ('Verdigris', '#43B3AE'), + ('Vermilion', '#E34234'), + ('Vermilion (Plochere)', '#D9381E'), + ('Veronica', '#A020F0'), + ('Very light azure', '#74BBFB'), + ('Very light blue', '#6666FF'), + ('Very light malachite green', '#64E986'), + ('Very light tangelo', '#FFB077'), + ('Very pale orange', '#FFDFBF'), + ('Very pale yellow', '#FFFFBF'), + ('Violet', '#8F00FF'), + ('Violet (color wheel)', '#7F00FF'), + ('Violet (RYB)', '#8601AF'), + ('Violet (web)', '#EE82EE'), + ('Violet-blue', '#324AB2'), + ('Violet-red', '#F75394'), + ('Viridian', '#40826D'), + ('Viridian green', '#009698'), + ('Vista blue', '#7C9ED9'), + ('Vivid amber', '#CC9900'), + ('Vivid auburn', '#922724'), + ('Vivid burgundy', '#9F1D35'), + ('Vivid cerise', '#DA1D81'), + ('Vivid cerulean', '#00AAEE'), + ('Vivid crimson', '#CC0033'), + ('Vivid gamboge', '#FF9900'), + ('Vivid lime green', '#A6D608'), + ('Vivid malachite', '#00CC33'), + ('Vivid mulberry', '#B80CE3'), + ('Vivid orange', '#FF5F00'), + ('Vivid orange peel', '#FFA000'), + ('Vivid orchid', '#CC00FF'), + ('Vivid raspberry', '#FF006C'), + ('Vivid red', '#F70D1A'), + ('Vivid red-tangelo', '#DF6124'), + ('Vivid sky blue', '#00CCFF'), + ('Vivid tangelo', '#F07427'), + ('Vivid tangerine', '#FFA089'), + ('Vivid vermilion', '#E56024'), + ('Vivid violet', '#9F00FF'), + ('Vivid yellow', '#FFE302'), + ('Volt', '#CEFF00'), + ('Wageningen Green', '#34B233'), + ('Warm black', '#004242'), + ('Waterspout', '#A4F4F9'), + ('Weldon Blue', '#7C98AB'), + ('Wenge', '#645452'), + ('Wheat', '#F5DEB3'), + ('White', '#FFFFFF'), + ('White smoke', '#F5F5F5'), + ('Wild blue yonder', '#A2ADD0'), + ('Wild orchid', '#D470A2'), + ('Wild Strawberry', '#FF43A4'), + ('Wild watermelon', '#FC6C85'), + ('Willpower orange', '#FD5800'), + ('Windsor tan', '#A75502'), + ('Wine', '#722F37'), + ('Wine dregs', '#673147'), + ('Winter Sky', '#FF007C'), + ('Winter Wizard', '#A0E6FF'), + ('Wintergreen Dream', '#56887D'), + ('Wisteria', '#C9A0DC'), + ('Wood brown', '#C19A6B'), + ('Xanadu', '#738678'), + ('Yale Blue', '#0F4D92'), + ('Yankees blue', '#1C2841'), + ('Yellow', '#FFFF00'), + ('Yellow (Crayola)', '#FCE883'), + ('Yellow (Munsell)', '#EFCC00'), + ('Yellow (NCS)', '#FFD300'), + ('Yellow (Pantone)', '#FEDF00'), + ('Yellow (process)', '#FFEF00'), + ('Yellow (RYB)', '#FEFE33'), + ('Yellow Orange', '#FFAE42'), + ('Yellow rose', '#FFF000'), + ('Yellow Sunshine', '#FFF700'), + ('Yellow-green', '#9ACD32'), + ('Zaffre', '#0014A8'), + ('Zinnwaldite brown', '#2C1608'), + ('Zomp', '#39A78E'), +) + +# Precomputed fast caches for the built-in catalog. +_HEX_TO_RGB_CACHE: dict[str, tuple[int, int, int]] = { + hx: (int(hx[1:3], 16), int(hx[3:5], 16), int(hx[5:7], 16)) + for _, hx in _DEFAULT_COLORS +} +_HEX_TO_LAB_CACHE: dict[str, tuple[float, float, float]] = {} + + +def _cached_rgb(hex_value: str) -> tuple[int, int, int]: + rgb = _HEX_TO_RGB_CACHE.get(hex_value) + if rgb is None: + rgb = _hex_to_rgb(hex_value) + _HEX_TO_RGB_CACHE[_rgb_to_hex(*rgb)] = rgb + return rgb + + +def _cached_lab(hex_value: str) -> tuple[float, float, float]: + rgb = _cached_rgb(hex_value) + key = _rgb_to_hex(*rgb) + lab = _HEX_TO_LAB_CACHE.get(key) + if lab is None: + lab = _rgb_to_lab(*rgb) + _HEX_TO_LAB_CACHE[key] = lab + return lab + + +def _compact_key(name: str) -> str: + """Collapse spaces, hyphens, and underscores for flexible CSS-style matching.""" + return _NORMALIZE_SEP_RE.sub("", name.strip().lower()) + + +def _format_entry(name: str, hex_value: str) -> dict[str, Any]: + upper_hex = hex_value.upper() + return { + "Name": name, + "Hex": upper_hex, + "RGB": _cached_rgb(upper_hex), + } + + class ColorManager: - """ - Manages a collection of predefined named colors and provides methods for color search - and conversion between different color formats. + """Manage a catalog of 1,300+ named colors with fast lookup and search. - Attributes: - color_list (list): A predefined list of dictionaries containing 'hex' and 'name' keys. + Includes all standard W3C CSS named colors alongside traditional, Crayola, + Pantone, Munsell, NCS, and X11 color names. - Methods: - __init__(): Initializes the ColorManager with a predefined list of colors. - hex_to_rgb(hex_value): Converts a hex color code to an RGB tuple. - rgb_to_hex(r, g, b): Converts RGB values to a hex color code. - closest_color_name(hex_value): Finds the closest color name to the given hex value. - get_color_by_name(name): Returns the hex and RGB values of a color based on its name. + Attributes: + color_list (list[dict[str, str]]): Mutable list of ``{'name', 'hex'}`` + color entries. """ - def __init__(self): - """ - Initializes the ColorManager with a predefined list of color data. - """ - - self.color_list = [ - {"name": "Absolute zero", "hex": "#0048BA"}, - {"name": "Acid green", "hex": "#B0BF1A"}, - {"name": "Aero", "hex": "#7CB9E8"}, - {"name": "Aero blue", "hex": "#C9FFE5"}, - {"name": "African violet", "hex": "#B284BE"}, - {"name": "Air Force blue (RAF)", "hex": "#5D8AA8"}, - {"name": "Air Force blue (USAF)", "hex": "#00308F"}, - {"name": "Air superiority blue", "hex": "#72A0C1"}, - {"name": "Alabama crimson", "hex": "#AF002A"}, - {"name": "Alabaster", "hex": "#F2F0E6"}, - {"name": "Alice blue", "hex": "#F0F8FF"}, - {"name": "Alien Armpit", "hex": "#84DE02"}, - {"name": "Alizarin crimson", "hex": "#E32636"}, - {"name": "Alloy orange", "hex": "#C46210"}, - {"name": "Almond", "hex": "#EFDECD"}, - {"name": "Amaranth", "hex": "#E52B50"}, - {"name": "Amaranth deep purple", "hex": "#9F2B68"}, - {"name": "Amaranth pink", "hex": "#F19CBB"}, - {"name": "Amaranth purple", "hex": "#AB274F"}, - {"name": "Amaranth red", "hex": "#D3212D"}, - {"name": "Amazon", "hex": "#3B7A57"}, - {"name": "Amazonite", "hex": "#00C4B0"}, - {"name": "Amber", "hex": "#FFBF00"}, - {"name": "Amber (SAE/ECE)", "hex": "#FF7E00"}, - {"name": "American rose", "hex": "#FF033E"}, - {"name": "Amethyst", "hex": "#9966CC"}, - {"name": "Android green", "hex": "#A4C639"}, - {"name": "Anti-flash white", "hex": "#F2F3F4"}, - {"name": "Antique brass", "hex": "#CD9575"}, - {"name": "Antique bronze", "hex": "#665D1E"}, - {"name": "Antique fuchsia", "hex": "#915C83"}, - {"name": "Antique ruby", "hex": "#841B2D"}, - {"name": "Antique white", "hex": "#FAEBD7"}, - {"name": "Ao (English)", "hex": "#008000"}, - {"name": "Apple green", "hex": "#8DB600"}, - {"name": "Apricot", "hex": "#FBCEB1"}, - {"name": "Aqua", "hex": "#00FFFF"}, - {"name": "Aquamarine", "hex": "#7FFFD4"}, - {"name": "Arctic lime", "hex": "#D0FF14"}, - {"name": "Army green", "hex": "#4B5320"}, - {"name": "Arsenic", "hex": "#3B444B"}, - {"name": "Artichoke", "hex": "#8F9779"}, - {"name": "Arylide yellow", "hex": "#E9D66B"}, - {"name": "Ash grey", "hex": "#B2BEB5"}, - {"name": "Asparagus", "hex": "#87A96B"}, - {"name": "Atomic tangerine", "hex": "#FF9966"}, - {"name": "Auburn", "hex": "#A52A2A"}, - {"name": "Aureolin", "hex": "#FDEE00"}, - {"name": "AuroMetalSaurus", "hex": "#6E7F80"}, - {"name": "Avocado", "hex": "#568203"}, - {"name": "Awesome", "hex": "#FF2052"}, - {"name": "Aztec Gold", "hex": "#C39953"}, - {"name": "Azure", "hex": "#007FFF"}, - {"name": "Azure (web color)", "hex": "#F0FFFF"}, - {"name": "Azure mist", "hex": "#F0FFFF"}, - {"name": "Azureish white", "hex": "#DBE9F4"}, - {"name": "Baby blue", "hex": "#89CFF0"}, - {"name": "Baby blue eyes", "hex": "#A1CAF1"}, - {"name": "Baby pink", "hex": "#F4C2C2"}, - {"name": "Baby powder", "hex": "#FEFEFA"}, - {"name": "Baker-Miller pink", "hex": "#FF91AF"}, - {"name": "Ball blue", "hex": "#21ABCD"}, - {"name": "Banana Mania", "hex": "#FAE7B5"}, - {"name": "Banana yellow", "hex": "#FFE135"}, - {"name": "Bangladesh green", "hex": "#006A4E"}, - {"name": "Barbie pink", "hex": "#E0218A"}, - {"name": "Barn red", "hex": "#7C0A02"}, - {"name": "Battery Charged Blue", "hex": "#1DACD6"}, - {"name": "Battleship grey", "hex": "#848482"}, - {"name": "Bazaar", "hex": "#98777B"}, - {"name": "Beau blue", "hex": "#BCD4E6"}, - {"name": "Beaver", "hex": "#9F8170"}, - {"name": "Begonia", "hex": "#FA6E79"}, - {"name": "Beige", "hex": "#F5F5DC"}, - {"name": "B'dazzled blue", "hex": "#2E5894"}, - {"name": "Big dip o’ruby", "hex": "#9C2542"}, - {"name": "Big Foot Feet", "hex": "#E88E5A"}, - {"name": "Bisque", "hex": "#FFE4C4"}, - {"name": "Bistre", "hex": "#3D2B1F"}, - {"name": "Bistre brown", "hex": "#967117"}, - {"name": "Bitter lemon", "hex": "#CAE00D"}, - {"name": "Bitter lime", "hex": "#BFFF00"}, - {"name": "Bittersweet", "hex": "#FE6F5E"}, - {"name": "Bittersweet shimmer", "hex": "#BF4F51"}, - {"name": "Black", "hex": "#000000"}, - {"name": "Black bean", "hex": "#3D0C02"}, - {"name": "Black Coral", "hex": "#54626F"}, - {"name": "Black leather jacket", "hex": "#253529"}, - {"name": "Black olive", "hex": "#3B3C36"}, - {"name": "Black Shadows", "hex": "#BFAFB2"}, - {"name": "Blanched almond", "hex": "#FFEBCD"}, - {"name": "Blast-off bronze", "hex": "#A57164"}, - {"name": "Bleu de France", "hex": "#318CE7"}, - {"name": "Blizzard Blue", "hex": "#ACE5EE"}, - {"name": "Blond", "hex": "#FAF0BE"}, - {"name": "Blue", "hex": "#0000FF"}, - {"name": "Blue (Crayola)", "hex": "#1F75FE"}, - {"name": "Blue (Munsell)", "hex": "#0093AF"}, - {"name": "Blue (NCS)", "hex": "#0087BD"}, - {"name": "Blue (Pantone)", "hex": "#0018A8"}, - {"name": "Blue (pigment)", "hex": "#333399"}, - {"name": "Blue (RYB)", "hex": "#0247FE"}, - {"name": "Blue Bell", "hex": "#A2A2D0"}, - {"name": "Blue Bolt", "hex": "#00B9FB"}, - {"name": "Blue-gray", "hex": "#6699CC"}, - {"name": "Blue-green", "hex": "#0D98BA"}, - {"name": "Blue Jeans", "hex": "#5DADEC"}, - {"name": "Blue Lagoon", "hex": "#ACE5EE"}, - {"name": "Blue-magenta violet", "hex": "#553592"}, - {"name": "Blue sapphire", "hex": "#126180"}, - {"name": "Blue-violet", "hex": "#8A2BE2"}, - {"name": "Blue yonder", "hex": "#5072A7"}, - {"name": "Blueberry", "hex": "#4F86F7"}, - {"name": "Bluebonnet", "hex": "#1C1CF0"}, - {"name": "Blush", "hex": "#DE5D83"}, - {"name": "Bole", "hex": "#79443B"}, - {"name": "Bondi blue", "hex": "#0095B6"}, - {"name": "Bone", "hex": "#E3DAC9"}, - {"name": "Booger Buster", "hex": "#DDE26A"}, - {"name": "Boston University Red", "hex": "#CC0000"}, - {"name": "Bottle green", "hex": "#006A4E"}, - {"name": "Boysenberry", "hex": "#873260"}, - {"name": "Brandeis blue", "hex": "#0070FF"}, - {"name": "Brass", "hex": "#B5A642"}, - {"name": "Brick red", "hex": "#CB4154"}, - {"name": "Bright cerulean", "hex": "#1DACD6"}, - {"name": "Bright green", "hex": "#66FF00"}, - {"name": "Bright lavender", "hex": "#BF94E4"}, - {"name": "Bright lilac", "hex": "#D891EF"}, - {"name": "Bright maroon", "hex": "#C32148"}, - {"name": "Bright navy blue", "hex": "#1974D2"}, - {"name": "Bright pink", "hex": "#FF007F"}, - {"name": "Bright turquoise", "hex": "#08E8DE"}, - {"name": "Bright ube", "hex": "#D19FE8"}, - {"name": "Bright Yellow (Crayola)", "hex": "#FFAA1D"}, - {"name": "Brilliant azure", "hex": "#3399FF"}, - {"name": "Brilliant lavender", "hex": "#F4BBFF"}, - {"name": "Brilliant rose", "hex": "#FF55A3"}, - {"name": "Brink pink", "hex": "#FB607F"}, - {"name": "British racing green", "hex": "#004225"}, - {"name": "Bronze", "hex": "#CD7F32"}, - {"name": "Bronze Yellow", "hex": "#737000"}, - {"name": "Brown (traditional)", "hex": "#964B00"}, - {"name": "Brown (web)", "hex": "#A52A2A"}, - {"name": "Brown-nose", "hex": "#6B4423"}, - {"name": "Brown Sugar", "hex": "#AF6E4D"}, - {"name": "Brown Yellow", "hex": "#cc9966"}, - {"name": "Brunswick green", "hex": "#1B4D3E"}, - {"name": "Bubble gum", "hex": "#FFC1CC"}, - {"name": "Bubbles", "hex": "#E7FEFF"}, - {"name": "Bud green", "hex": "#7BB661"}, - {"name": "Buff", "hex": "#F0DC82"}, - {"name": "Bulgarian rose", "hex": "#480607"}, - {"name": "Burgundy", "hex": "#800020"}, - {"name": "Burlywood", "hex": "#DEB887"}, - {"name": "Burnished Brown", "hex": "#A17A74"}, - {"name": "Burnt orange", "hex": "#CC5500"}, - {"name": "Burnt sienna", "hex": "#E97451"}, - {"name": "Burnt umber", "hex": "#8A3324"}, - {"name": "Byzantine", "hex": "#BD33A4"}, - {"name": "Byzantium", "hex": "#702963"}, - {"name": "Cadet", "hex": "#536872"}, - {"name": "Cadet blue", "hex": "#5F9EA0"}, - {"name": "Cadet grey", "hex": "#91A3B0"}, - {"name": "Cadmium green", "hex": "#006B3C"}, - {"name": "Cadmium orange", "hex": "#ED872D"}, - {"name": "Cadmium red", "hex": "#E30022"}, - {"name": "Cadmium yellow", "hex": "#FFF600"}, - {"name": "Café au lait", "hex": "#A67B5B"}, - {"name": "Café noir", "hex": "#4B3621"}, - {"name": "Cal Poly Pomona green", "hex": "#1E4D2B"}, - {"name": "Cambridge Blue", "hex": "#A3C1AD"}, - {"name": "Camel", "hex": "#C19A6B"}, - {"name": "Cameo pink", "hex": "#EFBBCC"}, - {"name": "Camouflage green", "hex": "#78866B"}, - {"name": "Canary", "hex": "#FFFF99"}, - {"name": "Canary yellow", "hex": "#FFEF00"}, - {"name": "Candy apple red", "hex": "#FF0800"}, - {"name": "Candy pink", "hex": "#E4717A"}, - {"name": "Capri", "hex": "#00BFFF"}, - {"name": "Caput mortuum", "hex": "#592720"}, - {"name": "Cardinal", "hex": "#C41E3A"}, - {"name": "Caribbean green", "hex": "#00CC99"}, - {"name": "Carmine", "hex": "#960018"}, - {"name": "Carmine (M&P)", "hex": "#D70040"}, - {"name": "Carmine pink", "hex": "#EB4C42"}, - {"name": "Carmine red", "hex": "#FF0038"}, - {"name": "Carnation pink", "hex": "#FFA6C9"}, - {"name": "Carnelian", "hex": "#B31B1B"}, - {"name": "Carolina blue", "hex": "#56A0D3"}, - {"name": "Carrot orange", "hex": "#ED9121"}, - {"name": "Castleton green", "hex": "#00563F"}, - {"name": "Catalina blue", "hex": "#062A78"}, - {"name": "Catawba", "hex": "#703642"}, - {"name": "Cedar Chest", "hex": "#C95A49"}, - {"name": "Ceil", "hex": "#92A1CF"}, - {"name": "Celadon", "hex": "#ACE1AF"}, - {"name": "Celadon blue", "hex": "#007BA7"}, - {"name": "Celadon green", "hex": "#2F847C"}, - {"name": "Celeste", "hex": "#B2FFFF"}, - {"name": "Celestial blue", "hex": "#4997D0"}, - {"name": "Cerise", "hex": "#DE3163"}, - {"name": "Cerise pink", "hex": "#EC3B83"}, - {"name": "Cerulean", "hex": "#007BA7"}, - {"name": "Cerulean blue", "hex": "#2A52BE"}, - {"name": "Cerulean frost", "hex": "#6D9BC3"}, - {"name": "CG Blue", "hex": "#007AA5"}, - {"name": "CG Red", "hex": "#E03C31"}, - {"name": "Chamoisee", "hex": "#A0785A"}, - {"name": "Champagne", "hex": "#F7E7CE"}, - {"name": "Champagne pink", "hex": "#F1DDCF"}, - {"name": "Charcoal", "hex": "#36454F"}, - {"name": "Charleston green", "hex": "#232B2B"}, - {"name": "Charm pink", "hex": "#E68FAC"}, - {"name": "Chartreuse (traditional)", "hex": "#DFFF00"}, - {"name": "Chartreuse (web)", "hex": "#7FFF00"}, - {"name": "Cherry", "hex": "#DE3163"}, - {"name": "Cherry blossom pink", "hex": "#FFB7C5"}, - {"name": "Chestnut", "hex": "#954535"}, - {"name": "China pink", "hex": "#DE6FA1"}, - {"name": "China rose", "hex": "#A8516E"}, - {"name": "Chinese red", "hex": "#AA381E"}, - {"name": "Chinese violet", "hex": "#856088"}, - {"name": "Chlorophyll green", "hex": "#4AFF00"}, - {"name": "Chocolate (traditional)", "hex": "#7B3F00"}, - {"name": "Chocolate (web)", "hex": "#D2691E"}, - {"name": "Chrome yellow", "hex": "#FFA700"}, - {"name": "Cinereous", "hex": "#98817B"}, - {"name": "Cinnabar", "hex": "#E34234"}, - {"name": "Cinnamon[citation needed]", "hex": "#D2691E"}, - {"name": "Cinnamon Satin", "hex": "#CD607E"}, - {"name": "Citrine", "hex": "#E4D00A"}, - {"name": "Citron", "hex": "#9FA91F"}, - {"name": "Claret", "hex": "#7F1734"}, - {"name": "Classic rose", "hex": "#FBCCE7"}, - {"name": "Cobalt Blue", "hex": "#0047AB"}, - {"name": "Cocoa brown", "hex": "#D2691E"}, - {"name": "Coconut", "hex": "#965A3E"}, - {"name": "Coffee", "hex": "#6F4E37"}, - {"name": "Columbia Blue", "hex": "#C4D8E2"}, - {"name": "Congo pink", "hex": "#F88379"}, - {"name": "Cool Black", "hex": "#002E63"}, - {"name": "Cool grey", "hex": "#8C92AC"}, - {"name": "Copper", "hex": "#B87333"}, - {"name": "Copper (Crayola)", "hex": "#DA8A67"}, - {"name": "Copper penny", "hex": "#AD6F69"}, - {"name": "Copper red", "hex": "#CB6D51"}, - {"name": "Copper rose", "hex": "#996666"}, - {"name": "Coquelicot", "hex": "#FF3800"}, - {"name": "Coral", "hex": "#FF7F50"}, - {"name": "Coral pink", "hex": "#F88379"}, - {"name": "Coral red", "hex": "#FF4040"}, - {"name": "Coral Reef", "hex": "#FD7C6E"}, - {"name": "Cordovan", "hex": "#893F45"}, - {"name": "Corn", "hex": "#FBEC5D"}, - {"name": "Cornell Red", "hex": "#B31B1B"}, - {"name": "Cornflower blue", "hex": "#6495ED"}, - {"name": "Cornsilk", "hex": "#FFF8DC"}, - {"name": "Cosmic Cobalt", "hex": "#2E2D88"}, - {"name": "Cosmic latte", "hex": "#FFF8E7"}, - {"name": "Coyote brown", "hex": "#81613C"}, - {"name": "Cotton candy", "hex": "#FFBCD9"}, - {"name": "Cream", "hex": "#FFFDD0"}, - {"name": "Crimson", "hex": "#DC143C"}, - {"name": "Crimson glory", "hex": "#BE0032"}, - {"name": "Crimson red", "hex": "#990000"}, - {"name": "Cultured", "hex": "#F5F5F5"}, - {"name": "Cyan", "hex": "#00FFFF"}, - {"name": "Cyan azure", "hex": "#4E82B4"}, - {"name": "Cyan-blue azure", "hex": "#4682BF"}, - {"name": "Cyan cobalt blue", "hex": "#28589C"}, - {"name": "Cyan cornflower blue", "hex": "#188BC2"}, - {"name": "Cyan (process)", "hex": "#00B7EB"}, - {"name": "Cyber grape", "hex": "#58427C"}, - {"name": "Cyber yellow", "hex": "#FFD300"}, - {"name": "Cyclamen", "hex": "#F56FA1"}, - {"name": "Daffodil", "hex": "#FFFF31"}, - {"name": "Dandelion", "hex": "#F0E130"}, - {"name": "Dark blue", "hex": "#00008B"}, - {"name": "Dark blue-gray", "hex": "#666699"}, - {"name": "Dark brown", "hex": "#654321"}, - {"name": "Dark brown-tangelo", "hex": "#88654E"}, - {"name": "Dark byzantium", "hex": "#5D3954"}, - {"name": "Dark candy apple red", "hex": "#A40000"}, - {"name": "Dark cerulean", "hex": "#08457E"}, - {"name": "Dark chestnut", "hex": "#986960"}, - {"name": "Dark coral", "hex": "#CD5B45"}, - {"name": "Dark cyan", "hex": "#008B8B"}, - {"name": "Dark electric blue", "hex": "#536878"}, - {"name": "Dark goldenrod", "hex": "#B8860B"}, - {"name": "Dark gray (X11)", "hex": "#A9A9A9"}, - {"name": "Dark green", "hex": "#013220"}, - {"name": "Dark green (X11)", "hex": "#006400"}, - {"name": "Dark gunmetal", "hex": "#1F262A"}, - {"name": "Dark imperial blue", "hex": "#00416A"}, - {"name": "Dark imperial blue", "hex": "#00147E"}, - {"name": "Dark jungle green", "hex": "#1A2421"}, - {"name": "Dark khaki", "hex": "#BDB76B"}, - {"name": "Dark lava", "hex": "#483C32"}, - {"name": "Dark lavender", "hex": "#734F96"}, - {"name": "Dark liver", "hex": "#534B4F"}, - {"name": "Dark liver (horses)", "hex": "#543D37"}, - {"name": "Dark magenta", "hex": "#8B008B"}, - {"name": "Dark medium gray", "hex": "#A9A9A9"}, - {"name": "Dark midnight blue", "hex": "#003366"}, - {"name": "Dark moss green", "hex": "#4A5D23"}, - {"name": "Dark olive green", "hex": "#556B2F"}, - {"name": "Dark orange", "hex": "#FF8C00"}, - {"name": "Dark orchid", "hex": "#9932CC"}, - {"name": "Dark pastel blue", "hex": "#779ECB"}, - {"name": "Dark pastel green", "hex": "#03C03C"}, - {"name": "Dark pastel purple", "hex": "#966FD6"}, - {"name": "Dark pastel red", "hex": "#C23B22"}, - {"name": "Dark pink", "hex": "#E75480"}, - {"name": "Dark powder blue", "hex": "#003399"}, - {"name": "Dark puce", "hex": "#4F3A3C"}, - {"name": "Dark purple", "hex": "#301934"}, - {"name": "Dark raspberry", "hex": "#872657"}, - {"name": "Dark red", "hex": "#8B0000"}, - {"name": "Dark salmon", "hex": "#E9967A"}, - {"name": "Dark scarlet", "hex": "#560319"}, - {"name": "Dark sea green", "hex": "#8FBC8F"}, - {"name": "Dark sienna", "hex": "#3C1414"}, - {"name": "Dark sky blue", "hex": "#8CBED6"}, - {"name": "Dark slate blue", "hex": "#483D8B"}, - {"name": "Dark slate gray", "hex": "#2F4F4F"}, - {"name": "Dark spring green", "hex": "#177245"}, - {"name": "Dark tan", "hex": "#918151"}, - {"name": "Dark tangerine", "hex": "#FFA812"}, - {"name": "Dark taupe", "hex": "#483C32"}, - {"name": "Dark terra cotta", "hex": "#CC4E5C"}, - {"name": "Dark turquoise", "hex": "#00CED1"}, - {"name": "Dark vanilla", "hex": "#D1BEA8"}, - {"name": "Dark violet", "hex": "#9400D3"}, - {"name": "Dark yellow", "hex": "#9B870C"}, - {"name": "Dartmouth green", "hex": "#00703C"}, - {"name": "Davy's grey", "hex": "#555555"}, - {"name": "Debian red", "hex": "#D70A53"}, - {"name": "Deep aquamarine", "hex": "#40826D"}, - {"name": "Deep carmine", "hex": "#A9203E"}, - {"name": "Deep carmine pink", "hex": "#EF3038"}, - {"name": "Deep carrot orange", "hex": "#E9692C"}, - {"name": "Deep cerise", "hex": "#DA3287"}, - {"name": "Deep champagne", "hex": "#FAD6A5"}, - {"name": "Deep chestnut", "hex": "#B94E48"}, - {"name": "Deep coffee", "hex": "#704241"}, - {"name": "Deep fuchsia", "hex": "#C154C1"}, - {"name": "Deep Green", "hex": "#056608"}, - {"name": "Deep green-cyan turquoise", "hex": "#0E7C61"}, - {"name": "Deep jungle green", "hex": "#004B49"}, - {"name": "Deep koamaru", "hex": "#333366"}, - {"name": "Deep lemon", "hex": "#F5C71A"}, - {"name": "Deep lilac", "hex": "#9955BB"}, - {"name": "Deep magenta", "hex": "#CC00CC"}, - {"name": "Deep maroon", "hex": "#820000"}, - {"name": "Deep mauve", "hex": "#D473D4"}, - {"name": "Deep moss green", "hex": "#355E3B"}, - {"name": "Deep peach", "hex": "#FFCBA4"}, - {"name": "Deep pink", "hex": "#FF1493"}, - {"name": "Deep puce", "hex": "#A95C68"}, - {"name": "Deep Red", "hex": "#850101"}, - {"name": "Deep ruby", "hex": "#843F5B"}, - {"name": "Deep saffron", "hex": "#FF9933"}, - {"name": "Deep sky blue", "hex": "#00BFFF"}, - {"name": "Deep Space Sparkle", "hex": "#4A646C"}, - {"name": "Deep spring bud", "hex": "#556B2F"}, - {"name": "Deep Taupe", "hex": "#7E5E60"}, - {"name": "Deep Tuscan red", "hex": "#66424D"}, - {"name": "Deep violet", "hex": "#330066"}, - {"name": "Deer", "hex": "#BA8759"}, - {"name": "Denim", "hex": "#1560BD"}, - {"name": "Denim Blue", "hex": "#2243B6"}, - {"name": "Desaturated cyan", "hex": "#669999"}, - {"name": "Desert", "hex": "#C19A6B"}, - {"name": "Desert sand", "hex": "#EDC9AF"}, - {"name": "Desire", "hex": "#EA3C53"}, - {"name": "Diamond", "hex": "#B9F2FF"}, - {"name": "Dim gray", "hex": "#696969"}, - {"name": "Dingy Dungeon", "hex": "#C53151"}, - {"name": "Dirt", "hex": "#9B7653"}, - {"name": "Dodger blue", "hex": "#1E90FF"}, - {"name": "Dogwood rose", "hex": "#D71868"}, - {"name": "Dollar bill", "hex": "#85BB65"}, - {"name": "Dolphin Gray", "hex": "#828E84"}, - {"name": "Donkey brown", "hex": "#664C28"}, - {"name": "Drab", "hex": "#967117"}, - {"name": "Duke blue", "hex": "#00009C"}, - {"name": "Dust storm", "hex": "#E5CCC9"}, - {"name": "Dutch white", "hex": "#EFDFBB"}, - {"name": "Earth yellow", "hex": "#E1A95F"}, - {"name": "Ebony", "hex": "#555D50"}, - {"name": "Ecru", "hex": "#C2B280"}, - {"name": "Eerie black", "hex": "#1B1B1B"}, - {"name": "Eggplant", "hex": "#614051"}, - {"name": "Eggshell", "hex": "#F0EAD6"}, - {"name": "Egyptian blue", "hex": "#1034A6"}, - {"name": "Electric blue", "hex": "#7DF9FF"}, - {"name": "Electric crimson", "hex": "#FF003F"}, - {"name": "Electric cyan", "hex": "#00FFFF"}, - {"name": "Electric green", "hex": "#00FF00"}, - {"name": "Electric indigo", "hex": "#6F00FF"}, - {"name": "Electric lavender", "hex": "#F4BBFF"}, - {"name": "Electric lime", "hex": "#CCFF00"}, - {"name": "Electric purple", "hex": "#BF00FF"}, - {"name": "Electric ultramarine", "hex": "#3F00FF"}, - {"name": "Electric violet", "hex": "#8F00FF"}, - {"name": "Electric yellow", "hex": "#FFFF33"}, - {"name": "Emerald", "hex": "#50C878"}, - {"name": "Eminence", "hex": "#6C3082"}, - {"name": "English green", "hex": "#1B4D3E"}, - {"name": "English lavender", "hex": "#B48395"}, - {"name": "English red", "hex": "#AB4B52"}, - {"name": "English vermillion", "hex": "#CC474B"}, - {"name": "English violet", "hex": "#563C5C"}, - {"name": "Eton blue", "hex": "#96C8A2"}, - {"name": "Eucalyptus", "hex": "#44D7A8"}, - {"name": "Fallow", "hex": "#C19A6B"}, - {"name": "Falu red", "hex": "#801818"}, - {"name": "Fandango", "hex": "#B53389"}, - {"name": "Fandango pink", "hex": "#DE5285"}, - {"name": "Fashion fuchsia", "hex": "#F400A1"}, - {"name": "Fawn", "hex": "#E5AA70"}, - {"name": "Feldgrau", "hex": "#4D5D53"}, - {"name": "Feldspar", "hex": "#FDD5B1"}, - {"name": "Fern green", "hex": "#4F7942"}, - {"name": "Ferrari Red", "hex": "#FF2800"}, - {"name": "Field drab", "hex": "#6C541E"}, - {"name": "Fiery Rose", "hex": "#FF5470"}, - {"name": "Firebrick", "hex": "#B22222"}, - {"name": "Fire engine red", "hex": "#CE2029"}, - {"name": "Flame", "hex": "#E25822"}, - {"name": "Flamingo pink", "hex": "#FC8EAC"}, - {"name": "Flattery", "hex": "#6B4423"}, - {"name": "Flavescent", "hex": "#F7E98E"}, - {"name": "Flax", "hex": "#EEDC82"}, - {"name": "Flirt", "hex": "#A2006D"}, - {"name": "Floral white", "hex": "#FFFAF0"}, - {"name": "Fluorescent orange", "hex": "#FFBF00"}, - {"name": "Fluorescent pink", "hex": "#FF1493"}, - {"name": "Fluorescent yellow", "hex": "#CCFF00"}, - {"name": "Folly", "hex": "#FF004F"}, - {"name": "Forest green (traditional)", "hex": "#014421"}, - {"name": "Forest green (web)", "hex": "#228B22"}, - {"name": "French beige", "hex": "#A67B5B"}, - {"name": "French bistre", "hex": "#856D4D"}, - {"name": "French blue", "hex": "#0072BB"}, - {"name": "French fuchsia", "hex": "#FD3F92"}, - {"name": "French lilac", "hex": "#86608E"}, - {"name": "French lime", "hex": "#9EFD38"}, - {"name": "French mauve", "hex": "#D473D4"}, - {"name": "French pink", "hex": "#FD6C9E"}, - {"name": "French plum", "hex": "#811453"}, - {"name": "French puce", "hex": "#4E1609"}, - {"name": "French raspberry", "hex": "#C72C48"}, - {"name": "French rose", "hex": "#F64A8A"}, - {"name": "French sky blue", "hex": "#77B5FE"}, - {"name": "French violet", "hex": "#8806CE"}, - {"name": "French wine", "hex": "#AC1E44"}, - {"name": "Fresh Air", "hex": "#A6E7FF"}, - {"name": "Frostbite", "hex": "#E936A7"}, - {"name": "Fuchsia", "hex": "#FF00FF"}, - {"name": "Fuchsia (Crayola)", "hex": "#C154C1"}, - {"name": "Fuchsia pink", "hex": "#FF77FF"}, - {"name": "Fuchsia purple", "hex": "#CC397B"}, - {"name": "Fuchsia rose", "hex": "#C74375"}, - {"name": "Fulvous", "hex": "#E48400"}, - {"name": "Fuzzy Wuzzy", "hex": "#CC6666"}, - {"name": "Gainsboro", "hex": "#DCDCDC"}, - {"name": "Gamboge", "hex": "#E49B0F"}, - {"name": "Gamboge orange (brown)", "hex": "#996600"}, - {"name": "Gargoyle Gas", "hex": "#FFDF46"}, - {"name": "Generic viridian", "hex": "#007F66"}, - {"name": "Ghost white", "hex": "#F8F8FF"}, - {"name": "Giant's Club", "hex": "#B05C52"}, - {"name": "Giants orange", "hex": "#FE5A1D"}, - {"name": "Ginger", "hex": "#B06500"}, - {"name": "Glaucous", "hex": "#6082B6"}, - {"name": "Glitter", "hex": "#E6E8FA"}, - {"name": "Glossy Grape", "hex": "#AB92B3"}, - {"name": "GO green", "hex": "#00AB66"}, - {"name": "Gold (metallic)", "hex": "#D4AF37"}, - {"name": "Gold (web) (Golden)", "hex": "#FFD700"}, - {"name": "Gold Fusion", "hex": "#85754E"}, - {"name": "Golden brown", "hex": "#996515"}, - {"name": "Golden poppy", "hex": "#FCC200"}, - {"name": "Golden yellow", "hex": "#FFDF00"}, - {"name": "Goldenrod", "hex": "#DAA520"}, - {"name": "Granite Gray", "hex": "#676767"}, - {"name": "Granny Smith Apple", "hex": "#A8E4A0"}, - {"name": "Grape", "hex": "#6F2DA8"}, - {"name": "Gray", "hex": "#808080"}, - {"name": "Gray (HTML/CSS gray)", "hex": "#808080"}, - {"name": "Gray (X11 gray)", "hex": "#BEBEBE"}, - {"name": "Gray-asparagus", "hex": "#465945"}, - {"name": "Gray-blue", "hex": "#8C92AC"}, - {"name": "Green (Color Wheel) (X11 green)", "hex": "#00FF00"}, - {"name": "Green (Crayola)", "hex": "#1CAC78"}, - {"name": "Green (HTML/CSS color)", "hex": "#008000"}, - {"name": "Green (Munsell)", "hex": "#00A877"}, - {"name": "Green (NCS)", "hex": "#009F6B"}, - {"name": "Green (Pantone)", "hex": "#00AD43"}, - {"name": "Green (pigment)", "hex": "#00A550"}, - {"name": "Green (RYB)", "hex": "#66B032"}, - {"name": "Green-blue", "hex": "#1164B4"}, - {"name": "Green-cyan", "hex": "#009966"}, - {"name": "Green Lizard", "hex": "#A7F432"}, - {"name": "Green Sheen", "hex": "#6EAEA1"}, - {"name": "Green-yellow", "hex": "#ADFF2F"}, - {"name": "Grizzly", "hex": "#885818"}, - {"name": "Grullo", "hex": "#A99A86"}, - {"name": "Guppie green", "hex": "#00FF7F"}, - {"name": "Gunmetal", "hex": "#2a3439"}, - {"name": "Halayà úbe", "hex": "#663854"}, - {"name": "Han blue", "hex": "#446CCF"}, - {"name": "Han purple", "hex": "#5218FA"}, - {"name": "Hansa yellow", "hex": "#E9D66B"}, - {"name": "Harlequin", "hex": "#3FFF00"}, - {"name": "Harlequin green", "hex": "#46CB18"}, - {"name": "Harvard crimson", "hex": "#C90016"}, - {"name": "Harvest gold", "hex": "#DA9100"}, - {"name": "Heart Gold", "hex": "#808000"}, - {"name": "Heat Wave", "hex": "#FF7A00"}, - {"name": "Heidelberg Red[2]", "hex": "#960018"}, - {"name": "Heliotrope", "hex": "#DF73FF"}, - {"name": "Heliotrope gray", "hex": "#AA98A9"}, - {"name": "Heliotrope magenta", "hex": "#AA00BB"}, - {"name": "Hollywood cerise", "hex": "#F400A1"}, - {"name": "Honeydew", "hex": "#F0FFF0"}, - {"name": "Honolulu blue", "hex": "#006DB0"}, - {"name": "Hooker's green", "hex": "#49796B"}, - {"name": "Hot magenta", "hex": "#FF1DCE"}, - {"name": "Hot pink", "hex": "#FF69B4"}, - {"name": "Hunter green", "hex": "#355E3B"}, - {"name": "Iceberg", "hex": "#71A6D2"}, - {"name": "Icterine", "hex": "#FCF75E"}, - {"name": "Iguana Green", "hex": "#71BC78"}, - {"name": "Illuminating Emerald", "hex": "#319177"}, - {"name": "Imperial", "hex": "#602F6B"}, - {"name": "Imperial blue", "hex": "#002395"}, - {"name": "Imperial purple", "hex": "#66023C"}, - {"name": "Imperial red", "hex": "#ED2939"}, - {"name": "Inchworm", "hex": "#B2EC5D"}, - {"name": "Independence", "hex": "#4C516D"}, - {"name": "India green", "hex": "#138808"}, - {"name": "Indian red", "hex": "#CD5C5C"}, - {"name": "Indian yellow", "hex": "#E3A857"}, - {"name": "Indigo", "hex": "#4B0082"}, - {"name": "Indigo dye", "hex": "#091F92"}, - {"name": "Indigo (web)", "hex": "#4B0082"}, - {"name": "Infra Red", "hex": "#FF496C"}, - {"name": "Interdimensional Blue", "hex": "#360CCC"}, - {"name": "International Klein Blue", "hex": "#002FA7"}, - {"name": "International orange (aerospace)", "hex": "#FF4F00"}, - {"name": "International orange (engineering)", "hex": "#BA160C"}, - {"name": "International orange (Golden Gate Bridge)", - "hex": "#C0362C"}, - {"name": "Iris", "hex": "#5A4FCF"}, - {"name": "Irresistible", "hex": "#B3446C"}, - {"name": "Isabelline", "hex": "#F4F0EC"}, - {"name": "Islamic green", "hex": "#009000"}, - {"name": "Italian sky blue", "hex": "#B2FFFF"}, - {"name": "Ivory", "hex": "#FFFFF0"}, - {"name": "Jade", "hex": "#00A86B"}, - {"name": "Japanese carmine", "hex": "#9D2933"}, - {"name": "Japanese indigo", "hex": "#264348"}, - {"name": "Japanese violet", "hex": "#5B3256"}, - {"name": "Jasmine", "hex": "#F8DE7E"}, - {"name": "Jasper", "hex": "#D73B3E"}, - {"name": "Jazzberry jam", "hex": "#A50B5E"}, - {"name": "Jelly Bean", "hex": "#DA614E"}, - {"name": "Jet", "hex": "#343434"}, - {"name": "Jonquil", "hex": "#F4CA16"}, - {"name": "Jordy blue", "hex": "#8AB9F1"}, - {"name": "June bud", "hex": "#BDDA57"}, - {"name": "Jungle green", "hex": "#29AB87"}, - {"name": "Kelly green", "hex": "#4CBB17"}, - {"name": "Kenyan copper", "hex": "#7C1C05"}, - {"name": "Keppel", "hex": "#3AB09E"}, - {"name": "Key Lime", "hex": "#E8F48C"}, - {"name": "Khaki (HTML/CSS) (Khaki)", "hex": "#C3B091"}, - {"name": "Khaki (X11) (Light khaki)", "hex": "#F0E68C"}, - {"name": "Kiwi", "hex": "#8EE53F"}, - {"name": "Kobe", "hex": "#882D17"}, - {"name": "Kobi", "hex": "#E79FC4"}, - {"name": "Kobicha", "hex": "#6B4423"}, - {"name": "Kombu green", "hex": "#354230"}, - {"name": "KSU Purple", "hex": "#512888"}, - {"name": "KU Crimson", "hex": "#E8000D"}, - {"name": "La Salle Green", "hex": "#087830"}, - {"name": "Languid lavender", "hex": "#D6CADD"}, - {"name": "Lapis lazuli", "hex": "#26619C"}, - {"name": "Laser Lemon", "hex": "#FFFF66"}, - {"name": "Laurel green", "hex": "#A9BA9D"}, - {"name": "Lava", "hex": "#CF1020"}, - {"name": "Lavender (floral)", "hex": "#B57EDC"}, - {"name": "Lavender (web)", "hex": "#E6E6FA"}, - {"name": "Lavender blue", "hex": "#CCCCFF"}, - {"name": "Lavender blush", "hex": "#FFF0F5"}, - {"name": "Lavender gray", "hex": "#C4C3D0"}, - {"name": "Lavender indigo", "hex": "#9457EB"}, - {"name": "Lavender magenta", "hex": "#EE82EE"}, - {"name": "Lavender mist", "hex": "#E6E6FA"}, - {"name": "Lavender pink", "hex": "#FBAED2"}, - {"name": "Lavender purple", "hex": "#967BB6"}, - {"name": "Lavender rose", "hex": "#FBA0E3"}, - {"name": "Lawn green", "hex": "#7CFC00"}, - {"name": "Lemon", "hex": "#FFF700"}, - {"name": "Lemon chiffon", "hex": "#FFFACD"}, - {"name": "Lemon curry", "hex": "#CCA01D"}, - {"name": "Lemon glacier", "hex": "#FDFF00"}, - {"name": "Lemon lime", "hex": "#E3FF00"}, - {"name": "Lemon meringue", "hex": "#F6EABE"}, - {"name": "Lemon yellow", "hex": "#FFF44F"}, - {"name": "Licorice", "hex": "#1A1110"}, - {"name": "Liberty", "hex": "#545AA7"}, - {"name": "Light apricot", "hex": "#FDD5B1"}, - {"name": "Light blue", "hex": "#ADD8E6"}, - {"name": "Light brown", "hex": "#B5651D"}, - {"name": "Light carmine pink", "hex": "#E66771"}, - {"name": "Light cobalt blue", "hex": "#88ACE0"}, - {"name": "Light coral", "hex": "#F08080"}, - {"name": "Light cornflower blue", "hex": "#93CCEA"}, - {"name": "Light crimson", "hex": "#F56991"}, - {"name": "Light cyan", "hex": "#E0FFFF"}, - {"name": "Light deep pink", "hex": "#FF5CCD"}, - {"name": "Light French beige", "hex": "#C8AD7F"}, - {"name": "Light fuchsia pink", "hex": "#F984EF"}, - {"name": "Light goldenrod yellow", "hex": "#FAFAD2"}, - {"name": "Light gray", "hex": "#D3D3D3"}, - {"name": "Light grayish magenta", "hex": "#CC99CC"}, - {"name": "Light green", "hex": "#90EE90"}, - {"name": "Light hot pink", "hex": "#FFB3DE"}, - {"name": "Light khaki", "hex": "#F0E68C"}, - {"name": "Light medium orchid", "hex": "#D39BCB"}, - {"name": "Light moss green", "hex": "#ADDFAD"}, - {"name": "Light orchid", "hex": "#E6A8D7"}, - {"name": "Light pastel purple", "hex": "#B19CD9"}, - {"name": "Light pink", "hex": "#FFB6C1"}, - {"name": "Light red ochre", "hex": "#E97451"}, - {"name": "Light salmon", "hex": "#FFA07A"}, - {"name": "Light salmon pink", "hex": "#FF9999"}, - {"name": "Light sea green", "hex": "#20B2AA"}, - {"name": "Light sky blue", "hex": "#87CEFA"}, - {"name": "Light slate gray", "hex": "#778899"}, - {"name": "Light steel blue", "hex": "#B0C4DE"}, - {"name": "Light taupe", "hex": "#B38B6D"}, - {"name": "Light Thulian pink", "hex": "#E68FAC"}, - {"name": "Light yellow", "hex": "#FFFFE0"}, - {"name": "Lilac", "hex": "#C8A2C8"}, - {"name": "Lilac Luster", "hex": "#AE98AA"}, - {"name": "Lime (color wheel)", "hex": "#BFFF00"}, - {"name": "Lime (web) (X11 green)", "hex": "#00FF00"}, - {"name": "Lime green", "hex": "#32CD32"}, - {"name": "Limerick", "hex": "#9DC209"}, - {"name": "Lincoln green", "hex": "#195905"}, - {"name": "Linen", "hex": "#FAF0E6"}, - {"name": "Loeen(lopen)look/vomit+indogo+Lopen+Gabriel", - "hex": "#15F2FD"}, - {"name": "Liseran Purple", "hex": "#DE6FA1"}, - {"name": "Little boy blue", "hex": "#6CA0DC"}, - {"name": "Liver", "hex": "#674C47"}, - {"name": "Liver (dogs)", "hex": "#B86D29"}, - {"name": "Liver (organ)", "hex": "#6C2E1F"}, - {"name": "Liver chestnut", "hex": "#987456"}, - {"name": "Livid", "hex": "#6699CC"}, - {"name": "Lumber", "hex": "#FFE4CD"}, - {"name": "Lust", "hex": "#E62020"}, - {"name": "Maastricht Blue", "hex": "#001C3D"}, - {"name": "Macaroni and Cheese", "hex": "#FFBD88"}, - {"name": "Madder Lake", "hex": "#CC3336"}, - {"name": "Magenta", "hex": "#FF00FF"}, - {"name": "Magenta (Crayola)", "hex": "#FF55A3"}, - {"name": "Magenta (dye)", "hex": "#CA1F7B"}, - {"name": "Magenta (Pantone)", "hex": "#D0417E"}, - {"name": "Magenta (process)", "hex": "#FF0090"}, - {"name": "Magenta haze", "hex": "#9F4576"}, - {"name": "Magenta-pink", "hex": "#CC338B"}, - {"name": "Magic mint", "hex": "#AAF0D1"}, - {"name": "Magic Potion", "hex": "#FF4466"}, - {"name": "Magnolia", "hex": "#F8F4FF"}, - {"name": "Mahogany", "hex": "#C04000"}, - {"name": "Maize", "hex": "#FBEC5D"}, - {"name": "Majorelle Blue", "hex": "#6050DC"}, - {"name": "Malachite", "hex": "#0BDA51"}, - {"name": "Manatee", "hex": "#979AAA"}, - {"name": "Mandarin", "hex": "#F37A48"}, - {"name": "Mango Tango", "hex": "#FF8243"}, - {"name": "Mantis", "hex": "#74C365"}, - {"name": "Mardi Gras", "hex": "#880085"}, - {"name": "Marigold", "hex": "#EAA221"}, - {"name": "Maroon (Crayola)", "hex": "#C32148"}, - {"name": "Maroon (HTML/CSS)", "hex": "#800000"}, - {"name": "Maroon (X11)", "hex": "#B03060"}, - {"name": "Mauve", "hex": "#E0B0FF"}, - {"name": "Mauve taupe", "hex": "#915F6D"}, - {"name": "Mauvelous", "hex": "#EF98AA"}, - {"name": "Maximum Blue", "hex": "#47ABCC"}, - {"name": "Maximum Blue Green", "hex": "#30BFBF"}, - {"name": "Maximum Blue Purple", "hex": "#ACACE6"}, - {"name": "Maximum Green", "hex": "#5E8C31"}, - {"name": "Maximum Green Yellow", "hex": "#D9E650"}, - {"name": "Maximum Purple", "hex": "#733380"}, - {"name": "Maximum Red", "hex": "#D92121"}, - {"name": "Maximum Red Purple", "hex": "#A63A79"}, - {"name": "Maximum Yellow", "hex": "#FAFA37"}, - {"name": "Maximum Yellow Red", "hex": "#F2BA49"}, - {"name": "May green", "hex": "#4C9141"}, - {"name": "Maya blue", "hex": "#73C2FB"}, - {"name": "Meat brown", "hex": "#E5B73B"}, - {"name": "Medium aquamarine", "hex": "#66DDAA"}, - {"name": "Medium blue", "hex": "#0000CD"}, - {"name": "Medium candy apple red", "hex": "#E2062C"}, - {"name": "Medium carmine", "hex": "#AF4035"}, - {"name": "Medium champagne", "hex": "#F3E5AB"}, - {"name": "Medium electric blue", "hex": "#035096"}, - {"name": "Medium jungle green", "hex": "#1C352D"}, - {"name": "Medium lavender magenta", "hex": "#DDA0DD"}, - {"name": "Medium orchid", "hex": "#BA55D3"}, - {"name": "Medium Persian blue", "hex": "#0067A5"}, - {"name": "Medium purple", "hex": "#9370DB"}, - {"name": "Medium red-violet", "hex": "#BB3385"}, - {"name": "Medium ruby", "hex": "#AA4069"}, - {"name": "Medium sea green", "hex": "#3CB371"}, - {"name": "Medium sky blue", "hex": "#80DAEB"}, - {"name": "Medium slate blue", "hex": "#7B68EE"}, - {"name": "Medium spring bud", "hex": "#C9DC87"}, - {"name": "Medium spring green", "hex": "#00FA9A"}, - {"name": "Medium taupe", "hex": "#674C47"}, - {"name": "Medium turquoise", "hex": "#48D1CC"}, - {"name": "Medium Tuscan red", "hex": "#79443B"}, - {"name": "Medium vermilion", "hex": "#D9603B"}, - {"name": "Medium violet-red", "hex": "#C71585"}, - {"name": "Mellow apricot", "hex": "#F8B878"}, - {"name": "Mellow yellow", "hex": "#F8DE7E"}, - {"name": "Melon", "hex": "#FDBCB4"}, - {"name": "Metallic Seaweed", "hex": "#0A7E8C"}, - {"name": "Metallic Sunburst", "hex": "#9C7C38"}, - {"name": "Mexican pink", "hex": "#E4007C"}, - {"name": "Middle Blue", "hex": "#7ED4E6"}, - {"name": "Middle Blue Green", "hex": "#8DD9CC"}, - {"name": "Middle Blue Purple", "hex": "#8B72BE"}, - {"name": "Middle Red Purple", "hex": "#210837"}, - {"name": "Middle Green", "hex": "#4D8C57"}, - {"name": "Middle Green Yellow", "hex": "#ACBF60"}, - {"name": "Middle Purple", "hex": "#D982B5"}, - {"name": "Middle Red", "hex": "#E58E73"}, - {"name": "Middle Red Purple", "hex": "#A55353"}, - {"name": "Middle Yellow", "hex": "#FFEB00"}, - {"name": "Middle Yellow Red", "hex": "#ECB176"}, - {"name": "Midnight", "hex": "#702670"}, - {"name": "Midnight blue", "hex": "#191970"}, - {"name": "Midnight green (eagle green)", "hex": "#004953"}, - {"name": "Mikado yellow", "hex": "#FFC40C"}, - {"name": "Milk", "hex": "#FDFFF5"}, - {"name": "Mimi Pink", "hex": "#FFDAE9"}, - {"name": "Mindaro", "hex": "#E3F988"}, - {"name": "Ming", "hex": "#36747D"}, - {"name": "Minion Yellow", "hex": "#F5E050"}, - {"name": "Mint", "hex": "#3EB489"}, - {"name": "Mint cream", "hex": "#F5FFFA"}, - {"name": "Mint green", "hex": "#98FF98"}, - {"name": "Misty Moss", "hex": "#BBB477"}, - {"name": "Misty rose", "hex": "#FFE4E1"}, - {"name": "Moccasin", "hex": "#FAEBD7"}, - {"name": "Mode beige", "hex": "#967117"}, - {"name": "Moonstone blue", "hex": "#73A9C2"}, - {"name": "Mordant red 19", "hex": "#AE0C00"}, - {"name": "Moss green", "hex": "#8A9A5B"}, - {"name": "Mountain Meadow", "hex": "#30BA8F"}, - {"name": "Mountbatten pink", "hex": "#997A8D"}, - {"name": "MSU Green", "hex": "#18453B"}, - {"name": "Mughal green", "hex": "#306030"}, - {"name": "Mulberry", "hex": "#C54B8C"}, - {"name": "Mummy's Tomb", "hex": "#828E84"}, - {"name": "Mustard", "hex": "#FFDB58"}, - {"name": "Myrtle green", "hex": "#317873"}, - {"name": "Mystic", "hex": "#D65282"}, - {"name": "Mystic Maroon", "hex": "#AD4379"}, - {"name": "Nadeshiko pink", "hex": "#F6ADC6"}, - {"name": "Napier green", "hex": "#2A8000"}, - {"name": "Naples yellow", "hex": "#FADA5E"}, - {"name": "Navajo white", "hex": "#FFDEAD"}, - {"name": "Navy", "hex": "#000080"}, - {"name": "Navy purple", "hex": "#9457EB"}, - {"name": "Neon Carrot", "hex": "#FFA343"}, - {"name": "Neon fuchsia", "hex": "#FE4164"}, - {"name": "Neon green", "hex": "#39FF14"}, - {"name": "New Car", "hex": "#214FC6"}, - {"name": "New York pink", "hex": "#D7837F"}, - {"name": "Nickel", "hex": "#727472"}, - {"name": "Non-photo blue", "hex": "#A4DDED"}, - {"name": "North Texas Green", "hex": "#059033"}, - {"name": "Nyanza", "hex": "#E9FFDB"}, - {"name": "Ocean Blue", "hex": "#4F42B5"}, - {"name": "Ocean Boat Blue", "hex": "#0077BE"}, - {"name": "Ocean Green", "hex": "#48BF91"}, - {"name": "Ochre", "hex": "#CC7722"}, - {"name": "Office green", "hex": "#008000"}, - {"name": "Ogre Odor", "hex": "#FD5240"}, - {"name": "Old burgundy", "hex": "#43302E"}, - {"name": "Old gold", "hex": "#CFB53B"}, - {"name": "Old heliotrope", "hex": "#563C5C"}, - {"name": "Old lace", "hex": "#FDF5E6"}, - {"name": "Old lavender", "hex": "#796878"}, - {"name": "Old mauve", "hex": "#673147"}, - {"name": "Old moss green", "hex": "#867E36"}, - {"name": "Old rose", "hex": "#C08081"}, - {"name": "Old silver", "hex": "#848482"}, - {"name": "Olive", "hex": "#808000"}, - {"name": "Olive Drab (#3)", "hex": "#6B8E23"}, - {"name": "Olive Drab #7", "hex": "#3C341F"}, - {"name": "Olivine", "hex": "#9AB973"}, - {"name": "Onyx", "hex": "#353839"}, - {"name": "Opera mauve", "hex": "#B784A7"}, - {"name": "Orange (color wheel)", "hex": "#FF7F00"}, - {"name": "Orange (Crayola)", "hex": "#FF7538"}, - {"name": "Orange (Pantone)", "hex": "#FF5800"}, - {"name": "Orange (RYB)", "hex": "#FB9902"}, - {"name": "Orange (web)", "hex": "#FFA500"}, - {"name": "Orange peel", "hex": "#FF9F00"}, - {"name": "Orange-red", "hex": "#FF4500"}, - {"name": "Orange Soda", "hex": "#FA5B3D"}, - {"name": "Orange-yellow", "hex": "#F8D568"}, - {"name": "Orchid", "hex": "#DA70D6"}, - {"name": "Orchid pink", "hex": "#F2BDCD"}, - {"name": "Orioles orange", "hex": "#FB4F14"}, - {"name": "Otter brown", "hex": "#654321"}, - {"name": "Outer Space", "hex": "#414A4C"}, - {"name": "Outrageous Orange", "hex": "#FF6E4A"}, - {"name": "Oxford Blue", "hex": "#002147"}, - {"name": "OU Crimson Red", "hex": "#990000"}, - {"name": "Pacific Blue", "hex": "#1CA9C9"}, - {"name": "Pakistan green", "hex": "#006600"}, - {"name": "Palatinate blue", "hex": "#273BE2"}, - {"name": "Palatinate purple", "hex": "#682860"}, - {"name": "Pale aqua", "hex": "#BCD4E6"}, - {"name": "Pale blue", "hex": "#AFEEEE"}, - {"name": "Pale brown", "hex": "#987654"}, - {"name": "Pale carmine", "hex": "#AF4035"}, - {"name": "Pale cerulean", "hex": "#9BC4E2"}, - {"name": "Pale chestnut", "hex": "#DDADAF"}, - {"name": "Pale copper", "hex": "#DA8A67"}, - {"name": "Pale cornflower blue", "hex": "#ABCDEF"}, - {"name": "Pale cyan", "hex": "#87D3F8"}, - {"name": "Pale gold", "hex": "#E6BE8A"}, - {"name": "Pale goldenrod", "hex": "#EEE8AA"}, - {"name": "Pale green", "hex": "#98FB98"}, - {"name": "Pale lavender", "hex": "#DCD0FF"}, - {"name": "Pale magenta", "hex": "#F984E5"}, - {"name": "Pale magenta-pink", "hex": "#FF99CC"}, - {"name": "Pale pink", "hex": "#FADADD"}, - {"name": "Pale plum", "hex": "#DDA0DD"}, - {"name": "Pale red-violet", "hex": "#DB7093"}, - {"name": "Pale robin egg blue", "hex": "#96DED1"}, - {"name": "Pale silver", "hex": "#C9C0BB"}, - {"name": "Pale spring bud", "hex": "#ECEBBD"}, - {"name": "Pale taupe", "hex": "#BC987E"}, - {"name": "Pale turquoise", "hex": "#AFEEEE"}, - {"name": "Pale violet", "hex": "#CC99FF"}, - {"name": "Pale violet-red", "hex": "#DB7093"}, - {"name": "Palm Leaf", "hex": "#6F9940"}, - {"name": "Pansy purple", "hex": "#78184A"}, - {"name": "Paolo Veronese green", "hex": "#009B7D"}, - {"name": "Papaya whip", "hex": "#FFEFD5"}, - {"name": "Paradise pink", "hex": "#E63E62"}, - {"name": "Paris Green", "hex": "#50C878"}, - {"name": "Parrot Pink", "hex": "#D998A0"}, - {"name": "Pastel blue", "hex": "#AEC6CF"}, - {"name": "Pastel brown", "hex": "#836953"}, - {"name": "Pastel gray", "hex": "#CFCFC4"}, - {"name": "Pastel green", "hex": "#77DD77"}, - {"name": "Pastel magenta", "hex": "#F49AC2"}, - {"name": "Pastel orange", "hex": "#FFB347"}, - {"name": "Pastel pink", "hex": "#DEA5A4"}, - {"name": "Pastel purple", "hex": "#B39EB5"}, - {"name": "Pastel red", "hex": "#FF6961"}, - {"name": "Pastel violet", "hex": "#CB99C9"}, - {"name": "Pastel yellow", "hex": "#FDFD96"}, - {"name": "Patriarch", "hex": "#800080"}, - {"name": "Payne's grey", "hex": "#536878"}, - {"name": "Peach", "hex": "#FFE5B4"}, - {"name": "Peach", "hex": "#FFCBA4"}, - {"name": "Peach-orange", "hex": "#FFCC99"}, - {"name": "Peach puff", "hex": "#FFDAB9"}, - {"name": "Peach-yellow", "hex": "#FADFAD"}, - {"name": "Pear", "hex": "#D1E231"}, - {"name": "Pearl", "hex": "#EAE0C8"}, - {"name": "Pearl Aqua", "hex": "#88D8C0"}, - {"name": "Pearly purple", "hex": "#B768A2"}, - {"name": "Peridot", "hex": "#E6E200"}, - {"name": "Periwinkle", "hex": "#CCCCFF"}, - {"name": "Permanent Geranium Lake", "hex": "#E12C2C"}, - {"name": "Persian blue", "hex": "#1C39BB"}, - {"name": "Persian green", "hex": "#00A693"}, - {"name": "Persian indigo", "hex": "#32127A"}, - {"name": "Persian orange", "hex": "#D99058"}, - {"name": "Persian pink", "hex": "#F77FBE"}, - {"name": "Persian plum", "hex": "#701C1C"}, - {"name": "Persian red", "hex": "#CC3333"}, - {"name": "Persian rose", "hex": "#FE28A2"}, - {"name": "Persimmon", "hex": "#EC5800"}, - {"name": "Peru", "hex": "#CD853F"}, - {"name": "Pewter Blue", "hex": "#8BA8B7"}, - {"name": "Phlox", "hex": "#DF00FF"}, - {"name": "Phthalo blue", "hex": "#000F89"}, - {"name": "Phthalo green", "hex": "#123524"}, - {"name": "Picton blue", "hex": "#45B1E8"}, - {"name": "Pictorial carmine", "hex": "#C30B4E"}, - {"name": "Piggy pink", "hex": "#FDDDE6"}, - {"name": "Pine green", "hex": "#01796F"}, - {"name": "Pineapple", "hex": "#563C5C"}, - {"name": "Pink", "hex": "#FFC0CB"}, - {"name": "Pink (Pantone)", "hex": "#D74894"}, - {"name": "Pink Flamingo", "hex": "#FC74FD"}, - {"name": "Pink lace", "hex": "#FFDDF4"}, - {"name": "Pink lavender", "hex": "#D8B2D1"}, - {"name": "Pink-orange", "hex": "#FF9966"}, - {"name": "Pink pearl", "hex": "#E7ACCF"}, - {"name": "Pink raspberry", "hex": "#980036"}, - {"name": "Pink Sherbet", "hex": "#F78FA7"}, - {"name": "Pistachio", "hex": "#93C572"}, - {"name": "Pixie Powder", "hex": "#391285"}, - {"name": "Platinum", "hex": "#E5E4E2"}, - {"name": "Plum", "hex": "#8E4585"}, - {"name": "Plum (web)", "hex": "#DDA0DD"}, - {"name": "Plump Purple", "hex": "#5946B2"}, - {"name": "Polished Pine", "hex": "#5DA493"}, - {"name": "Pomp and Power", "hex": "#86608E"}, - {"name": "Popstar", "hex": "#BE4F62"}, - {"name": "Portland Orange", "hex": "#FF5A36"}, - {"name": "Powder blue", "hex": "#B0E0E6"}, - {"name": "Princess Perfume", "hex": "#FF85CF"}, - {"name": "Princeton orange", "hex": "#F58025"}, - {"name": "Prune", "hex": "#701C1C"}, - {"name": "Prussian blue", "hex": "#003153"}, - {"name": "Psychedelic purple", "hex": "#DF00FF"}, - {"name": "Puce", "hex": "#CC8899"}, - {"name": "Puce red", "hex": "#722F37"}, - {"name": "Pullman Brown (UPS Brown)", "hex": "#644117"}, - {"name": "Pullman Green", "hex": "#3B331C"}, - {"name": "Pumpkin", "hex": "#FF7518"}, - {"name": "Purple (HTML)", "hex": "#800080"}, - {"name": "Purple (Munsell)", "hex": "#9F00C5"}, - {"name": "Purple (X11)", "hex": "#A020F0"}, - {"name": "Purple Heart", "hex": "#69359C"}, - {"name": "Purple mountain majesty", "hex": "#9678B6"}, - {"name": "Purple navy", "hex": "#4E5180"}, - {"name": "Purple pizzazz", "hex": "#FE4EDA"}, - {"name": "Purple Plum", "hex": "#9C51B6"}, - {"name": "Purple taupe", "hex": "#50404D"}, - {"name": "Purpureus", "hex": "#9A4EAE"}, - {"name": "Quartz", "hex": "#51484F"}, - {"name": "Queen blue", "hex": "#436B95"}, - {"name": "Queen pink", "hex": "#E8CCD7"}, - {"name": "Quick Silver", "hex": "#A6A6A6"}, - {"name": "Quinacridone magenta", "hex": "#8E3A59"}, - {"name": "Rackley", "hex": "#5D8AA8"}, - {"name": "Radical Red", "hex": "#FF355E"}, - {"name": "Raisin black", "hex": "#242124"}, - {"name": "Rajah", "hex": "#FBAB60"}, - {"name": "Raspberry", "hex": "#E30B5D"}, - {"name": "Raspberry glace", "hex": "#915F6D"}, - {"name": "Raspberry pink", "hex": "#E25098"}, - {"name": "Raspberry rose", "hex": "#B3446C"}, - {"name": "Raw Sienna", "hex": "#D68A59"}, - {"name": "Raw umber", "hex": "#826644"}, - {"name": "Razzle dazzle rose", "hex": "#FF33CC"}, - {"name": "Razzmatazz", "hex": "#E3256B"}, - {"name": "Razzmic Berry", "hex": "#8D4E85"}, - {"name": "Rebecca Purple", "hex": "#663399"}, - {"name": "Red", "hex": "#FF0000"}, - {"name": "Red (Crayola)", "hex": "#EE204D"}, - {"name": "Red (Munsell)", "hex": "#F2003C"}, - {"name": "Red (NCS)", "hex": "#C40233"}, - {"name": "Red (Pantone)", "hex": "#ED2939"}, - {"name": "Red (pigment)", "hex": "#ED1C24"}, - {"name": "Red (RYB)", "hex": "#FE2712"}, - {"name": "Red-brown", "hex": "#A52A2A"}, - {"name": "Red devil", "hex": "#860111"}, - {"name": "Red-orange", "hex": "#FF5349"}, - {"name": "Red-purple", "hex": "#E40078"}, - {"name": "Red Salsa", "hex": "#FD3A4A"}, - {"name": "Red-violet", "hex": "#C71585"}, - {"name": "Redwood", "hex": "#A45A52"}, - {"name": "Regalia", "hex": "#522D80"}, - {"name": "Registration black", "hex": "#000000"}, - {"name": "Resolution blue", "hex": "#002387"}, - {"name": "Rhythm", "hex": "#777696"}, - {"name": "Rich black", "hex": "#004040"}, - {"name": "Rich black (FOGRA29)", "hex": "#010B13"}, - {"name": "Rich black (FOGRA39)", "hex": "#010203"}, - {"name": "Rich brilliant lavender", "hex": "#F1A7FE"}, - {"name": "Rich carmine", "hex": "#D70040"}, - {"name": "Rich electric blue", "hex": "#0892D0"}, - {"name": "Rich lavender", "hex": "#A76BCF"}, - {"name": "Rich lilac", "hex": "#B666D2"}, - {"name": "Rich maroon", "hex": "#B03060"}, - {"name": "Rifle green", "hex": "#444C38"}, - {"name": "Roast coffee", "hex": "#704241"}, - {"name": "Robin egg blue", "hex": "#00CCCC"}, - {"name": "Rocket metallic", "hex": "#8A7F80"}, - {"name": "Roman silver", "hex": "#838996"}, - {"name": "Rose", "hex": "#FF007F"}, - {"name": "Rose bonbon", "hex": "#F9429E"}, - {"name": "Rose Dust", "hex": "#9E5E6F"}, - {"name": "Rose ebony", "hex": "#674846"}, - {"name": "Rose gold", "hex": "#B76E79"}, - {"name": "Rose madder", "hex": "#E32636"}, - {"name": "Rose pink", "hex": "#FF66CC"}, - {"name": "Rose quartz", "hex": "#AA98A9"}, - {"name": "Rose red", "hex": "#C21E56"}, - {"name": "Rose taupe", "hex": "#905D5D"}, - {"name": "Rose vale", "hex": "#AB4E52"}, - {"name": "Rosewood", "hex": "#65000B"}, - {"name": "Rosso corsa", "hex": "#D40000"}, - {"name": "Rosy brown", "hex": "#BC8F8F"}, - {"name": "Royal azure", "hex": "#0038A8"}, - {"name": "Royal blue", "hex": "#002366"}, - {"name": "Royal blue", "hex": "#4169E1"}, - {"name": "Royal fuchsia", "hex": "#CA2C92"}, - {"name": "Royal purple", "hex": "#7851A9"}, - {"name": "Royal yellow", "hex": "#FADA5E"}, - {"name": "Ruber", "hex": "#CE4676"}, - {"name": "Rubine red", "hex": "#D10056"}, - {"name": "Ruby", "hex": "#E0115F"}, - {"name": "Ruby red", "hex": "#9B111E"}, - {"name": "Ruddy", "hex": "#FF0028"}, - {"name": "Ruddy brown", "hex": "#BB6528"}, - {"name": "Ruddy pink", "hex": "#E18E96"}, - {"name": "Rufous", "hex": "#A81C07"}, - {"name": "Russet", "hex": "#80461B"}, - {"name": "Russian green", "hex": "#679267"}, - {"name": "Russian violet", "hex": "#32174D"}, - {"name": "Rust", "hex": "#B7410E"}, - {"name": "Rusty red", "hex": "#DA2C43"}, - {"name": "Sacramento State green", "hex": "#00563F"}, - {"name": "Saddle brown", "hex": "#8B4513"}, - {"name": "Safety orange", "hex": "#FF7800"}, - {"name": "Safety orange (blaze orange)", "hex": "#FF6700"}, - {"name": "Safety yellow", "hex": "#EED202"}, - {"name": "Saffron", "hex": "#F4C430"}, - {"name": "Sage", "hex": "#BCB88A"}, - {"name": "St. Patrick's blue", "hex": "#23297A"}, - {"name": "Salmon", "hex": "#FA8072"}, - {"name": "Salmon pink", "hex": "#FF91A4"}, - {"name": "Sand", "hex": "#C2B280"}, - {"name": "Sand dune", "hex": "#967117"}, - {"name": "Sandstorm", "hex": "#ECD540"}, - {"name": "Sandy brown", "hex": "#F4A460"}, - {"name": "Sandy Tan", "hex": "#FDD9B5"}, - {"name": "Sandy taupe", "hex": "#967117"}, - {"name": "Sangria", "hex": "#92000A"}, - {"name": "Sap green", "hex": "#507D2A"}, - {"name": "Sapphire", "hex": "#0F52BA"}, - {"name": "Sapphire blue", "hex": "#0067A5"}, - {"name": "Sasquatch Socks", "hex": "#FF4681"}, - {"name": "Satin sheen gold", "hex": "#CBA135"}, - {"name": "Scarlet", "hex": "#FF2400"}, - {"name": "Scarlet", "hex": "#FD0E35"}, - {"name": "Schauss pink", "hex": "#FF91AF"}, - {"name": "School bus yellow", "hex": "#FFD800"}, - {"name": "Screamin' Green", "hex": "#66FF66"}, - {"name": "Sea blue", "hex": "#006994"}, - {"name": "Sea Foam Green", "hex": "#9FE2BF"}, - {"name": "Sea green", "hex": "#2E8B57"}, - {"name": "Sea Serpent", "hex": "#4BC7CF"}, - {"name": "Seal brown", "hex": "#59260B"}, - {"name": "Seashell", "hex": "#FFF5EE"}, - {"name": "Selective yellow", "hex": "#FFBA00"}, - {"name": "Sepia", "hex": "#704214"}, - {"name": "Shadow", "hex": "#8A795D"}, - {"name": "Shadow blue", "hex": "#778BA5"}, - {"name": "Shampoo", "hex": "#FFCFF1"}, - {"name": "Shamrock green", "hex": "#009E60"}, - {"name": "Sheen Green", "hex": "#8FD400"}, - {"name": "Shimmering Blush", "hex": "#D98695"}, - {"name": "Shiny Shamrock", "hex": "#5FA778"}, - {"name": "Shocking pink", "hex": "#FC0FC0"}, - {"name": "Shocking pink (Crayola)", "hex": "#FF6FFF"}, - {"name": "Sienna", "hex": "#882D17"}, - {"name": "Silver", "hex": "#C0C0C0"}, - {"name": "Silver chalice", "hex": "#ACACAC"}, - {"name": "Silver Lake blue", "hex": "#5D89BA"}, - {"name": "Silver pink", "hex": "#C4AEAD"}, - {"name": "Silver sand", "hex": "#BFC1C2"}, - {"name": "Sinopia", "hex": "#CB410B"}, - {"name": "Sizzling Red", "hex": "#FF3855"}, - {"name": "Sizzling Sunrise", "hex": "#FFDB00"}, - {"name": "Skobeloff", "hex": "#007474"}, - {"name": "Sky blue", "hex": "#87CEEB"}, - {"name": "Sky magenta", "hex": "#CF71AF"}, - {"name": "Slate blue", "hex": "#6A5ACD"}, - {"name": "Slate gray", "hex": "#708090"}, - {"name": "Smalt (Dark powder blue)", "hex": "#003399"}, - {"name": "Slimy Green", "hex": "#299617"}, - {"name": "Smashed Pumpkin", "hex": "#FF6D3A"}, - {"name": "Smitten", "hex": "#C84186"}, - {"name": "Smoke", "hex": "#738276"}, - {"name": "Smokey Topaz", "hex": "#832A0D"}, - {"name": "Smoky black", "hex": "#100C08"}, - {"name": "Smoky Topaz", "hex": "#933D41"}, - {"name": "Snow", "hex": "#FFFAFA"}, - {"name": "Soap", "hex": "#CEC8EF"}, - {"name": "Solid pink", "hex": "#893843"}, - {"name": "Sonic silver", "hex": "#757575"}, - {"name": "Spartan Crimson", "hex": "#9E1316"}, - {"name": "Space cadet", "hex": "#1D2951"}, - {"name": "Spanish bistre", "hex": "#807532"}, - {"name": "Spanish blue", "hex": "#0070B8"}, - {"name": "Spanish carmine", "hex": "#D10047"}, - {"name": "Spanish crimson", "hex": "#E51A4C"}, - {"name": "Spanish gray", "hex": "#989898"}, - {"name": "Spanish green", "hex": "#009150"}, - {"name": "Spanish orange", "hex": "#E86100"}, - {"name": "Spanish pink", "hex": "#F7BFBE"}, - {"name": "Spanish red", "hex": "#E60026"}, - {"name": "Spanish sky blue", "hex": "#00FFFF"}, - {"name": "Spanish violet", "hex": "#4C2882"}, - {"name": "Spanish viridian", "hex": "#007F5C"}, - {"name": "Spicy mix", "hex": "#8B5f4D"}, - {"name": "Spiro Disco Ball", "hex": "#0FC0FC"}, - {"name": "Spring bud", "hex": "#A7FC00"}, - {"name": "Spring Frost", "hex": "#87FF2A"}, - {"name": "Spring green", "hex": "#00FF7F"}, - {"name": "Star command blue", "hex": "#007BB8"}, - {"name": "Steel blue", "hex": "#4682B4"}, - {"name": "Steel pink", "hex": "#CC33CC"}, - {"name": "Steel Teal", "hex": "#5F8A8B"}, - {"name": "Stil de grain yellow", "hex": "#FADA5E"}, - {"name": "Stizza", "hex": "#990000"}, - {"name": "Stormcloud", "hex": "#4F666A"}, - {"name": "Straw", "hex": "#E4D96F"}, - {"name": "Strawberry", "hex": "#FC5A8D"}, - {"name": "Sugar Plum", "hex": "#914E75"}, - {"name": "Sunburnt Cyclops", "hex": "#FF404C"}, - {"name": "Sunglow", "hex": "#FFCC33"}, - {"name": "Sunny", "hex": "#F2F27A"}, - {"name": "Sunray", "hex": "#E3AB57"}, - {"name": "Sunset", "hex": "#FAD6A5"}, - {"name": "Sunset orange", "hex": "#FD5E53"}, - {"name": "Super pink", "hex": "#CF6BA9"}, - {"name": "Sweet Brown", "hex": "#A83731"}, - {"name": "Tan", "hex": "#D2B48C"}, - {"name": "Tangelo", "hex": "#F94D00"}, - {"name": "Tangerine", "hex": "#F28500"}, - {"name": "Tangerine yellow", "hex": "#FFCC00"}, - {"name": "Tango pink", "hex": "#E4717A"}, - {"name": "Tart Orange", "hex": "#FB4D46"}, - {"name": "Taupe", "hex": "#483C32"}, - {"name": "Taupe gray", "hex": "#8B8589"}, - {"name": "Tea green", "hex": "#D0F0C0"}, - {"name": "Tea rose", "hex": "#F88379"}, - {"name": "Tea rose", "hex": "#F4C2C2"}, - {"name": "Teal", "hex": "#008080"}, - {"name": "Teal blue", "hex": "#367588"}, - {"name": "Teal deer", "hex": "#99E6B3"}, - {"name": "Teal green", "hex": "#00827F"}, - {"name": "Telemagenta", "hex": "#CF3476"}, - {"name": "Tenné (tawny)", "hex": "#CD5700"}, - {"name": "Terra cotta", "hex": "#E2725B"}, - {"name": "Thistle", "hex": "#D8BFD8"}, - {"name": "Thulian pink", "hex": "#DE6FA1"}, - {"name": "Tickle Me Pink", "hex": "#FC89AC"}, - {"name": "Tiffany Blue", "hex": "#0ABAB5"}, - {"name": "Tiger's eye", "hex": "#E08D3C"}, - {"name": "Timberwolf", "hex": "#DBD7D2"}, - {"name": "Titanium yellow", "hex": "#EEE600"}, - {"name": "Tomato", "hex": "#FF6347"}, - {"name": "Toolbox", "hex": "#746CC0"}, - {"name": "Topaz", "hex": "#FFC87C"}, - {"name": "Tractor red", "hex": "#FD0E35"}, - {"name": "Trolley Grey", "hex": "#808080"}, - {"name": "Tropical rain forest", "hex": "#00755E"}, - {"name": "Tropical violet", "hex": "#CDA4DE"}, - {"name": "True Blue", "hex": "#0073CF"}, - {"name": "Tufts Blue", "hex": "#3E8EDE"}, - {"name": "Tulip", "hex": "#FF878D"}, - {"name": "Tumbleweed", "hex": "#DEAA88"}, - {"name": "Turkish rose", "hex": "#B57281"}, - {"name": "Turquoise", "hex": "#40E0D0"}, - {"name": "Turquoise blue", "hex": "#00FFEF"}, - {"name": "Turquoise green", "hex": "#A0D6B4"}, - {"name": "Turquoise Surf", "hex": "#00C5CD"}, - {"name": "Turtle green", "hex": "#8A9A5B"}, - {"name": "Tuscan", "hex": "#FAD6A5"}, - {"name": "Tuscan brown", "hex": "#6F4E37"}, - {"name": "Tuscan red", "hex": "#7C4848"}, - {"name": "Tuscan tan", "hex": "#A67B5B"}, - {"name": "Tuscany", "hex": "#C09999"}, - {"name": "Twilight lavender", "hex": "#8A496B"}, - {"name": "Tyrian purple", "hex": "#66023C"}, - {"name": "UA blue", "hex": "#0033AA"}, - {"name": "UA red", "hex": "#D9004C"}, - {"name": "Ube", "hex": "#8878C3"}, - {"name": "UCLA Blue", "hex": "#536895"}, - {"name": "UCLA Gold", "hex": "#FFB300"}, - {"name": "UFO Green", "hex": "#3CD070"}, - {"name": "Ultramarine", "hex": "#3F00FF"}, - {"name": "Ultramarine blue", "hex": "#4166F5"}, - {"name": "Ultra pink", "hex": "#FF6FFF"}, - {"name": "Ultra red", "hex": "#FC6C85"}, - {"name": "Umber", "hex": "#635147"}, - {"name": "Unbleached silk", "hex": "#FFDDCA"}, - {"name": "United Nations blue", "hex": "#5B92E5"}, - {"name": "University of California Gold", "hex": "#B78727"}, - {"name": "Unmellow yellow", "hex": "#FFFF66"}, - {"name": "UP Forest green", "hex": "#014421"}, - {"name": "UP Maroon", "hex": "#7B1113"}, - {"name": "Upsdell red", "hex": "#AE2029"}, - {"name": "Urobilin", "hex": "#E1AD21"}, - {"name": "USAFA blue", "hex": "#004F98"}, - {"name": "USC Cardinal", "hex": "#990000"}, - {"name": "USC Gold", "hex": "#FFCC00"}, - {"name": "University of Tennessee Orange", "hex": "#F77F00"}, - {"name": "Utah Crimson", "hex": "#D3003F"}, - {"name": "Van Dyke Brown", "hex": "#664228"}, - {"name": "Vanilla", "hex": "#F3E5AB"}, - {"name": "Vanilla ice", "hex": "#F38FA9"}, - {"name": "Vegas gold", "hex": "#C5B358"}, - {"name": "Venetian red", "hex": "#C80815"}, - {"name": "Verdigris", "hex": "#43B3AE"}, - {"name": "Vermilion", "hex": "#E34234"}, - {"name": "Vermilion", "hex": "#D9381E"}, - {"name": "Veronica", "hex": "#A020F0"}, - {"name": "Very light azure", "hex": "#74BBFB"}, - {"name": "Very light blue", "hex": "#6666FF"}, - {"name": "Very light malachite green", "hex": "#64E986"}, - {"name": "Very light tangelo", "hex": "#FFB077"}, - {"name": "Very pale orange", "hex": "#FFDFBF"}, - {"name": "Very pale yellow", "hex": "#FFFFBF"}, - {"name": "Violet", "hex": "#8F00FF"}, - {"name": "Violet (color wheel)", "hex": "#7F00FF"}, - {"name": "Violet (RYB)", "hex": "#8601AF"}, - {"name": "Violet (web)", "hex": "#EE82EE"}, - {"name": "Violet-blue", "hex": "#324AB2"}, - {"name": "Violet-red", "hex": "#F75394"}, - {"name": "Viridian", "hex": "#40826D"}, - {"name": "Viridian green", "hex": "#009698"}, - {"name": "Vista blue", "hex": "#7C9ED9"}, - {"name": "Vivid amber", "hex": "#CC9900"}, - {"name": "Vivid auburn", "hex": "#922724"}, - {"name": "Vivid burgundy", "hex": "#9F1D35"}, - {"name": "Vivid cerise", "hex": "#DA1D81"}, - {"name": "Vivid cerulean", "hex": "#00AAEE"}, - {"name": "Vivid crimson", "hex": "#CC0033"}, - {"name": "Vivid gamboge", "hex": "#FF9900"}, - {"name": "Vivid lime green", "hex": "#A6D608"}, - {"name": "Vivid malachite", "hex": "#00CC33"}, - {"name": "Vivid mulberry", "hex": "#B80CE3"}, - {"name": "Vivid orange", "hex": "#FF5F00"}, - {"name": "Vivid orange peel", "hex": "#FFA000"}, - {"name": "Vivid orchid", "hex": "#CC00FF"}, - {"name": "Vivid raspberry", "hex": "#FF006C"}, - {"name": "Vivid red", "hex": "#F70D1A"}, - {"name": "Vivid red-tangelo", "hex": "#DF6124"}, - {"name": "Vivid sky blue", "hex": "#00CCFF"}, - {"name": "Vivid tangelo", "hex": "#F07427"}, - {"name": "Vivid tangerine", "hex": "#FFA089"}, - {"name": "Vivid vermilion", "hex": "#E56024"}, - {"name": "Vivid violet", "hex": "#9F00FF"}, - {"name": "Vivid yellow", "hex": "#FFE302"}, - {"name": "Volt", "hex": "#CEFF00"}, - {"name": "Wageningen Green", "hex": "#34B233"}, - {"name": "Warm black", "hex": "#004242"}, - {"name": "Waterspout", "hex": "#A4F4F9"}, - {"name": "Weldon Blue", "hex": "#7C98AB"}, - {"name": "Wenge", "hex": "#645452"}, - {"name": "Wheat", "hex": "#F5DEB3"}, - {"name": "White", "hex": "#FFFFFF"}, - {"name": "White smoke", "hex": "#F5F5F5"}, - {"name": "Wild blue yonder", "hex": "#A2ADD0"}, - {"name": "Wild orchid", "hex": "#D470A2"}, - {"name": "Wild Strawberry", "hex": "#FF43A4"}, - {"name": "Wild watermelon", "hex": "#FC6C85"}, - {"name": "Willpower orange", "hex": "#FD5800"}, - {"name": "Windsor tan", "hex": "#A75502"}, - {"name": "Wine", "hex": "#722F37"}, - {"name": "Wine dregs", "hex": "#673147"}, - {"name": "Winter Sky", "hex": "#FF007C"}, - {"name": "Winter Wizard", "hex": "#A0E6FF"}, - {"name": "Wintergreen Dream", "hex": "#56887D"}, - {"name": "Wisteria", "hex": "#C9A0DC"}, - {"name": "Wood brown", "hex": "#C19A6B"}, - {"name": "Xanadu", "hex": "#738678"}, - {"name": "Yale Blue", "hex": "#0F4D92"}, - {"name": "Yankees blue", "hex": "#1C2841"}, - {"name": "Yellow", "hex": "#FFFF00"}, - {"name": "Yellow (Crayola)", "hex": "#FCE883"}, - {"name": "Yellow (Munsell)", "hex": "#EFCC00"}, - {"name": "Yellow (NCS)", "hex": "#FFD300"}, - {"name": "Yellow (Pantone)", "hex": "#FEDF00"}, - {"name": "Yellow (process)", "hex": "#FFEF00"}, - {"name": "Yellow (RYB)", "hex": "#FEFE33"}, - {"name": "Yellow-green", "hex": "#9ACD32"}, - {"name": "Yellow Orange", "hex": "#FFAE42"}, - {"name": "Yellow rose", "hex": "#FFF000"}, - {"name": "Yellow Sunshine", "hex": "#FFF700"}, - {"name": "Zaffre", "hex": "#0014A8"}, - {"name": "Zinnwaldite brown", "hex": "#2C1608"}, - {"name": "Zomp", "hex": "#39A78E"} + def __init__(self) -> None: + """Initialize the ColorManager with the predefined color catalog.""" + self.color_list: list[dict[str, str]] = [ + {"name": name, "hex": hx} for name, hx in _DEFAULT_COLORS ] - def hex_to_rgb(self, hex_value): - """ - Converts a hex color code to an RGB tuple. + def hex_to_rgb(self, hex_value: str) -> tuple[int, int, int]: + """Convert a 3- or 6-digit hex color code to an RGB tuple.""" + return _hex_to_rgb(hex_value) + + def rgb_to_hex(self, r: int, g: int, b: int) -> str: + """Convert integer RGB values in ``[0, 255]`` to an uppercase hex code.""" + return _rgb_to_hex(r, g, b) + + def closest_color_name(self, hex_value: str, space: str = "rgb") -> str: + """Find the closest named color to ``hex_value``. Parameters: - hex_value (str): A string representing a hex color code (e.g., "#FFFFFF"). + hex_value (str): Target hex color code (e.g., ``"#FF5733"`` or ``"#F53"``). + space (str): Distance metric — ``"rgb"`` (default, Euclidean sRGB), + ``"lab"`` (perceptual CIE76 in L*a*b*), or ``"cie2000"`` + (perceptual CIEDE2000). Returns: - tuple: A tuple representing the RGB values (e.g., (255, 255, 255)). - """ - hex_value = hex_value.lstrip('#') - return tuple(int(hex_value[i:i+2], 16) for i in (0, 2, 4)) + str: Name of the closest color in ``self.color_list``. - def rgb_to_hex(self, r, g, b): + Raises: + ValueError: If ``hex_value`` or ``space`` is invalid, or ``color_list`` is empty. """ - Converts RGB values to a hex color code. + if not self.color_list: + raise ValueError("color_list is empty.") + if not isinstance(space, str): + raise TypeError(f"space must be a string, got {type(space).__name__}.") - Parameters: - r (int): Red value (0-255). - g (int): Green value (0-255). - b (int): Blue value (0-255). + target_rgb = _hex_to_rgb(hex_value) + mode = space.strip().lower() + if mode not in {"rgb", "lab", "cie2000"}: + raise ValueError( + f"Unknown color space {space!r}. Use 'rgb', 'lab', or 'cie2000'." + ) - Returns: - str: A string representing the hex color code (e.g., "#FFFFFF"). - """ - return f"#{r:02X}{g:02X}{b:02X}" + closest_color = self.color_list[0]["name"] + min_distance = float("inf") - def closest_color_name(self, hex_value): - """ - Finds the closest named color to the given hex value. + if mode == "rgb": + tr, tg, tb = target_rgb + for color in self.color_list: + cr, cg, cb = _cached_rgb(color["hex"]) + if (cr, cg, cb) == target_rgb: + return color["name"] + dr = tr - cr + dg = tg - cg + db = tb - cb + dist = dr * dr + dg * dg + db * db + if dist < min_distance: + min_distance = dist + closest_color = color["name"] + return closest_color - Parameters: - hex_value (str): A string representing a hex color code (e.g., "#FFFFFF"). + target_lab = _rgb_to_lab(*target_rgb) + if mode == "lab": + tl, ta, tb_l = target_lab + for color in self.color_list: + hx = color["hex"] + if _cached_rgb(hx) == target_rgb: + return color["name"] + cl, ca, cb_l = _cached_lab(hx) + dl = tl - cl + da = ta - ca + db_v = tb_l - cb_l + dist = dl * dl + da * da + db_v * db_v + if dist < min_distance: + min_distance = dist + closest_color = color["name"] + return closest_color + + # mode == 'cie2000' + for color in self.color_list: + hx = color["hex"] + if _cached_rgb(hx) == target_rgb: + return color["name"] + dist = _ciede2000(target_lab, _cached_lab(hx)) + if dist < min_distance: + min_distance = dist + closest_color = color["name"] + return closest_color + + def get_color_by_name(self, name: str) -> dict[str, Any] | None: + """Look up a named color (case-insensitive, CSS-name friendly). + + Matches exact names first (e.g., ``"Blue"``, ``"Air Force blue (RAF)"``), + then falls back to hyphen/space-insensitive matching so standard CSS + tokens like ``"cornflowerblue"``, ``"blue violet"``, and + ``"rebeccapurple"`` also resolve. Returns: - str: The name of the closest color from the list. + dict | None: ``{'Name': str, 'Hex': str, 'RGB': tuple[int, int, int]}`` + if found, otherwise ``None``. """ - target_rgb = self.hex_to_rgb(hex_value) - closest_color = None - min_distance = float('inf') + if not isinstance(name, str): + raise TypeError(f"name must be a string, got {type(name).__name__}.") + + target = name.strip().lower() + if not target: + return None for color in self.color_list: - current_rgb = self.hex_to_rgb(color['hex']) - distance = sum((c1 - c2) ** 2 for c1, - c2 in zip(target_rgb, current_rgb)) - if distance < min_distance: - min_distance = distance - closest_color = color['name'] + if color["name"].lower() == target: + return _format_entry(color["name"], _rgb_to_hex(*_cached_rgb(color["hex"]))) - return closest_color + compact = _compact_key(target) + if compact: + for color in self.color_list: + if _compact_key(color["name"]) == compact: + return _format_entry(color["name"], _rgb_to_hex(*_cached_rgb(color["hex"]))) - def get_color_by_name(self, name): - """ - Returns the hex and RGB values of a color based on its name. + return None + + def get_color_by_hex(self, hex_value: str) -> dict[str, Any] | None: + """Return the first named color with the exact ``hex_value``, or ``None``.""" + canonical = _rgb_to_hex(*_hex_to_rgb(hex_value)) + for color in self.color_list: + if _rgb_to_hex(*_cached_rgb(color["hex"])) == canonical: + return _format_entry(color["name"], canonical) + return None + + def search_colors(self, query: str) -> list[dict[str, Any]]: + """Return all named colors whose name contains ``query`` (case-insensitive).""" + if not isinstance(query, str): + raise TypeError(f"query must be a string, got {type(query).__name__}.") + needle = query.strip().lower() + if not needle: + return [] + results: list[dict[str, Any]] = [] + for color in self.color_list: + if needle in color["name"].lower(): + results.append(_format_entry(color["name"], _rgb_to_hex(*_cached_rgb(color["hex"])))) + return results + + def get_random_color(self) -> dict[str, Any]: + """Return a randomly chosen named color as ``{'Name', 'Hex', 'RGB'}``.""" + if not self.color_list: + raise ValueError("color_list is empty.") + chosen = random.choice(self.color_list) + return _format_entry(chosen["name"], _rgb_to_hex(*_cached_rgb(chosen["hex"]))) + + def add_color(self, name: str, hex_value: str) -> dict[str, Any]: + """Add or update a custom named color in ``self.color_list``. Parameters: - name (str): The name of the color to look up (e.g., "red"). + name (str): Non-empty color name. + hex_value (str): Valid 3- or 6-digit hex color code. Returns: - dict: A dictionary containing: - - 'Name' (str): The color name in title case. - - 'Hex' (str): The uppercase hex value (e.g., "#FF0000"). - - 'RGB' (tuple): The RGB values (e.g., (255, 0, 0)). + dict: The added/updated ``{'Name', 'Hex', 'RGB'}`` color record. """ - name = name.lower() + if not isinstance(name, str): + raise TypeError(f"name must be a string, got {type(name).__name__}.") + cleaned_name = name.strip() + if not cleaned_name: + raise ValueError("Color name must not be empty.") + + rgb = _hex_to_rgb(hex_value) + canonical_hex = _rgb_to_hex(*rgb) + _HEX_TO_RGB_CACHE[canonical_hex] = rgb + + target = cleaned_name.lower() for color in self.color_list: - if color['name'].lower() == name: - hex_value = color['hex'].upper() - rgb_value = self.hex_to_rgb(color['hex']) - return { - 'Name': color['name'].title(), - 'Hex': hex_value, - 'RGB': rgb_value - } - return None \ No newline at end of file + if color["name"].lower() == target: + color["name"] = cleaned_name + color["hex"] = canonical_hex + return _format_entry(cleaned_name, canonical_hex) + + self.color_list.append({"name": cleaned_name, "hex": canonical_hex}) + return _format_entry(cleaned_name, canonical_hex) + + def remove_color(self, name: str) -> bool: + """Remove a named color (case-insensitive) from ``self.color_list``. + + Returns: + bool: ``True`` if a color was removed, ``False`` if not found. + """ + if not isinstance(name, str): + raise TypeError(f"name must be a string, got {type(name).__name__}.") + target = name.strip().lower() + for idx, color in enumerate(self.color_list): + if color["name"].lower() == target: + del self.color_list[idx] + return True + return False diff --git a/hued/conversions.py b/hued/conversions.py index 4d17f84..b71714a 100644 --- a/hued/conversions.py +++ b/hued/conversions.py @@ -1,680 +1,925 @@ -def rgb_to_hex(r, g, b): - """ - Converts RGB values to a hex color code. +"""Color space conversion and color manipulation utilities.""" + +from __future__ import annotations + +import math +import re +from collections.abc import Sequence + +__all__ = [ + "rgb_to_hex", + "hex_to_rgb", + "rgb_to_hsl", + "hsl_to_rgb", + "rgb_to_hsv", + "hsv_to_rgb", + "rgb_to_cmyk", + "cmyk_to_rgb", + "hex_to_hsl", + "hex_to_hsv", + "hex_to_cmyk", + "hsl_to_hex", + "hsl_to_hsv", + "hsl_to_cmyk", + "hsv_to_hex", + "hsv_to_hsl", + "hsv_to_cmyk", + "cmyk_to_hex", + "cmyk_to_hsv", + "cmyk_to_hsl", + "rgb_to_xyz", + "xyz_to_rgb", + "hex_to_xyz", + "xyz_to_hex", + "hsl_to_xyz", + "xyz_to_hsl", + "hsv_to_xyz", + "xyz_to_hsv", + "cmyk_to_xyz", + "xyz_to_cmyk", + "rgb_to_lab", + "lab_to_rgb", + "xyz_to_lab", + "lab_to_xyz", + "hex_to_lab", + "lab_to_hex", + "hsl_to_lab", + "lab_to_hsl", + "hsv_to_lab", + "lab_to_hsv", + "cmyk_to_lab", + "lab_to_cmyk", + "linear_to_rgb", + "blend_colors", + "invert_color", + "to_grayscale", + "adjust_lightness", + "adjust_saturation", +] + +_HEX_DIGITS_RE = re.compile(r"^[0-9A-Fa-f]+$") + +# Standard CIE D65 2-degree reference white matching the IEC 61966-2-1 sRGB matrix. +_D65_X = 0.95047 +_D65_Y = 1.00000 +_D65_Z = 1.08883 + +# Exact CIE L*a*b* transfer constants. +_LAB_EPSILON = 216.0 / 24389.0 # (6/29)^3 ~= 0.008856 +_LAB_KAPPA = 24389.0 / 27.0 # (29/3)^3 ~= 903.296296 +_LAB_DELTA = 6.0 / 29.0 + + +def _validate_real(value: float, name: str) -> float: + """Validate that ``value`` is a finite real number (rejecting ``bool``).""" + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise TypeError(f"{name} must be a real number, got {type(value).__name__}.") + if not math.isfinite(value): + raise ValueError(f"{name} must be a finite number, got {value!r}.") + return float(value) + + +def _validate_int_channel(value: int, name: str) -> int: + """Validate an integer RGB channel in ``[0, 255]`` (rejecting ``bool``).""" + if isinstance(value, bool) or not isinstance(value, int): + raise TypeError(f"{name} must be an integer in [0, 255], got {type(value).__name__}.") + if not 0 <= value <= 255: + raise ValueError(f"{name} must be in the range [0, 255], got {value}.") + return value + + +def _validate_rgb_channels(r: float, g: float, b: float) -> tuple[float, float, float]: + """Validate three RGB components in ``[0, 255]``.""" + rf = _validate_real(r, "r") + gf = _validate_real(g, "g") + bf = _validate_real(b, "b") + if not (0.0 <= rf <= 255.0 and 0.0 <= gf <= 255.0 and 0.0 <= bf <= 255.0): + raise ValueError("RGB values must be in the range [0, 255].") + return rf, gf, bf + + +def _validate_sequence(value: Sequence[float], length: int, name: str) -> tuple[float, ...]: + """Unpack and validate a fixed-length numeric tuple/list.""" + if not isinstance(value, (tuple, list)): + raise TypeError(f"{name} must be a tuple or list of {length} numbers, got {type(value).__name__}.") + if len(value) != length: + raise ValueError(f"{name} must have exactly {length} elements, got {len(value)}.") + return tuple(value) + + +def _validate_rgb_tuple(rgb: Sequence[int], name: str = "rgb") -> tuple[int, int, int]: + """Validate a 3-element integer RGB sequence in ``[0, 255]``.""" + r, g, b = _validate_sequence(rgb, 3, name) + return ( + _validate_int_channel(r, f"{name}[0]"), # type: ignore[arg-type] + _validate_int_channel(g, f"{name}[1]"), # type: ignore[arg-type] + _validate_int_channel(b, f"{name}[2]"), # type: ignore[arg-type] + ) + + +def _validate_rgb_number_tuple(rgb: Sequence[float], name: str = "rgb") -> tuple[float, float, float]: + """Validate a 3-element real RGB sequence in ``[0, 255]``.""" + r, g, b = _validate_sequence(rgb, 3, name) + return _validate_rgb_channels(r, g, b) + + +def _validate_hsl(h: float, s: float, l: float) -> tuple[float, float, float]: + hf = _validate_real(h, "h") + sf = _validate_real(s, "s") + lf = _validate_real(l, "l") + if not (0.0 <= hf < 360.0 and 0.0 <= sf <= 1.0 and 0.0 <= lf <= 1.0): + raise ValueError("HSL values must be in range: h [0, 360), s [0, 1], l [0, 1].") + return hf, sf, lf + + +def _validate_hsv(h: float, s: float, v: float) -> tuple[float, float, float]: + hf = _validate_real(h, "h") + sf = _validate_real(s, "s") + vf = _validate_real(v, "v") + if not (0.0 <= hf < 360.0 and 0.0 <= sf <= 1.0 and 0.0 <= vf <= 1.0): + raise ValueError("HSV values must be in range: h [0, 360), s [0, 1], v [0, 1].") + return hf, sf, vf + + +def _validate_cmyk(c: float, m: float, y: float, k: float) -> tuple[float, float, float, float]: + cf = _validate_real(c, "c") + mf = _validate_real(m, "m") + yf = _validate_real(y, "y") + kf = _validate_real(k, "k") + if not (0.0 <= cf <= 1.0 and 0.0 <= mf <= 1.0 and 0.0 <= yf <= 1.0 and 0.0 <= kf <= 1.0): + raise ValueError("CMYK values must be in range: c, m, y, k [0, 1].") + return cf, mf, yf, kf + + +def _validate_xyz(x: float, y: float, z: float) -> tuple[float, float, float]: + xf = _validate_real(x, "x") + yf = _validate_real(y, "y") + zf = _validate_real(z, "z") + if xf < 0.0 or yf < 0.0 or zf < 0.0: + raise ValueError("XYZ values must be non-negative.") + return xf, yf, zf + + +def _validate_lab(l: float, a: float, b: float) -> tuple[float, float, float]: + lf = _validate_real(l, "l") + af = _validate_real(a, "a") + bf = _validate_real(b, "b") + if not 0.0 <= lf <= 100.0: + raise ValueError("LAB lightness L* must be in the range [0, 100].") + return lf, af, bf + + +def _srgb_to_linear_channel(channel: float) -> float: + """Apply the IEC 61966-2-1 sRGB inverse companding function to a ``[0, 255]`` channel.""" + s = channel / 255.0 + if s <= 0.04045: + return s / 12.92 + return ((s + 0.055) / 1.055) ** 2.4 + + +def _linear_to_srgb_channel(linear: float) -> float: + """Apply the IEC 61966-2-1 sRGB companding function to a linear value, clamped to ``[0, 1]``.""" + c = max(0.0, min(1.0, linear)) + if c <= 0.0031308: + return 12.92 * c + return 1.055 * (c ** (1.0 / 2.4)) - 0.055 + + +def _wrap_hue(angle: float) -> float: + """Wrap an angle in degrees strictly into ``[0.0, 360.0)`` (handling ``-1e-15 % 360 == 360``).""" + wrapped = angle % 360.0 + if wrapped >= 360.0 or wrapped == 0.0: + return 0.0 + return wrapped + + +def _rgb_to_hsl_exact(r: float, g: float, b: float) -> tuple[float, float, float]: + """Full-precision RGB ``[0, 255]`` to HSL conversion without rounding.""" + rn, gn, bn = r / 255.0, g / 255.0, b / 255.0 + max_c = max(rn, gn, bn) + min_c = min(rn, gn, bn) + delta = max_c - min_c + l = (max_c + min_c) / 2.0 - Parameters: - r (int): Red value (0-255). - g (int): Green value (0-255). - b (int): Blue value (0-255). + if delta == 0.0: + return 0.0, 0.0, l - Returns: - str: A string representing the hex color code (e.g., "#FFFFFF"). - """ - return f"#{r:02X}{g:02X}{b:02X}" + s = delta / (1.0 - abs(2.0 * l - 1.0)) + if max_c == rn: + h = ((gn - bn) / delta) % 6.0 + elif max_c == gn: + h = (bn - rn) / delta + 2.0 + else: + h = (rn - gn) / delta + 4.0 + return _wrap_hue(h * 60.0), min(1.0, max(0.0, s)), min(1.0, max(0.0, l)) -def hex_to_rgb(hex_value): - """ - Converts a hex color code to RGB values. - Parameters: - hex_value (str): A string representing a hex color code (e.g., "#FFFFFF"). +def _rgb_to_hsv_exact(r: float, g: float, b: float) -> tuple[float, float, float]: + """Full-precision RGB ``[0, 255]`` to HSV conversion without rounding.""" + rn, gn, bn = r / 255.0, g / 255.0, b / 255.0 + max_c = max(rn, gn, bn) + min_c = min(rn, gn, bn) + delta = max_c - min_c + v = max_c - Returns: - tuple: A tuple representing the RGB values (e.g., (255, 255, 255)). - """ - hex_value = hex_value.lstrip('#') - return tuple(int(hex_value[i:i+2], 16) for i in (0, 2, 4)) + if delta == 0.0: + return 0.0, 0.0, v -def rgb_to_hsl(r, g, b): - """ - Converts RGB values to HSL (Hue, Saturation, Lightness). + s = delta / max_c + if max_c == rn: + h = ((gn - bn) / delta) % 6.0 + elif max_c == gn: + h = (bn - rn) / delta + 2.0 + else: + h = (rn - gn) / delta + 4.0 + return _wrap_hue(h * 60.0), min(1.0, max(0.0, s)), min(1.0, max(0.0, v)) - Parameters: - r (int): Red value (0-255). - g (int): Green value (0-255). - b (int): Blue value (0-255). - Returns: - tuple: A tuple representing the HSL values (h, s, l) where - h (float) is hue in the range [0, 360), - s (float) is saturation in the range [0, 1], - l (float) is lightness in the range [0, 1]. - """ - r, g, b = r / 255.0, g / 255.0, b / 255.0 - max_c, min_c = max(r, g, b), min(r, g, b) - delta = max_c - min_c - l = (max_c + min_c) / 2 +def _round_hue(h: float) -> float: + """Round hue to 2 decimal places while strictly preserving ``[0, 360)``.""" + rounded = round(h, 2) + if rounded >= 360.0 or rounded == 0.0: + return 0.0 + return rounded - if delta == 0: - h = s = 0 # achromatic - else: - s = delta / (1 - abs(2 * l - 1)) - if max_c == r: - h = ((g - b) / delta) % 6 - elif max_c == g: - h = (b - r) / delta + 2 - elif max_c == b: - h = (r - g) / delta + 4 - h *= 60 - - return round(h, 2), round(s, 2), round(l, 2) - -def hsl_to_rgb(h, s, l): - """ - Converts HSL values to RGB. + +def rgb_to_hex(r: int, g: int, b: int) -> str: + """Convert integer RGB values to an uppercase 6-digit hex color code. Parameters: - h (float): Hue in the range [0, 360). - s (float): Saturation in the range [0, 1]. - l (float): Lightness in the range [0, 1]. + r (int): Red component in ``[0, 255]``. + g (int): Green component in ``[0, 255]``. + b (int): Blue component in ``[0, 255]``. Returns: - tuple: A tuple representing the RGB values (0-255). + str: Uppercase hex color string (e.g., ``"#FF0000"``). + + Raises: + TypeError: If any component is not an integer. + ValueError: If any component is outside ``[0, 255]``. """ - c = (1 - abs(2 * l - 1)) * s - x = c * (1 - abs((h / 60) % 2 - 1)) - m = l - c/2 - - if 0 <= h < 60: - r, g, b = c, x, 0 - elif 60 <= h < 120: - r, g, b = x, c, 0 - elif 120 <= h < 180: - r, g, b = 0, c, x - elif 180 <= h < 240: - r, g, b = 0, x, c - elif 240 <= h < 300: - r, g, b = x, 0, c - elif 300 <= h < 360: - r, g, b = c, 0, x - else: - r, g, b = 0, 0, 0 + ri = _validate_int_channel(r, "r") + gi = _validate_int_channel(g, "g") + bi = _validate_int_channel(b, "b") + return f"#{ri:02X}{gi:02X}{bi:02X}" - return round((r + m) * 255), round((g + m) * 255), round((b + m) * 255) -def rgb_to_hsv(r, g, b): - """ - Converts RGB values to HSV (Hue, Saturation, Value). +def hex_to_rgb(hex_value: str) -> tuple[int, int, int]: + """Convert a 3- or 6-digit hex color code to an RGB tuple. + + Supports leading ``#`` (optional), 3-digit shorthand (e.g., ``"#F0A"``), + case-insensitive hex digits, and surrounding whitespace. Parameters: - r (int): Red value (0-255). - g (int): Green value (0-255). - b (int): Blue value (0-255). + hex_value (str): Hex color code (e.g., ``"#FFFFFF"``, ``"FF5733"``, ``"#FFF"``). Returns: - tuple: A tuple representing the HSV values (h, s, v) where - h (float) is hue in the range [0, 360), - s (float) is saturation in the range [0, 1], - v (float) is value in the range [0, 1]. - """ - r, g, b = r / 255.0, g / 255.0, b / 255.0 - max_c, min_c = max(r, g, b), min(r, g, b) - delta = max_c - min_c - v = max_c + tuple[int, int, int]: RGB values in ``[0, 255]``. - if delta == 0: - h = s = 0 # achromatic - else: - s = delta / max_c - if max_c == r: - h = ((g - b) / delta) % 6 - elif max_c == g: - h = (b - r) / delta + 2 - elif max_c == b: - h = (r - g) / delta + 4 - h *= 60 - - return round(h, 2), round(s, 2), round(v, 2) - -def hsv_to_rgb(h, s, v): + Raises: + TypeError: If ``hex_value`` is not a string. + ValueError: If ``hex_value`` is not a valid 3- or 6-digit hex color code. """ - Converts HSV values to RGB. + if not isinstance(hex_value, str): + raise TypeError(f"hex_value must be a string, got {type(hex_value).__name__}.") + + cleaned = hex_value.strip() + if cleaned.startswith("#"): + cleaned = cleaned[1:] + + if len(cleaned) == 3: + cleaned = "".join(ch * 2 for ch in cleaned) + elif len(cleaned) != 6: + raise ValueError( + f"Invalid hex color {hex_value!r}: expected 3 or 6 hexadecimal digits." + ) + + if not _HEX_DIGITS_RE.match(cleaned): + raise ValueError( + f"Invalid hex color {hex_value!r}: contains non-hexadecimal characters." + ) + + return ( + int(cleaned[0:2], 16), + int(cleaned[2:4], 16), + int(cleaned[4:6], 16), + ) + + +def rgb_to_hsl(r: int, g: int, b: int) -> tuple[float, float, float]: + """Convert RGB values to HSL (Hue, Saturation, Lightness). Parameters: - h (float): Hue in the range [0, 360). - s (float): Saturation in the range [0, 1]. - v (float): Value in the range [0, 1]. + r (int): Red value in ``[0, 255]``. + g (int): Green value in ``[0, 255]``. + b (int): Blue value in ``[0, 255]``. Returns: - tuple: A tuple representing the RGB values (0-255). + tuple[float, float, float]: ``(h, s, l)`` with ``h`` in ``[0, 360)`` + and ``s``, ``l`` in ``[0, 1]``, rounded to 2 decimal places. """ - c = v * s - x = c * (1 - abs((h / 60) % 2 - 1)) - m = v - c - - if 0 <= h < 60: - r, g, b = c, x, 0 - elif 60 <= h < 120: - r, g, b = x, c, 0 - elif 120 <= h < 180: - r, g, b = 0, c, x - elif 180 <= h < 240: - r, g, b = 0, x, c - elif 240 <= h < 300: - r, g, b = x, 0, c - elif 300 <= h < 360: - r, g, b = c, 0, x - else: - r, g, b = 0, 0, 0 + rf, gf, bf = _validate_rgb_channels(r, g, b) + h, s, l = _rgb_to_hsl_exact(rf, gf, bf) + return _round_hue(h), round(s, 2), round(l, 2) - return round((r + m) * 255), round((g + m) * 255), round((b + m) * 255) -def rgb_to_cmyk(r, g, b): - """ - Converts RGB values to CMYK (Cyan, Magenta, Yellow, Key/Black). +def hsl_to_rgb(h: float, s: float, l: float) -> tuple[int, int, int]: + """Convert HSL (Hue, Saturation, Lightness) values to RGB. Parameters: - r (int): Red value (0-255). - g (int): Green value (0-255). - b (int): Blue value (0-255). + h (float): Hue in ``[0, 360)``. + s (float): Saturation in ``[0, 1]``. + l (float): Lightness in ``[0, 1]``. Returns: - tuple: A tuple representing the CMYK values (c, m, y, k) where - c (float) is cyan in the range [0, 1], - m (float) is magenta in the range [0, 1], - y (float) is yellow in the range [0, 1], - k (float) is key/black in the range [0, 1]. - """ - if (r, g, b) == (0, 0, 0): - return 0, 0, 0, 1 + tuple[int, int, int]: RGB values in ``[0, 255]``. - c = 1 - r / 255.0 - m = 1 - g / 255.0 - y = 1 - b / 255.0 - k = min(c, m, y) + Raises: + TypeError: If any argument is not a real number. + ValueError: If any HSL component is outside its valid range. + """ + hf, sf, lf = _validate_hsl(h, s, l) + c = (1.0 - abs(2.0 * lf - 1.0)) * sf + x = c * (1.0 - abs((hf / 60.0) % 2.0 - 1.0)) + m = lf - c / 2.0 + + if hf < 60.0: + r, g, b = c, x, 0.0 + elif hf < 120.0: + r, g, b = x, c, 0.0 + elif hf < 180.0: + r, g, b = 0.0, c, x + elif hf < 240.0: + r, g, b = 0.0, x, c + elif hf < 300.0: + r, g, b = x, 0.0, c + else: + r, g, b = c, 0.0, x - c = (c - k) / (1 - k) - m = (m - k) / (1 - k) - y = (y - k) / (1 - k) + return ( + max(0, min(255, round((r + m) * 255.0))), + max(0, min(255, round((g + m) * 255.0))), + max(0, min(255, round((b + m) * 255.0))), + ) - return round(c, 2), round(m, 2), round(y, 2), round(k, 2) -def cmyk_to_rgb(c, m, y, k): - """ - Converts CMYK values to RGB. +def rgb_to_hsv(r: int, g: int, b: int) -> tuple[float, float, float]: + """Convert RGB values to HSV (Hue, Saturation, Value). Parameters: - c (float): Cyan in the range [0, 1]. - m (float): Magenta in the range [0, 1]. - y (float): Yellow in the range [0, 1]. - k (float): Key/black in the range [0, 1]. + r (int): Red value in ``[0, 255]``. + g (int): Green value in ``[0, 255]``. + b (int): Blue value in ``[0, 255]``. Returns: - tuple: A tuple representing the RGB values (0-255). + tuple[float, float, float]: ``(h, s, v)`` with ``h`` in ``[0, 360)`` + and ``s``, ``v`` in ``[0, 1]``, rounded to 2 decimal places. """ - r = 255 * (1 - c) * (1 - k) - g = 255 * (1 - m) * (1 - k) - b = 255 * (1 - y) * (1 - k) + rf, gf, bf = _validate_rgb_channels(r, g, b) + h, s, v = _rgb_to_hsv_exact(rf, gf, bf) + return _round_hue(h), round(s, 2), round(v, 2) - return round(r), round(g), round(b) -def hex_to_hsl(hex_value: str) -> tuple: - """ - Converts a hex color code to HSL (Hue, Saturation, Lightness). +def hsv_to_rgb(h: float, s: float, v: float) -> tuple[int, int, int]: + """Convert HSV (Hue, Saturation, Value) values to RGB. Parameters: - hex_value (str): A string representing a hex color code (e.g., "#FFFFFF"). + h (float): Hue in ``[0, 360)``. + s (float): Saturation in ``[0, 1]``. + v (float): Value in ``[0, 1]``. Returns: - tuple: A tuple representing the HSL values (h, s, l) where - h (float) is hue in the range [0, 360), - s (float) is saturation in the range [0, 1], - l (float) is lightness in the range [0, 1]. - """ - rgb = hex_to_rgb(hex_value) - return rgb_to_hsl(*rgb) + tuple[int, int, int]: RGB values in ``[0, 255]``. -def hex_to_hsv(hex_value: str) -> tuple: - """ - Converts a hex color code to HSV (Hue, Saturation, Value). + Raises: + TypeError: If any argument is not a real number. + ValueError: If any HSV component is outside its valid range. + """ + hf, sf, vf = _validate_hsv(h, s, v) + c = vf * sf + x = c * (1.0 - abs((hf / 60.0) % 2.0 - 1.0)) + m = vf - c + + if hf < 60.0: + r, g, b = c, x, 0.0 + elif hf < 120.0: + r, g, b = x, c, 0.0 + elif hf < 180.0: + r, g, b = 0.0, c, x + elif hf < 240.0: + r, g, b = 0.0, x, c + elif hf < 300.0: + r, g, b = x, 0.0, c + else: + r, g, b = c, 0.0, x - Parameters: - hex_value (str): A string representing a hex color code (e.g., "#FFFFFF"). + return ( + max(0, min(255, round((r + m) * 255.0))), + max(0, min(255, round((g + m) * 255.0))), + max(0, min(255, round((b + m) * 255.0))), + ) - Returns: - tuple: A tuple representing the HSV values (h, s, v) where - h (float) is hue in the range [0, 360), - s (float) is saturation in the range [0, 1], - v (float) is value in the range [0, 1]. - """ - rgb = hex_to_rgb(hex_value) - return rgb_to_hsv(*rgb) -def hex_to_cmyk(hex_value: str) -> tuple: - """ - Converts a hex color code to CMYK (Cyan, Magenta, Yellow, Key/Black). +def rgb_to_cmyk(r: int, g: int, b: int) -> tuple[float, float, float, float]: + """Convert RGB values to CMYK (Cyan, Magenta, Yellow, Key/Black). Parameters: - hex_value (str): A string representing a hex color code (e.g., "#FFFFFF"). + r (int): Red value in ``[0, 255]``. + g (int): Green value in ``[0, 255]``. + b (int): Blue value in ``[0, 255]``. Returns: - tuple: A tuple representing the CMYK values (c, m, y, k) where - c (float) is cyan in the range [0, 1], - m (float) is magenta in the range [0, 1], - y (float) is yellow in the range [0, 1], - k (float) is key/black in the range [0, 1]. + tuple[float, float, float, float]: ``(c, m, y, k)`` each in ``[0, 1]``, + rounded to 2 decimal places. """ - rgb = hex_to_rgb(hex_value) - return rgb_to_cmyk(*rgb) + rf, gf, bf = _validate_rgb_channels(r, g, b) + if rf == 0.0 and gf == 0.0 and bf == 0.0: + return 0.0, 0.0, 0.0, 1.0 -def hsl_to_hex(hsl_value: tuple) -> str: - """ - Converts HSL (Hue, Saturation, Lightness) to a hex color code. + c = 1.0 - rf / 255.0 + m = 1.0 - gf / 255.0 + y = 1.0 - bf / 255.0 + k = min(c, m, y) + + denom = 1.0 - k + c = (c - k) / denom + m = (m - k) / denom + y = (y - k) / denom + + return round(c, 2), round(m, 2), round(y, 2), round(k, 2) + + +def cmyk_to_rgb(c: float, m: float, y: float, k: float) -> tuple[int, int, int]: + """Convert CMYK values to RGB. Parameters: - hsl_value (tuple): A tuple representing the HSL values (h, s, l) where - h (float) is hue in the range [0, 360), - s (float) is saturation in the range [0, 1], - l (float) is lightness in the range [0, 1]. + c (float): Cyan in ``[0, 1]``. + m (float): Magenta in ``[0, 1]``. + y (float): Yellow in ``[0, 1]``. + k (float): Key/black in ``[0, 1]``. Returns: - str: A string representing the hex color code (e.g., "#FFFFFF"). + tuple[int, int, int]: RGB values in ``[0, 255]``. Raises: - ValueError: If the HSL values are out of range. + TypeError: If any argument is not a real number. + ValueError: If any CMYK component is outside ``[0, 1]``. """ - h, s, l = hsl_value - if not (0 <= h < 360 and 0 <= s <= 1 and 0 <= l <= 1): - raise ValueError("HSL values must be in range: h [0, 360), s [0, 1], l [0, 1]") + cf, mf, yf, kf = _validate_cmyk(c, m, y, k) + r = 255.0 * (1.0 - cf) * (1.0 - kf) + g = 255.0 * (1.0 - mf) * (1.0 - kf) + b = 255.0 * (1.0 - yf) * (1.0 - kf) + return round(r), round(g), round(b) - return rgb_to_hex(*hsl_to_rgb(h, s, l)) -def hsl_to_hsv(hsl_value: tuple) -> tuple: - """ - Converts HSL (Hue, Saturation, Lightness) to HSV (Hue, Saturation, Value). +def hex_to_hsl(hex_value: str) -> tuple[float, float, float]: + """Convert a hex color code to HSL.""" + return rgb_to_hsl(*hex_to_rgb(hex_value)) - Parameters: - hsl_value (tuple): A tuple representing the HSL values (h, s, l) where - h (float) is hue in the range [0, 360), - s (float) is saturation in the range [0, 1], - l (float) is lightness in the range [0, 1]. - Returns: - tuple: A tuple representing the HSV values (h, s, v) where - h (float) is hue in the range [0, 360), - s (float) is saturation in the range [0, 1], - v (float) is value in the range [0, 1]. +def hex_to_hsv(hex_value: str) -> tuple[float, float, float]: + """Convert a hex color code to HSV.""" + return rgb_to_hsv(*hex_to_rgb(hex_value)) - Raises: - ValueError: If the HSL values are out of range. - """ - h, s, l = hsl_value - if not (0 <= h < 360 and 0 <= s <= 1 and 0 <= l <= 1): - raise ValueError("HSL values must be in range: h [0, 360), s [0, 1], l [0, 1]") - return rgb_to_hsv(*hsl_to_rgb(h, s, l)) +def hex_to_cmyk(hex_value: str) -> tuple[float, float, float, float]: + """Convert a hex color code to CMYK.""" + return rgb_to_cmyk(*hex_to_rgb(hex_value)) -def hsl_to_cmyk(hsl_value: tuple) -> tuple: - """ - Converts HSL (Hue, Saturation, Lightness) to CMYK (Cyan, Magenta, Yellow, Key/Black). - Parameters: - hsl_value (tuple): A tuple representing the HSL values (h, s, l) where - h (float) is hue in the range [0, 360), - s (float) is saturation in the range [0, 1], - l (float) is lightness in the range [0, 1]. +def hsl_to_hex(hsl_value: Sequence[float]) -> str: + """Convert an HSL tuple ``(h, s, l)`` to a hex color code.""" + h, s, l = _validate_hsl(*_validate_sequence(hsl_value, 3, "hsl_value")) + return rgb_to_hex(*hsl_to_rgb(h, s, l)) - Returns: - tuple: A tuple representing the CMYK values (c, m, y, k) where - c (float) is cyan in the range [0, 1], - m (float) is magenta in the range [0, 1], - y (float) is yellow in the range [0, 1], - k (float) is key/black in the range [0, 1]. - Raises: - ValueError: If the HSL values are out of range. - """ - h, s, l = hsl_value - if not (0 <= h < 360 and 0 <= s <= 1 and 0 <= l <= 1): - raise ValueError("HSL values must be in range: h [0, 360), s [0, 1], l [0, 1]") +def hsl_to_hsv(hsl_value: Sequence[float]) -> tuple[float, float, float]: + """Convert an HSL tuple ``(h, s, l)`` directly to HSV without 8-bit RGB loss.""" + h, s, l = _validate_hsl(*_validate_sequence(hsl_value, 3, "hsl_value")) + v = l + s * min(l, 1.0 - l) + sv = 0.0 if v == 0.0 else 2.0 * (1.0 - l / v) + hv = 0.0 if sv == 0.0 else h + return _round_hue(hv), round(sv, 2), round(v, 2) + +def hsl_to_cmyk(hsl_value: Sequence[float]) -> tuple[float, float, float, float]: + """Convert an HSL tuple ``(h, s, l)`` to CMYK.""" + h, s, l = _validate_hsl(*_validate_sequence(hsl_value, 3, "hsl_value")) return rgb_to_cmyk(*hsl_to_rgb(h, s, l)) -def hsv_to_hex(hsv_value: tuple) -> str: - """ - Converts HSV (Hue, Saturation, Value) to a hex color code. - Parameters: - hsv_value (tuple): A tuple representing the HSV values (h, s, v) where - h (float) is hue in the range [0, 360), - s (float) is saturation in the range [0, 1], - v (float) is value in the range [0, 1]. +def hsv_to_hex(hsv_value: Sequence[float]) -> str: + """Convert an HSV tuple ``(h, s, v)`` to a hex color code.""" + h, s, v = _validate_hsv(*_validate_sequence(hsv_value, 3, "hsv_value")) + return rgb_to_hex(*hsv_to_rgb(h, s, v)) - Returns: - str: A string representing the hex color code (e.g., "#FFFFFF"). - Raises: - ValueError: If the HSV values are out of range. - """ - h, s, v = hsv_value - if not (0 <= h < 360 and 0 <= s <= 1 and 0 <= v <= 1): - raise ValueError("HSV values must be in range: h [0, 360), s [0, 1], v [0, 1]") +def hsv_to_hsl(hsv_value: Sequence[float]) -> tuple[float, float, float]: + """Convert an HSV tuple ``(h, s, v)`` directly to HSL without 8-bit RGB loss.""" + h, s, v = _validate_hsv(*_validate_sequence(hsv_value, 3, "hsv_value")) + l = v * (1.0 - s / 2.0) + sl = 0.0 if (l == 0.0 or l == 1.0) else (v - l) / min(l, 1.0 - l) + hl = 0.0 if sl == 0.0 else h + return _round_hue(hl), round(sl, 2), round(l, 2) - return rgb_to_hex(*hsv_to_rgb(h, s, v)) -def hsv_to_hsl(hsv_value: tuple) -> tuple: - """ - Converts HSV (Hue, Saturation, Value) to HSL (Hue, Saturation, Lightness). +def hsv_to_cmyk(hsv_value: Sequence[float]) -> tuple[float, float, float, float]: + """Convert an HSV tuple ``(h, s, v)`` to CMYK.""" + h, s, v = _validate_hsv(*_validate_sequence(hsv_value, 3, "hsv_value")) + return rgb_to_cmyk(*hsv_to_rgb(h, s, v)) - Parameters: - hsv_value (tuple): A tuple representing the HSV values (h, s, v) where - h (float) is hue in the range [0, 360), - s (float) is saturation in the range [0, 1], - v (float) is value in the range [0, 1]. - Returns: - tuple: A tuple representing the HSL values (h, s, l) where - h (float) is hue in the range [0, 360), - s (float) is saturation in the range [0, 1], - l (float) is lightness in the range [0, 1]. +def cmyk_to_hex(cmyk_value: Sequence[float]) -> str: + """Convert a CMYK tuple ``(c, m, y, k)`` to a hex color code.""" + c, m, y, k = _validate_cmyk(*_validate_sequence(cmyk_value, 4, "cmyk_value")) + return rgb_to_hex(*cmyk_to_rgb(c, m, y, k)) - Raises: - ValueError: If the HSV values are out of range. - """ - h, s, v = hsv_value - if not (0 <= h < 360 and 0 <= s <= 1 and 0 <= v <= 1): - raise ValueError("HSV values must be in range: h [0, 360), s [0, 1], v [0, 1]") - return rgb_to_hsl(*hsv_to_rgb(h, s, v)) +def cmyk_to_hsv(cmyk_value: Sequence[float]) -> tuple[float, float, float]: + """Convert a CMYK tuple ``(c, m, y, k)`` to HSV.""" + c, m, y, k = _validate_cmyk(*_validate_sequence(cmyk_value, 4, "cmyk_value")) + return rgb_to_hsv(*cmyk_to_rgb(c, m, y, k)) -def hsv_to_cmyk(hsv_value: tuple) -> tuple: - """ - Converts HSV (Hue, Saturation, Value) to CMYK (Cyan, Magenta, Yellow, Key/Black). + +def cmyk_to_hsl(cmyk_value: Sequence[float]) -> tuple[float, float, float]: + """Convert a CMYK tuple ``(c, m, y, k)`` to HSL.""" + c, m, y, k = _validate_cmyk(*_validate_sequence(cmyk_value, 4, "cmyk_value")) + return rgb_to_hsl(*cmyk_to_rgb(c, m, y, k)) + + +def rgb_to_xyz(r: int, g: int, b: int) -> tuple[float, float, float]: + """Convert sRGB ``(r, g, b)`` to CIE 1931 XYZ (D65 standard illuminant). + + Uses the standard IEC 61966-2-1 sRGB transfer function and D65 matrix, + returning values normalized so D65 white has ``Y = 1.0``. Parameters: - hsv_value (tuple): A tuple representing the HSV values (h, s, v) where - h (float) is hue in the range [0, 360), - s (float) is saturation in the range [0, 1], - v (float) is value in the range [0, 1]. + r (int): Red component in ``[0, 255]``. + g (int): Green component in ``[0, 255]``. + b (int): Blue component in ``[0, 255]``. Returns: - tuple: A tuple representing the CMYK values (c, m, y, k) where - c (float) is cyan in the range [0, 1], - m (float) is magenta in the range [0, 1], - y (float) is yellow in the range [0, 1], - k (float) is key/black in the range [0, 1]. - - Raises: - ValueError: If the HSV values are out of range. + tuple[float, float, float]: ``(x, y, z)`` in CIE 1931 XYZ space. """ - h, s, v = hsv_value - if not (0 <= h < 360 and 0 <= s <= 1 and 0 <= v <= 1): - raise ValueError("HSV values must be in range: h [0, 360), s [0, 1], v [0, 1]") + rf, gf, bf = _validate_rgb_channels(r, g, b) + r_lin = _srgb_to_linear_channel(rf) + g_lin = _srgb_to_linear_channel(gf) + b_lin = _srgb_to_linear_channel(bf) - return rgb_to_cmyk(*hsv_to_rgb(h, s, v)) + x = 0.4124564 * r_lin + 0.3575761 * g_lin + 0.1804375 * b_lin + y = 0.2126729 * r_lin + 0.7151522 * g_lin + 0.0721749 * b_lin + z = 0.0193339 * r_lin + 0.1191920 * g_lin + 0.9503041 * b_lin -def cmyk_to_hex(cmyk_value: tuple) -> str: - """ - Converts CMYK (Cyan, Magenta, Yellow, Key/Black) to a hex color code. + return x, y, z + + +def xyz_to_rgb(x: float, y: float, z: float) -> tuple[int, int, int]: + """Convert CIE 1931 XYZ (D65) to sRGB ``(r, g, b)``. + + Uses the standard IEC 61966-2-1 inverse matrix and sRGB companding + function. Out-of-sRGB-gamut values are safely clamped to ``[0, 255]``. Parameters: - cmyk_value (tuple): A tuple representing the CMYK values (c, m, y, k) where - c (float) is cyan in the range [0, 1], - m (float) is magenta in the range [0, 1], - y (float) is yellow in the range [0, 1], - k (float) is key/black in the range [0, 1]. + x (float): X component (``>= 0``). + y (float): Y component (``>= 0``). + z (float): Z component (``>= 0``). Returns: - str: A string representing the hex color code (e.g., "#FFFFFF"). - - Raises: - ValueError: If the CMYK values are out of range. + tuple[int, int, int]: RGB values in ``[0, 255]``. """ - c, m, y, k = cmyk_value - if not (0 <= c <= 1 and 0 <= m <= 1 and 0 <= y <= 1 and 0 <= k <= 1): - raise ValueError("CMYK values must be in range: c, m, y, k [0, 1]") + xf, yf, zf = _validate_xyz(x, y, z) - return rgb_to_hex(*cmyk_to_rgb(c, m, y, k)) + r_lin = 3.2404542 * xf - 1.5371385 * yf - 0.4985314 * zf + g_lin = -0.9692660 * xf + 1.8760108 * yf + 0.0415560 * zf + b_lin = 0.0556434 * xf - 0.2040259 * yf + 1.0572252 * zf -def cmyk_to_hsv(cmyk_value: tuple) -> tuple: - """ - Converts CMYK (Cyan, Magenta, Yellow, Key/Black) to HSV (Hue, Saturation, Value). + r = round(_linear_to_srgb_channel(r_lin) * 255.0) + g = round(_linear_to_srgb_channel(g_lin) * 255.0) + b = round(_linear_to_srgb_channel(b_lin) * 255.0) - Parameters: - cmyk_value (tuple): A tuple representing the CMYK values (c, m, y, k) where - c (float) is cyan in the range [0, 1], - m (float) is magenta in the range [0, 1], - y (float) is yellow in the range [0, 1], - k (float) is key/black in the range [0, 1]. + return max(0, min(255, r)), max(0, min(255, g)), max(0, min(255, b)) - Returns: - tuple: A tuple representing the HSV values (h, s, v) where - h (float) is hue in the range [0, 360), - s (float) is saturation in the range [0, 1], - v (float) is value in the range [0, 1]. - Raises: - ValueError: If the CMYK values are out of range. - """ - c, m, y, k = cmyk_value - if not (0 <= c <= 1 and 0 <= m <= 1 and 0 <= y <= 1 and 0 <= k <= 1): - raise ValueError("CMYK values must be in range: c, m, y, k [0, 1]") +def hex_to_xyz(hex_value: str) -> tuple[float, float, float]: + """Convert a hex color code to CIE 1931 XYZ (D65).""" + return rgb_to_xyz(*hex_to_rgb(hex_value)) - return rgb_to_hsv(*cmyk_to_rgb(c, m, y, k)) -def cmyk_to_hsl(cmyk_value: tuple) -> tuple: - """ - Converts CMYK (Cyan, Magenta, Yellow, Key/Black) to HSL (Hue, Saturation, Lightness). +def xyz_to_hex(xyz_value: Sequence[float]) -> str: + """Convert a CIE 1931 XYZ tuple ``(x, y, z)`` to a hex color code.""" + x, y, z = _validate_xyz(*_validate_sequence(xyz_value, 3, "xyz_value")) + return rgb_to_hex(*xyz_to_rgb(x, y, z)) - Parameters: - cmyk_value (tuple): A tuple representing the CMYK values (c, m, y, k) where - c (float) is cyan in the range [0, 1], - m (float) is magenta in the range [0, 1], - y (float) is yellow in the range [0, 1], - k (float) is key/black in the range [0, 1]. - Returns: - tuple: A tuple representing the HSL values (h, s, l) where - h (float) is hue in the range [0, 360), - s (float) is saturation in the range [0, 1], - l (float) is lightness in the range [0, 1]. +def hsl_to_xyz(hsl_value: Sequence[float]) -> tuple[float, float, float]: + """Convert an HSL tuple ``(h, s, l)`` to CIE 1931 XYZ (D65).""" + h, s, l = _validate_hsl(*_validate_sequence(hsl_value, 3, "hsl_value")) + return rgb_to_xyz(*hsl_to_rgb(h, s, l)) - Raises: - ValueError: If the CMYK values are out of range. - """ - c, m, y, k = cmyk_value - if not (0 <= c <= 1 and 0 <= m <= 1 and 0 <= y <= 1 and 0 <= k <= 1): - raise ValueError("CMYK values must be in range: c, m, y, k [0, 1]") - return rgb_to_hsl(*cmyk_to_rgb(c, m, y, k)) +def xyz_to_hsl(xyz_value: Sequence[float]) -> tuple[float, float, float]: + """Convert a CIE 1931 XYZ tuple ``(x, y, z)`` to HSL.""" + x, y, z = _validate_xyz(*_validate_sequence(xyz_value, 3, "xyz_value")) + return rgb_to_hsl(*xyz_to_rgb(x, y, z)) -def rgb_to_xyz(r: int, g: int, b: int) -> tuple: - """ - Converts RGB (Red, Green, Blue) to CIE 1931 XYZ color space. - Parameters: - r (int): Red component, in the range [0, 255]. - g (int): Green component, in the range [0, 255]. - b (int): Blue component, in the range [0, 255]. +def hsv_to_xyz(hsv_value: Sequence[float]) -> tuple[float, float, float]: + """Convert an HSV tuple ``(h, s, v)`` to CIE 1931 XYZ (D65).""" + h, s, v = _validate_hsv(*_validate_sequence(hsv_value, 3, "hsv_value")) + return rgb_to_xyz(*hsv_to_rgb(h, s, v)) - Returns: - tuple: A tuple representing the XYZ values (x, y, z), where: - x, y, z (float): Correspond to the CIE 1931 color space. - Raises: - ValueError: If any RGB value is out of range. - """ - if not (0 <= r <= 255 and 0 <= g <= 255 and 0 <= b <= 255): - raise ValueError("RGB values must be in the range [0, 255].") +def xyz_to_hsv(xyz_value: Sequence[float]) -> tuple[float, float, float]: + """Convert a CIE 1931 XYZ tuple ``(x, y, z)`` to HSV.""" + x, y, z = _validate_xyz(*_validate_sequence(xyz_value, 3, "xyz_value")) + return rgb_to_hsv(*xyz_to_rgb(x, y, z)) - r_linear, g_linear, b_linear = [ - (c / 255) ** 2.2 if c > 0.04045 else c / 255 / 12.92 for c in (r, g, b) - ] - x = 0.412453 * r_linear + 0.357580 * g_linear + 0.180423 * b_linear - y = 0.212671 * r_linear + 0.715160 * g_linear + 0.072169 * b_linear - z = 0.019334 * r_linear + 0.119193 * g_linear + 0.950227 * b_linear +def xyz_to_cmyk(xyz_value: Sequence[float]) -> tuple[float, float, float, float]: + """Convert a CIE 1931 XYZ tuple ``(x, y, z)`` to CMYK.""" + x, y, z = _validate_xyz(*_validate_sequence(xyz_value, 3, "xyz_value")) + return rgb_to_cmyk(*xyz_to_rgb(x, y, z)) - return x, y, z +def cmyk_to_xyz(cmyk_value: Sequence[float]) -> tuple[float, float, float]: + """Convert a CMYK tuple ``(c, m, y, k)`` to CIE 1931 XYZ (D65).""" + c, m, y, k = _validate_cmyk(*_validate_sequence(cmyk_value, 4, "cmyk_value")) + return rgb_to_xyz(*cmyk_to_rgb(c, m, y, k)) -def xyz_to_rgb(x: float, y: float, z: float) -> tuple: - """ - Converts CIE 1931 XYZ to RGB (Red, Green, Blue) color space. + +def xyz_to_lab(xyz_value: Sequence[float]) -> tuple[float, float, float]: + """Convert a CIE 1931 XYZ (D65) tuple ``(x, y, z)`` to CIE 1976 L*a*b*. Parameters: - x (float): X component of the XYZ color space. - y (float): Y component of the XYZ color space. - z (float): Z component of the XYZ color space. + xyz_value (tuple): ``(x, y, z)`` coordinates under illuminant D65. Returns: - tuple: A tuple representing the RGB values (r, g, b), where: - r, g, b (int): Red, Green, and Blue components, each in the range [0, 255]. - - Raises: - ValueError: If any resulting RGB values are outside the valid range after conversion. + tuple[float, float, float]: ``(L*, a*, b*)`` where ``L*`` is in + ``[0, 100]`` and ``a*``, ``b*`` represent green-red and blue-yellow axes. """ - r_linear = 3.240479 * x - 1.537150 * y - 0.498535 * z - g_linear = -0.969256 * x + 1.875992 * y + 0.041556 * z - b_linear = 0.055648 * x - 0.204043 * y + 1.057311 * z + x, y, z = _validate_xyz(*_validate_sequence(xyz_value, 3, "xyz_value")) - r = r_linear ** (1 / 2.2) - g = g_linear ** (1 / 2.2) - b = b_linear ** (1 / 2.2) + def _f(t: float) -> float: + if t > _LAB_EPSILON: + return t ** (1.0 / 3.0) + return (_LAB_KAPPA * t + 16.0) / 116.0 - r = max(0, min(r, 1)) * 255 - g = max(0, min(g, 1)) * 255 - b = max(0, min(b, 1)) * 255 + fx = _f(x / _D65_X) + fy = _f(y / _D65_Y) + fz = _f(z / _D65_Z) - return round(r), round(g), round(b) + l_star = max(0.0, 116.0 * fy - 16.0) + if 100.0 < l_star <= 100.0001: + l_star = 100.0 + a_star = 500.0 * (fx - fy) + b_star = 200.0 * (fy - fz) + return l_star, a_star, b_star -def hex_to_xyz(hex_value: str) -> tuple: - """ - Converts a hexadecimal color code to CIE 1931 XYZ color space. +def lab_to_xyz(lab_value: Sequence[float]) -> tuple[float, float, float]: + """Convert a CIE 1976 L*a*b* tuple ``(L*, a*, b*)`` to CIE 1931 XYZ (D65). Parameters: - hex_value (str): A hexadecimal color code (e.g., '#RRGGBB'). + lab_value (tuple): ``(L*, a*, b*)`` coordinates with ``L*`` in ``[0, 100]``. Returns: - tuple: A tuple representing the XYZ values (x, y, z). + tuple[float, float, float]: ``(x, y, z)`` under illuminant D65. """ - r, g, b = hex_to_rgb(hex_value) - return rgb_to_xyz(r, g, b) + l_star, a_star, b_star = _validate_lab(*_validate_sequence(lab_value, 3, "lab_value")) + fy = (l_star + 16.0) / 116.0 + fx = a_star / 500.0 + fy + fz = fy - b_star / 200.0 -def xyz_to_hex(xyz_value: tuple) -> str: - """ - Converts CIE 1931 XYZ to a hexadecimal color code. + xr = fx**3 if fx > _LAB_DELTA else (116.0 * fx - 16.0) / _LAB_KAPPA + yr = ((l_star + 16.0) / 116.0) ** 3 if l_star > _LAB_KAPPA * _LAB_EPSILON else l_star / _LAB_KAPPA + zr = fz**3 if fz > _LAB_DELTA else (116.0 * fz - 16.0) / _LAB_KAPPA + + return max(0.0, xr * _D65_X), max(0.0, yr * _D65_Y), max(0.0, zr * _D65_Z) + + +def rgb_to_lab(r: int, g: int, b: int) -> tuple[float, float, float]: + """Convert sRGB ``(r, g, b)`` to CIE 1976 L*a*b* (D65). Parameters: - xyz_value (tuple): A tuple of XYZ values (x, y, z). + r (int): Red component in ``[0, 255]``. + g (int): Green component in ``[0, 255]``. + b (int): Blue component in ``[0, 255]``. Returns: - str: A hexadecimal color code (e.g., '#RRGGBB'). + tuple[float, float, float]: ``(L*, a*, b*)`` coordinates. """ - r, g, b = xyz_to_rgb(*xyz_value) - return rgb_to_hex(r, g, b) + return xyz_to_lab(rgb_to_xyz(r, g, b)) -def hsl_to_xyz(hsl_value: tuple) -> tuple: - """ - Converts HSL (Hue, Saturation, Lightness) to CIE 1931 XYZ color space. +def lab_to_rgb(l: float, a: float, b: float) -> tuple[int, int, int]: + """Convert CIE 1976 L*a*b* (D65) to sRGB ``(r, g, b)``. + + Out-of-sRGB-gamut values are safely clamped to ``[0, 255]``. Parameters: - hsl_value (tuple): A tuple representing the HSL values (h, s, l). + l (float): Lightness ``L*`` in ``[0, 100]``. + a (float): Green-red opponent component ``a*``. + b (float): Blue-yellow opponent component ``b*``. Returns: - tuple: A tuple representing the XYZ values (x, y, z). + tuple[int, int, int]: RGB values in ``[0, 255]``. """ - r, g, b = hsl_to_rgb(*hsl_value) - return rgb_to_xyz(r, g, b) + return xyz_to_rgb(*lab_to_xyz((l, a, b))) -def xyz_to_hsl(xyz_value: tuple) -> tuple: - """ - Converts CIE 1931 XYZ to HSL (Hue, Saturation, Lightness). +def hex_to_lab(hex_value: str) -> tuple[float, float, float]: + """Convert a hex color code to CIE 1976 L*a*b* (D65).""" + return rgb_to_lab(*hex_to_rgb(hex_value)) - Parameters: - xyz_value (tuple): A tuple of XYZ values (x, y, z). - Returns: - tuple: A tuple representing the HSL values (h, s, l). - """ - r, g, b = xyz_to_rgb(*xyz_value) - return rgb_to_hsl(r, g, b) +def lab_to_hex(lab_value: Sequence[float]) -> str: + """Convert a CIE 1976 L*a*b* tuple ``(L*, a*, b*)`` to a hex color code.""" + l_star, a_star, b_star = _validate_lab(*_validate_sequence(lab_value, 3, "lab_value")) + return rgb_to_hex(*lab_to_rgb(l_star, a_star, b_star)) -def hsv_to_xyz(hsv_value: tuple) -> tuple: - """ - Converts HSV (Hue, Saturation, Value) to CIE 1931 XYZ color space. +def hsl_to_lab(hsl_value: Sequence[float]) -> tuple[float, float, float]: + """Convert an HSL tuple ``(h, s, l)`` to CIE 1976 L*a*b* (D65).""" + h, s, l = _validate_hsl(*_validate_sequence(hsl_value, 3, "hsl_value")) + return rgb_to_lab(*hsl_to_rgb(h, s, l)) + + +def lab_to_hsl(lab_value: Sequence[float]) -> tuple[float, float, float]: + """Convert a CIE 1976 L*a*b* tuple ``(L*, a*, b*)`` to HSL.""" + l_star, a_star, b_star = _validate_lab(*_validate_sequence(lab_value, 3, "lab_value")) + return rgb_to_hsl(*lab_to_rgb(l_star, a_star, b_star)) + + +def hsv_to_lab(hsv_value: Sequence[float]) -> tuple[float, float, float]: + """Convert an HSV tuple ``(h, s, v)`` to CIE 1976 L*a*b* (D65).""" + h, s, v = _validate_hsv(*_validate_sequence(hsv_value, 3, "hsv_value")) + return rgb_to_lab(*hsv_to_rgb(h, s, v)) + + +def lab_to_hsv(lab_value: Sequence[float]) -> tuple[float, float, float]: + """Convert a CIE 1976 L*a*b* tuple ``(L*, a*, b*)`` to HSV.""" + l_star, a_star, b_star = _validate_lab(*_validate_sequence(lab_value, 3, "lab_value")) + return rgb_to_hsv(*lab_to_rgb(l_star, a_star, b_star)) + + +def cmyk_to_lab(cmyk_value: Sequence[float]) -> tuple[float, float, float]: + """Convert a CMYK tuple ``(c, m, y, k)`` to CIE 1976 L*a*b* (D65).""" + c, m, y, k = _validate_cmyk(*_validate_sequence(cmyk_value, 4, "cmyk_value")) + return rgb_to_lab(*cmyk_to_rgb(c, m, y, k)) + + +def lab_to_cmyk(lab_value: Sequence[float]) -> tuple[float, float, float, float]: + """Convert a CIE 1976 L*a*b* tuple ``(L*, a*, b*)`` to CMYK.""" + l_star, a_star, b_star = _validate_lab(*_validate_sequence(lab_value, 3, "lab_value")) + return rgb_to_cmyk(*lab_to_rgb(l_star, a_star, b_star)) + + +def linear_to_rgb(linear_rgb: Sequence[float]) -> tuple[int, int, int]: + """Convert linear sRGB components in ``[0, 1]`` to 8-bit sRGB ``(r, g, b)``. + + Applies the IEC 61966-2-1 sRGB companding function (the exact inverse of + :func:`hued.analysis.rgb_to_linear`). Parameters: - hsv_value (tuple): A tuple representing the HSV values (h, s, v). + linear_rgb (Sequence[float]): Three linear components in ``[0, 1]``. Returns: - tuple: A tuple representing the XYZ values (x, y, z). - """ - r, g, b = hsv_to_rgb(*hsv_value) - return rgb_to_xyz(r, g, b) + tuple[int, int, int]: sRGB values in ``[0, 255]``. + """ + r, g, b = _validate_sequence(linear_rgb, 3, "linear_rgb") + rf = _validate_real(r, "linear_rgb[0]") + gf = _validate_real(g, "linear_rgb[1]") + bf = _validate_real(b, "linear_rgb[2]") + if not (0.0 <= rf <= 1.0 and 0.0 <= gf <= 1.0 and 0.0 <= bf <= 1.0): + raise ValueError("Linear RGB values must be in the range [0, 1].") + return ( + max(0, min(255, round(_linear_to_srgb_channel(rf) * 255.0))), + max(0, min(255, round(_linear_to_srgb_channel(gf) * 255.0))), + max(0, min(255, round(_linear_to_srgb_channel(bf) * 255.0))), + ) + + +def blend_colors( + color1: Sequence[int], + color2: Sequence[int], + ratio: float = 0.5, + *, + linear: bool = False, +) -> tuple[int, int, int]: + """Blend two RGB colors according to ``ratio``. + Parameters: + color1 (tuple): First RGB color ``(r, g, b)`` in ``[0, 255]``. + color2 (tuple): Second RGB color ``(r, g, b)`` in ``[0, 255]``. + ratio (float): Interpolation factor in ``[0, 1]`` (``0.0`` returns + ``color1``, ``1.0`` returns ``color2``, ``0.5`` is an equal mix). + linear (bool): If ``True``, perform physically accurate blending in + linear sRGB light space instead of gamma-encoded sRGB. -def xyz_to_hsv(xyz_value: tuple) -> tuple: - """ - Converts CIE 1931 XYZ to HSV (Hue, Saturation, Value). + Returns: + tuple[int, int, int]: Blended RGB color in ``[0, 255]``. + + Raises: + TypeError: If colors or ``ratio`` have invalid types. + ValueError: If RGB components are outside ``[0, 255]`` or ``ratio`` is outside ``[0, 1]``. + """ + r1, g1, b1 = _validate_rgb_number_tuple(color1, "color1") + r2, g2, b2 = _validate_rgb_number_tuple(color2, "color2") + t = _validate_real(ratio, "ratio") + if not 0.0 <= t <= 1.0: + raise ValueError(f"ratio must be in the range [0, 1], got {ratio}.") + if not isinstance(linear, bool): + raise TypeError(f"linear must be a bool, got {type(linear).__name__}.") + + inv = 1.0 - t + if linear: + rl = _srgb_to_linear_channel(r1) * inv + _srgb_to_linear_channel(r2) * t + gl = _srgb_to_linear_channel(g1) * inv + _srgb_to_linear_channel(g2) * t + bl = _srgb_to_linear_channel(b1) * inv + _srgb_to_linear_channel(b2) * t + return ( + max(0, min(255, round(_linear_to_srgb_channel(rl) * 255.0))), + max(0, min(255, round(_linear_to_srgb_channel(gl) * 255.0))), + max(0, min(255, round(_linear_to_srgb_channel(bl) * 255.0))), + ) + + return ( + max(0, min(255, round(r1 * inv + r2 * t))), + max(0, min(255, round(g1 * inv + g2 * t))), + max(0, min(255, round(b1 * inv + b2 * t))), + ) + + +def invert_color(rgb: Sequence[int]) -> tuple[int, int, int]: + """Return the inverted sRGB color ``(255 - r, 255 - g, 255 - b)``. Parameters: - xyz_value (tuple): A tuple of XYZ values (x, y, z). + rgb (tuple): Input RGB color ``(r, g, b)`` in ``[0, 255]``. Returns: - tuple: A tuple representing the HSV values (h, s, v). + tuple[int, int, int]: Inverted RGB color. """ - r, g, b = xyz_to_rgb(*xyz_value) - return rgb_to_hsv(r, g, b) + r, g, b = _validate_rgb_tuple(rgb) + return 255 - r, 255 - g, 255 - b -def xyz_to_cmyk(xyz_value: tuple) -> tuple: - """ - Converts CIE 1931 XYZ to CMYK (Cyan, Magenta, Yellow, Key/Black). +def to_grayscale(rgb: Sequence[int]) -> tuple[int, int, int]: + """Convert an RGB color to a perceptual grayscale RGB tuple. + + Computes relative luminance in linear sRGB and re-encodes using the sRGB + transfer function so perceived brightness is faithfully preserved. Parameters: - xyz_value (tuple): A tuple of XYZ values (x, y, z). + rgb (tuple): Input RGB color ``(r, g, b)`` in ``[0, 255]``. Returns: - tuple: A tuple representing the CMYK values (c, m, y, k). + tuple[int, int, int]: Grayscale ``(v, v, v)`` tuple in ``[0, 255]``. """ - r, g, b = xyz_to_rgb(*xyz_value) - return rgb_to_cmyk(r, g, b) + r, g, b = _validate_rgb_number_tuple(rgb) + y_lin = ( + 0.2126 * _srgb_to_linear_channel(r) + + 0.7152 * _srgb_to_linear_channel(g) + + 0.0722 * _srgb_to_linear_channel(b) + ) + gray = max(0, min(255, round(_linear_to_srgb_channel(y_lin) * 255.0))) + return gray, gray, gray -def cmyk_to_xyz(cmyk_value: tuple) -> tuple: - """ - Converts CMYK (Cyan, Magenta, Yellow, Key/Black) to CIE 1931 XYZ color space. +def adjust_lightness(rgb: Sequence[int], amount: float) -> tuple[int, int, int]: + """Lighten or darken an RGB color by adjusting its HSL lightness. Parameters: - cmyk_value (tuple): A tuple of CMYK values (c, m, y, k). + rgb (tuple): Input RGB color ``(r, g, b)`` in ``[0, 255]``. + amount (float): Signed delta in ``[-1, 1]`` added to HSL lightness + (positive lightens, negative darkens; result clamped to ``[0, 1]``). Returns: - tuple: A tuple representing the XYZ values (x, y, z). + tuple[int, int, int]: Adjusted RGB color in ``[0, 255]``. """ - r, g, b = cmyk_to_rgb(*cmyk_value) - return rgb_to_xyz(r, g, b) + r, g, b = _validate_rgb_number_tuple(rgb) + delta = _validate_real(amount, "amount") + if not -1.0 <= delta <= 1.0: + raise ValueError(f"amount must be in the range [-1, 1], got {amount}.") + h, s, l = _rgb_to_hsl_exact(r, g, b) + new_l = max(0.0, min(1.0, l + delta)) + return hsl_to_rgb(h, s, new_l) -def blend_colors(color1, color2, ratio=0.5): - """ - Blends two colors in the RGB format using the specified ratio. - This function takes two RGB colors and blends them based on the provided ratio. - A ratio of 0.5 will give an equal mix of both colors, while other ratios will - give more weight to one color over the other. +def adjust_saturation(rgb: Sequence[int], amount: float) -> tuple[int, int, int]: + """Increase or decrease an RGB color's HSL saturation. Parameters: - color1 (tuple): The first RGB color as a tuple of three integers (R, G, B). - color2 (tuple): The second RGB color as a tuple of three integers (R, G, B). - ratio (float, optional): The ratio to blend the colors. A value of 0.5 will - blend both colors equally. Values closer to 0 will - give more weight to `color1`, and values closer to - 1 will favor `color2`. Default is 0.5. + rgb (tuple): Input RGB color ``(r, g, b)`` in ``[0, 255]``. + amount (float): Signed delta in ``[-1, 1]`` added to HSL saturation + (positive saturates, negative desaturates; result clamped to ``[0, 1]``). Returns: - tuple: The blended color as an RGB tuple of three integers. - - Example: - >>> blend_colors((255, 0, 0), (0, 0, 255), 0.5) - (127, 0, 127) - """ - r = int(color1[0] * (1 - ratio) + color2[0] * ratio) - g = int(color1[1] * (1 - ratio) + color2[1] * ratio) - b = int(color1[2] * (1 - ratio) + color2[2] * ratio) - - return (r, g, b) \ No newline at end of file + tuple[int, int, int]: Adjusted RGB color in ``[0, 255]``. + """ + r, g, b = _validate_rgb_number_tuple(rgb) + delta = _validate_real(amount, "amount") + if not -1.0 <= delta <= 1.0: + raise ValueError(f"amount must be in the range [-1, 1], got {amount}.") + h, s, l = _rgb_to_hsl_exact(r, g, b) + new_s = max(0.0, min(1.0, s + delta)) + return hsl_to_rgb(h, new_s, l) diff --git a/hued/palettes.py b/hued/palettes.py index 352857b..e7fcb2b 100644 --- a/hued/palettes.py +++ b/hued/palettes.py @@ -1,416 +1,517 @@ -import random -import json +"""Color palette harmony generation, gradients, random sampling, and file export.""" + +from __future__ import annotations + import csv -from hued.conversions import rgb_to_hsl, hsl_to_rgb, rgb_to_hex +import json +import os +import random +import re +from collections.abc import Sequence +from typing import Any + +from hued.conversions import ( + _linear_to_srgb_channel, + _rgb_to_hsl_exact, + _srgb_to_linear_channel, + _validate_real, + _validate_rgb_tuple, + _wrap_hue, + hsl_to_rgb, + lab_to_rgb, + rgb_to_hex, + rgb_to_hsl, + rgb_to_lab, +) + +__all__ = ["ColorPalette"] + +_SUPPORTED_EXPORT_EXTENSIONS = {".json", ".txt", ".csv", ".css"} +_CSS_SLUG_RE = re.compile(r"[^a-z0-9]+") + + +def _is_rgb_color(value: Any) -> bool: + """Return True if ``value`` is a valid 3-channel integer RGB tuple.""" + return ( + isinstance(value, tuple) + and len(value) == 3 + and all(isinstance(c, int) and not isinstance(c, bool) and 0 <= c <= 255 for c in value) + ) + + +def _css_slug(label: str) -> str: + return _CSS_SLUG_RE.sub("-", label.strip().lower()).strip("-") or "color" + class ColorPalette: - """ - A class to create and manipulate color palettes. + """Create, manipulate, and export harmonious color palettes. Attributes: - base_color (tuple): The RGB tuple of the base color. - palette (list): A list of RGB tuples representing the color palette. + base_color (tuple[int, int, int]): Base RGB color ``(r, g, b)`` in ``[0, 255]``. + palette (list | dict): Current palette — a list of RGB tuples for single + harmony schemes, or a dictionary of schemes after + :meth:`generate_random_palette`. """ - def __init__(self, base_color): - """ - Initializes the ColorPalette with a base color. + def __init__(self, base_color: Sequence[int]) -> None: + """Initialize the palette with an RGB base color in ``[0, 255]``.""" + validated = _validate_rgb_tuple(base_color, "base_color") + self.base_color: tuple[int, int, int] = validated + self.palette: list[tuple[int, int, int]] | dict[str, Any] = [validated] - Parameters: - base_color (tuple): The RGB tuple of the base color (0-255). - """ - self.base_color = base_color - self.palette = [base_color] - - def generate_complementary(self): - """ - Generates a complementary color palette. - - Returns: - list: A list of RGB tuples representing the complementary palette. - """ + def generate_complementary(self) -> list[tuple[int, int, int]]: + """Generate a 2-color complementary palette (``0°``, ``+180°``).""" h, s, l = rgb_to_hsl(*self.base_color) - complementary_h = (h + 180) % 360 - complementary_color = hsl_to_rgb(complementary_h, s, l) + complementary_color = hsl_to_rgb(_wrap_hue(h + 180.0), s, l) self.palette = [self.base_color, complementary_color] return self.palette - def generate_analogous(self, angle=30): - """ - Generates an analogous color palette. + def generate_analogous(self, angle: float = 30) -> list[tuple[int, int, int]]: + """Generate a 3-color analogous palette (``-angle``, ``0°``, ``+angle``). Parameters: - angle (int): The angle difference for analogous colors (default 30). - - Returns: - list: A list of RGB tuples representing the analogous palette. + angle (float): Hue separation in degrees (default ``30``). """ + step = _validate_real(angle, "angle") + if not 0.0 < step < 180.0: + raise ValueError(f"angle must be in (0, 180), got {angle}.") h, s, l = rgb_to_hsl(*self.base_color) - analogous1_h = (h + angle) % 360 - analogous2_h = (h - angle) % 360 - analogous1 = hsl_to_rgb(analogous1_h, s, l) - analogous2 = hsl_to_rgb(analogous2_h, s, l) + analogous1 = hsl_to_rgb(_wrap_hue(h + step), s, l) + analogous2 = hsl_to_rgb(_wrap_hue(h - step), s, l) self.palette = [analogous2, self.base_color, analogous1] return self.palette - def generate_triadic(self): - """ - Generates a triadic color palette. - - Returns: - list: A list of RGB tuples representing the triadic palette. - """ + def generate_triadic(self) -> list[tuple[int, int, int]]: + """Generate a 3-color triadic palette (``0°``, ``+120°``, ``+240°``).""" h, s, l = rgb_to_hsl(*self.base_color) - triadic1_h = (h + 120) % 360 - triadic2_h = (h - 120) % 360 - triadic1 = hsl_to_rgb(triadic1_h, s, l) - triadic2 = hsl_to_rgb(triadic2_h, s, l) + triadic1 = hsl_to_rgb(_wrap_hue(h + 120.0), s, l) + triadic2 = hsl_to_rgb(_wrap_hue(h - 120.0), s, l) self.palette = [self.base_color, triadic1, triadic2] return self.palette - def generate_monochromatic(self, shades=24): - """ - Generates a monochromatic color palette with varying lightness. + def generate_monochromatic(self, shades: int = 24) -> list[tuple[int, int, int]]: + """Generate a monochromatic palette of varying lightness levels. Parameters: - shades (int): Number of shades to generate (default 24). - - Returns: - list: A list of RGB tuples representing the monochromatic palette. + shades (int): Number of lightness steps to sample (must be ``>= 1``, + default ``24``). Clamped duplicate lightness values are omitted. """ - h, s, l = rgb_to_hsl(*self.base_color) + if isinstance(shades, bool) or not isinstance(shades, int): + raise TypeError(f"shades must be an integer, got {type(shades).__name__}.") + if shades < 1: + raise ValueError(f"shades must be at least 1, got {shades}.") + + if shades == 1: + self.palette = [self.base_color] + return self.palette - # Generate unique lightness values - lightness_values = [] + h, s, l = rgb_to_hsl(*self.base_color) + lightness_values: list[float] = [] for i in range(shades): - new_lightness = max(min(l + (i / (shades - 1)) - 0.5, 1), 0) - if new_lightness not in lightness_values: # Avoid duplicates + new_lightness = max(min(l + (i / (shades - 1)) - 0.5, 1.0), 0.0) + if new_lightness not in lightness_values: lightness_values.append(new_lightness) self.palette = [hsl_to_rgb(h, s, lightness) for lightness in lightness_values] return self.palette - def generate_tetradic(self): - """ - Generates a tetradic color palette. + def generate_tetradic(self, angle: float = 60) -> list[tuple[int, int, int]]: + """Generate a 4-color rectangular tetradic (double-complementary) palette. - Returns: - list: A list of RGB tuples representing the tetradic palette. + Produces colors at hue offsets ``0°``, ``+angle``, ``+180°``, and + ``+(180° + angle)``. With default ``angle=60`` this forms a classic + rectangular tetrad distinct from :meth:`generate_square` (``angle=90``). + + Parameters: + angle (float): Separation between paired hues in ``(0, 180)`` + (default ``60``). """ - h, s, l = rgb_to_hsl(*self.base_color) - tetradic1_h = (h + 90) % 360 - tetradic2_h = (h + 180) % 360 - tetradic3_h = (h + 270) % 360 + step = _validate_real(angle, "angle") + if not 0.0 < step < 180.0: + raise ValueError(f"angle must be in (0, 180), got {angle}.") - tetradic1 = hsl_to_rgb(tetradic1_h, s, l) - tetradic2 = hsl_to_rgb(tetradic2_h, s, l) - tetradic3 = hsl_to_rgb(tetradic3_h, s, l) + h, s, l = rgb_to_hsl(*self.base_color) + tetradic1 = hsl_to_rgb(_wrap_hue(h + step), s, l) + tetradic2 = hsl_to_rgb(_wrap_hue(h + 180.0), s, l) + tetradic3 = hsl_to_rgb(_wrap_hue(h + 180.0 + step), s, l) self.palette = [self.base_color, tetradic1, tetradic2, tetradic3] return self.palette - def generate_square(self): - """ - Generates a square color palette. - - Returns: - list: A list of RGB tuples representing the square palette. - """ + def generate_square(self) -> list[tuple[int, int, int]]: + """Generate a 4-color square palette (``0°``, ``+90°``, ``+180°``, ``+270°``).""" h, s, l = rgb_to_hsl(*self.base_color) - square1_h = (h + 90) % 360 - square2_h = (h + 180) % 360 - square3_h = (h + 270) % 360 - - square1 = hsl_to_rgb(square1_h, s, l) - square2 = hsl_to_rgb(square2_h, s, l) - square3 = hsl_to_rgb(square3_h, s, l) + square1 = hsl_to_rgb(_wrap_hue(h + 90.0), s, l) + square2 = hsl_to_rgb(_wrap_hue(h + 180.0), s, l) + square3 = hsl_to_rgb(_wrap_hue(h + 270.0), s, l) self.palette = [self.base_color, square1, square2, square3] return self.palette - def generate_split_complementary(self): - """ - Generates a split-complementary color palette. + def generate_split_complementary(self, angle: float = 30) -> list[tuple[int, int, int]]: + """Generate a 3-color split-complementary palette. - Returns: - list: A list of RGB tuples representing the split-complementary palette. + Parameters: + angle (float): Offset in degrees on each side of the complement + (default ``30``, giving ``+150°`` and ``+210°``). """ - h, s, l = rgb_to_hsl(*self.base_color) - split_comp1_h = (h + 150) % 360 - split_comp2_h = (h + 210) % 360 + step = _validate_real(angle, "angle") + if not 0.0 < step < 180.0: + raise ValueError(f"angle must be in (0, 180), got {angle}.") - split_comp1 = hsl_to_rgb(split_comp1_h, s, l) - split_comp2 = hsl_to_rgb(split_comp2_h, s, l) + h, s, l = rgb_to_hsl(*self.base_color) + split_comp1 = hsl_to_rgb(_wrap_hue(h + 180.0 - step), s, l) + split_comp2 = hsl_to_rgb(_wrap_hue(h + 180.0 + step), s, l) self.palette = [self.base_color, split_comp1, split_comp2] return self.palette - def palette_to_hex(self): - """ - Converts the RGB palette to HEX format. - - Returns: - list: A list of HEX strings representing the palette. - """ - return [rgb_to_hex(*color).upper() for color in self.palette] + def palette_to_hex(self) -> list[str] | dict[str, Any]: + """Convert the current palette to uppercase ``#RRGGBB`` hex strings. + + Returns a ``list[str]`` when ``self.palette`` is a list of RGB tuples, + or a ``dict`` mirroring the keys of ``self.palette`` when it was + populated by :meth:`generate_random_palette`. + """ + if isinstance(self.palette, list): + return [rgb_to_hex(*_validate_rgb_tuple(color, "color")) for color in self.palette] + if isinstance(self.palette, dict): + converted: dict[str, Any] = {} + for key, value in self.palette.items(): + if _is_rgb_color(value): + converted[key] = rgb_to_hex(*value) + elif isinstance(value, list): + converted[key] = [ + rgb_to_hex(*_validate_rgb_tuple(color, "color")) for color in value + ] + else: + converted[key] = value + return converted + raise TypeError( + f"Unsupported palette type: {type(self.palette).__name__}. Must be list or dict." + ) - def add_color(self, rgb_color): - """ - Adds a color to the palette. + def add_color(self, rgb_color: Sequence[int]) -> None: + """Append a validated RGB color to a list-based palette. - Parameters: - rgb_color (tuple): An RGB tuple (0-255). + Raises: + TypeError: If ``rgb_color`` is invalid or ``self.palette`` is currently a dict. + ValueError: If RGB channel values are outside ``[0, 255]``. """ - self.palette.append(rgb_color) + validated = _validate_rgb_tuple(rgb_color, "rgb_color") + if not isinstance(self.palette, list): + raise TypeError( + "Cannot add a color when palette is a dictionary. " + "Generate a list-based palette first or use set_as_current=False." + ) + self.palette.append(validated) - def remove_color(self, rgb_color): - """ - Removes a color from the palette if it exists. + def remove_color(self, rgb_color: Sequence[int]) -> None: + """Remove a validated RGB color from a list-based palette if present. - Parameters: - rgb_color (tuple): An RGB tuple (0-255). + Raises: + TypeError: If ``rgb_color`` is invalid or ``self.palette`` is currently a dict. + ValueError: If RGB channel values are outside ``[0, 255]``. """ - if rgb_color in self.palette: - self.palette.remove(rgb_color) + validated = _validate_rgb_tuple(rgb_color, "rgb_color") + if not isinstance(self.palette, list): + raise TypeError( + "Cannot remove a color when palette is a dictionary. " + "Generate a list-based palette first or use set_as_current=False." + ) + if validated in self.palette: + self.palette.remove(validated) - def generate_random_palette(self, set_as_current=True): - """ - Generates a random base color and its associated palettes as a dictionary. + def generate_random_palette(self, set_as_current: bool = True) -> dict[str, Any]: + """Generate a random base color and all harmony palettes as a dictionary. Parameters: - set_as_current (bool): If True, sets self.palette to the generated dictionary. - If False, returns the dictionary without modifying self.palette. - - Returns: - dict: A dictionary containing the base color and various generated palettes (as lists of RGB tuples). - Example keys: 'Base Color', 'Complementary Palette', 'Analogous Palette', etc. + set_as_current (bool): If ``True`` (default), update ``self.base_color`` + and set ``self.palette`` to the returned dictionary. If ``False``, + leave instance state unchanged. """ - # Generate a random RGB color + if not isinstance(set_as_current, bool): + raise TypeError( + f"set_as_current must be a bool, got {type(set_as_current).__name__}." + ) + random_base_color = ( random.randint(0, 255), random.randint(0, 255), random.randint(0, 255), ) - # Store current state original_base = self.base_color original_palette = self.palette - - # Temporarily set base color for generation self.base_color = random_base_color - # Generate the palettes using the instance methods - # These methods currently modify self.palette, so we capture their return value - palette_dict = { - "Base Color": random_base_color, # Store the base color itself - "Complementary Palette": self.generate_complementary(), - "Analogous Palette": self.generate_analogous(), - "Triadic Palette": self.generate_triadic(), - "Monochromatic Palette": self.generate_monochromatic(), - "Tetradic Palette": self.generate_tetradic(), - "Square Palette": self.generate_square(), # Often same as tetradic here - "Split Complementary Palette": self.generate_split_complementary() - } + try: + palette_dict: dict[str, Any] = { + "Base Color": random_base_color, + "Complementary Palette": self.generate_complementary(), + "Analogous Palette": self.generate_analogous(), + "Triadic Palette": self.generate_triadic(), + "Monochromatic Palette": self.generate_monochromatic(), + "Tetradic Palette": self.generate_tetradic(), + "Square Palette": self.generate_square(), + "Split Complementary Palette": self.generate_split_complementary(), + } + except Exception: + self.base_color = original_base + self.palette = original_palette + raise - # Restore original state or set the new dict as the current palette if set_as_current: self.palette = palette_dict - # self.base_color remains the random_base_color in this case else: self.base_color = original_base self.palette = original_palette return palette_dict - def generate_random_color(self): - """ - Generates a random RGB color and converts it to both HEX and HSL formats. - - This method generates a random color in the RGB format by selecting random - values for red, green, and blue channels between 0 and 255. It then converts - the generated RGB values into both HEX and HSL formats. - - Returns: - dict: A dictionary containing: - - "RGB Color" (tuple): The random RGB color as a tuple of three integers. - - "HEX Color" (str): The color converted into HEX format. - - "HSL Color" (tuple): The color converted into HSL format. - """ - - # Generate a random RGB color + def generate_random_color(self) -> dict[str, Any]: + """Generate a random color returned in RGB, HEX, and HSL formats.""" base_color = ( random.randint(0, 255), random.randint(0, 255), random.randint(0, 255), ) - - hex_color = rgb_to_hex(base_color[0], base_color[1], base_color[2]) - hsl_color = rgb_to_hsl(base_color[0], base_color[1], base_color[2]) - return { "RGB Color": base_color, - "HEX Color": hex_color, - "HSL Color": hsl_color + "HEX Color": rgb_to_hex(*base_color), + "HSL Color": rgb_to_hsl(*base_color), } - def generate_random_hex_colors(self, n=10): - """ - Generates a list of random colors in HEX format. - - This method uses `generate_random_color` to generate multiple random colors - and extracts the HEX value of each color. By default, it generates 10 random - HEX colors. + def generate_random_hex_colors(self, n: int = 10) -> list[str]: + """Generate ``n`` random uppercase ``#RRGGBB`` color codes.""" + if isinstance(n, bool) or not isinstance(n, int): + raise TypeError(f"n must be an integer, got {type(n).__name__}.") + if n < 0: + raise ValueError(f"n must be non-negative, got {n}.") + return [self.generate_random_color()["HEX Color"] for _ in range(n)] + + def generate_gradient( + self, + color1: Sequence[int], + color2: Sequence[int], + steps: int = 10, + *, + space: str = "rgb", + ) -> list[tuple[int, int, int]]: + """Generate a smooth gradient between two RGB colors (``steps + 1`` stops). + + Does not modify ``self.palette``. Parameters: - n (int, optional): The number of random HEX colors to generate. Default is 10. + color1 (tuple): Starting RGB color ``(r, g, b)`` in ``[0, 255]``. + color2 (tuple): Ending RGB color ``(r, g, b)`` in ``[0, 255]``. + steps (int): Number of intervals (``>= 1``; returns ``steps + 1`` colors). + space (str): Interpolation color space — ``"rgb"`` (default), + ``"linear"`` (gamma-correct linear sRGB), ``"lab"`` (perceptually + uniform CIE L*a*b*), or ``"hsl"`` (shortest-arc hue). Returns: - list: A list of HEX color strings. - """ - - hex_colors = [] - for i in range(n): - hex_color = self.generate_random_color().get("HEX Color") - hex_colors.append(hex_color) - - return hex_colors - - def generate_gradient(self, color1, color2, steps=10): - """ - Generates a gradient between two RGB colors. - - Parameters: - color1 (tuple): The starting RGB color (0-255). - color2 (tuple): The ending RGB color (0-255). - steps (int): The number of intermediate steps in the gradient (total colors = steps + 1). - - Returns: - list: A list of RGB tuples representing the gradient. - Does NOT modify self.palette. + list[tuple[int, int, int]]: Gradient stops starting at ``color1`` and + ending at ``color2``. """ + c1 = _validate_rgb_tuple(color1, "color1") + c2 = _validate_rgb_tuple(color2, "color2") + if isinstance(steps, bool) or not isinstance(steps, int): + raise TypeError(f"steps must be an integer, got {type(steps).__name__}.") if steps < 1: - raise ValueError("Number of steps must be at least 1.") - gradient = [] + raise ValueError("Number of steps must be at least 1.") + if not isinstance(space, str): + raise TypeError(f"space must be a string, got {type(space).__name__}.") + + mode = space.strip().lower() + if mode not in {"rgb", "linear", "lab", "hsl"}: + raise ValueError( + f"Unknown gradient color space {space!r}. Use 'rgb', 'linear', 'lab', or 'hsl'." + ) + + gradient: list[tuple[int, int, int]] = [] + + if mode == "rgb": + for i in range(steps + 1): + ratio = i / steps + inv = 1.0 - ratio + r = max(0, min(255, round(c1[0] * inv + c2[0] * ratio))) + g = max(0, min(255, round(c1[1] * inv + c2[1] * ratio))) + b = max(0, min(255, round(c1[2] * inv + c2[2] * ratio))) + gradient.append((r, g, b)) + return gradient + + if mode == "linear": + lin1 = tuple(_srgb_to_linear_channel(ch) for ch in c1) + lin2 = tuple(_srgb_to_linear_channel(ch) for ch in c2) + for i in range(steps + 1): + ratio = i / steps + inv = 1.0 - ratio + rgb = ( + max(0, min(255, round(_linear_to_srgb_channel(lin1[0] * inv + lin2[0] * ratio) * 255.0))), + max(0, min(255, round(_linear_to_srgb_channel(lin1[1] * inv + lin2[1] * ratio) * 255.0))), + max(0, min(255, round(_linear_to_srgb_channel(lin1[2] * inv + lin2[2] * ratio) * 255.0))), + ) + gradient.append(rgb) + return gradient + + if mode == "lab": + lab1 = rgb_to_lab(*c1) + lab2 = rgb_to_lab(*c2) + for i in range(steps + 1): + if i == 0: + gradient.append(c1) + elif i == steps: + gradient.append(c2) + else: + ratio = i / steps + inv = 1.0 - ratio + l_val = lab1[0] * inv + lab2[0] * ratio + a_val = lab1[1] * inv + lab2[1] * ratio + b_val = lab1[2] * inv + lab2[2] * ratio + gradient.append(lab_to_rgb(l_val, a_val, b_val)) + return gradient + + # mode == "hsl" (shortest-arc hue interpolation; preserve hue for achromatic endpoints) + h1, s1, l1 = _rgb_to_hsl_exact(*c1) + h2, s2, l2 = _rgb_to_hsl_exact(*c2) + if s1 == 0.0 and s2 > 0.0: + h1 = h2 + elif s2 == 0.0 and s1 > 0.0: + h2 = h1 + dh = ((h2 - h1 + 540.0) % 360.0) - 180.0 + for i in range(steps + 1): - ratio = i / steps - r = int(color1[0] * (1 - ratio) + color2[0] * ratio) - g = int(color1[1] * (1 - ratio) + color2[1] * ratio) - b = int(color1[2] * (1 - ratio) + color2[2] * ratio) - # Clamp values just in case of floating point inaccuracies - r = max(0, min(255, r)) - g = max(0, min(255, g)) - b = max(0, min(255, b)) - gradient.append((r, g, b)) + if i == 0: + gradient.append(c1) + elif i == steps: + gradient.append(c2) + else: + ratio = i / steps + inv = 1.0 - ratio + h_val = _wrap_hue(h1 + dh * ratio) + s_val = max(0.0, min(1.0, s1 * inv + s2 * ratio)) + l_val = max(0.0, min(1.0, l1 * inv + l2 * ratio)) + gradient.append(hsl_to_rgb(h_val, s_val, l_val)) return gradient - def _format_color_output(self, color_tuple): - """Helper to consistently format color output.""" - hex_val = rgb_to_hex(*color_tuple).upper() - return {"rgb": color_tuple, "hex": hex_val} - - def export_palette(self, filename="palette.json"): - """ - Exports the current color palette (list or dict) to a file. - - Handles both list-based palettes and dictionary-based palettes - (like those from `generate_random_palette`). + def _format_color_output(self, color_tuple: Sequence[int]) -> dict[str, Any]: + """Format a validated RGB tuple for export.""" + rgb = _validate_rgb_tuple(color_tuple, "color") + return {"rgb": rgb, "hex": rgb_to_hex(*rgb)} - Supported formats: .json, .txt, .csv. + def export_palette(self, filename: str | os.PathLike[str] = "palette.json") -> None: + """Export the current palette (list or dictionary) to disk. - - JSON: Exports the full structure, converting RGB tuples to - {"rgb": (r,g,b), "hex": "#RRGGBB"} objects for clarity. - - TXT: Exports a human-readable text format, labeling each - palette type if the source is a dictionary. - - CSV: Exports a flattened structure. - For lists: Type, Index, Hex, R, G, B - For dicts: PaletteName, Index, Hex, R, G, B + Supported file extensions: ``.json``, ``.txt``, ``.csv``, and ``.css``. Parameters: - filename (str): The name of the file to save the palette. - The extension determines the format (.json, .txt, .csv). - Defaults to "palette.json". + filename (str | os.PathLike): Destination path whose extension selects + the output format (default ``"palette.json"``). Raises: - ValueError: If the filename has an unsupported extension or if - the palette is empty or in an unexpected format. - TypeError: If self.palette is not a list or dict. - """ + TypeError: If ``filename`` or ``self.palette`` has an unsupported type. + ValueError: If ``self.palette`` is empty or ``filename`` has an + unsupported/missing extension. + """ + if not isinstance(filename, (str, os.PathLike)): + raise TypeError( + f"filename must be a string or PathLike, got {type(filename).__name__}." + ) + if not isinstance(self.palette, (list, dict)): + raise TypeError( + f"Unsupported palette type: {type(self.palette).__name__}. Must be list or dict." + ) if not self.palette: raise ValueError("Palette is empty, cannot export.") - file_ext = filename.lower().split('.')[-1] - - try: - if isinstance(self.palette, list): - # --- Handle List Palette Export --- - if file_ext == "json": - export_data = [self._format_color_output(color) for color in self.palette] - with open(filename, "w", encoding='utf-8') as f: - json.dump(export_data, f, indent=4) - elif file_ext == "txt": - with open(filename, "w", encoding='utf-8') as f: - f.write("--- Simple Palette ---\n") - for i, color in enumerate(self.palette): - formatted = self._format_color_output(color) - f.write(f"{i}: {formatted['hex']} - RGB{formatted['rgb']}\n") - elif file_ext == "csv": - with open(filename, "w", newline='', encoding='utf-8') as f: - writer = csv.writer(f) - writer.writerow(["Type", "Index", "Hex", "R", "G", "B"]) - for i, color in enumerate(self.palette): - formatted = self._format_color_output(color) - writer.writerow(["Simple Palette", i, formatted['hex'], color[0], color[1], color[2]]) - else: - raise ValueError("Unsupported file format. Use .json, .txt, or .csv.") - - elif isinstance(self.palette, dict): - # --- Handle Dictionary Palette Export --- - if file_ext == "json": - export_data = {} - for key, value in self.palette.items(): - if isinstance(value, tuple) and len(value) == 3: # Single color - export_data[key] = self._format_color_output(value) - elif isinstance(value, list): # List of colors - export_data[key] = [self._format_color_output(color) for color in value] - else: - export_data[key] = value # Preserve other data types - with open(filename, "w", encoding='utf-8') as f: - json.dump(export_data, f, indent=4) - elif file_ext == "txt": - with open(filename, "w", encoding='utf-8') as f: - for key, value in self.palette.items(): - f.write(f"--- {key} ---\n") - if isinstance(value, tuple) and len(value) == 3: # Single color - formatted = self._format_color_output(value) - f.write(f"0: {formatted['hex']} - RGB{formatted['rgb']}\n") - elif isinstance(value, list): # List of colors - for i, color in enumerate(value): - formatted = self._format_color_output(color) - f.write(f"{i}: {formatted['hex']} - RGB{formatted['rgb']}\n") - else: - f.write(f"{value}\n") # Write other data as is - f.write("\n") # Add space between sections - elif file_ext == "csv": - with open(filename, "w", newline='', encoding='utf-8') as f: - writer = csv.writer(f) - writer.writerow(["PaletteName", "Index", "Hex", "R", "G", "B"]) - for key, value in self.palette.items(): - if isinstance(value, tuple) and len(value) == 3: # Single color - formatted = self._format_color_output(value) - writer.writerow([key, 0, formatted['hex'], value[0], value[1], value[2]]) - elif isinstance(value, list): # List of colors - for i, color in enumerate(value): - formatted = self._format_color_output(color) - writer.writerow([key, i, formatted['hex'], color[0], color[1], color[2]]) - # Ignoring non-color list/tuple values for CSV + path_str = os.fspath(filename) + file_ext = os.path.splitext(path_str)[1].lower() + if file_ext not in _SUPPORTED_EXPORT_EXTENSIONS: + raise ValueError("Unsupported file format. Use .json, .txt, .csv, or .css.") + + if isinstance(self.palette, list): + formatted_list = [self._format_color_output(color) for color in self.palette] + if file_ext == ".json": + export_list = [ + {"rgb": list(item["rgb"]), "hex": item["hex"]} for item in formatted_list + ] + with open(path_str, "w", encoding="utf-8") as f: + json.dump(export_list, f, indent=4) + elif file_ext == ".txt": + with open(path_str, "w", encoding="utf-8") as f: + f.write("--- Simple Palette ---\n") + for i, item in enumerate(formatted_list): + f.write(f"{i}: {item['hex']} - RGB{item['rgb']}\n") + elif file_ext == ".csv": + with open(path_str, "w", newline="", encoding="utf-8") as f: + writer = csv.writer(f) + writer.writerow(["Type", "Index", "Hex", "R", "G", "B"]) + for i, item in enumerate(formatted_list): + r, g, b = item["rgb"] + writer.writerow(["Simple Palette", i, item["hex"], r, g, b]) + elif file_ext == ".css": + with open(path_str, "w", encoding="utf-8") as f: + f.write(":root {\n") + for i, item in enumerate(formatted_list): + f.write(f" --palette-color-{i}: {item['hex']};\n") + f.write("}\n") + return + + # Dictionary palette export + if file_ext == ".json": + export_dict: dict[str, Any] = {} + for key, value in self.palette.items(): + if _is_rgb_color(value): + item = self._format_color_output(value) + export_dict[key] = {"rgb": list(item["rgb"]), "hex": item["hex"]} + elif isinstance(value, list): + export_dict[key] = [ + {"rgb": list(item["rgb"]), "hex": item["hex"]} + for item in (self._format_color_output(c) for c in value) + ] else: - raise ValueError("Unsupported file format. Use .json, .txt, or .csv.") - else: - raise TypeError(f"Unsupported palette type: {type(self.palette)}. Must be list or dict.") - - except IOError as e: - print(f"Error writing to file {filename}: {e}") - raise # Re-raise the exception after printing - except Exception as e: - print(f"An unexpected error occurred during export: {e}") - raise # Re-raise \ No newline at end of file + export_dict[key] = value + with open(path_str, "w", encoding="utf-8") as f: + json.dump(export_dict, f, indent=4) + elif file_ext == ".txt": + with open(path_str, "w", encoding="utf-8") as f: + for key, value in self.palette.items(): + f.write(f"--- {key} ---\n") + if _is_rgb_color(value): + item = self._format_color_output(value) + f.write(f"0: {item['hex']} - RGB{item['rgb']}\n") + elif isinstance(value, list): + for i, color in enumerate(value): + item = self._format_color_output(color) + f.write(f"{i}: {item['hex']} - RGB{item['rgb']}\n") + else: + f.write(f"{value}\n") + f.write("\n") + elif file_ext == ".csv": + with open(path_str, "w", newline="", encoding="utf-8") as f: + writer = csv.writer(f) + writer.writerow(["PaletteName", "Index", "Hex", "R", "G", "B"]) + for key, value in self.palette.items(): + if _is_rgb_color(value): + item = self._format_color_output(value) + r, g, b = item["rgb"] + writer.writerow([key, 0, item["hex"], r, g, b]) + elif isinstance(value, list): + for i, color in enumerate(value): + item = self._format_color_output(color) + r, g, b = item["rgb"] + writer.writerow([key, i, item["hex"], r, g, b]) + elif file_ext == ".css": + with open(path_str, "w", encoding="utf-8") as f: + f.write(":root {\n") + for key, value in self.palette.items(): + slug = _css_slug(str(key)) + if _is_rgb_color(value): + item = self._format_color_output(value) + f.write(f" --{slug}: {item['hex']};\n") + elif isinstance(value, list): + for i, color in enumerate(value): + item = self._format_color_output(color) + f.write(f" --{slug}-{i}: {item['hex']};\n") + f.write("}\n") diff --git a/hued/py.typed b/hued/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..2d36dcd --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,84 @@ +[build-system] +requires = ["setuptools>=77.0.3", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "hued" +version = "1.1.0" +description = "An open-source, zero-dependency Python library for color conversion, WCAG accessibility analysis, perceptual color difference, harmonious palette generation, and named color lookup." +readme = "readme.md" +requires-python = ">=3.9" +authors = [{ name = "Infinitode Pty Ltd", email = "infinitode.ltd@gmail.com" }] +keywords = [ + "color", + "colour", + "palette", + "rgb", + "hex", + "hsl", + "hsv", + "cmyk", + "xyz", + "lab", + "wcag", + "contrast", + "accessibility", + "color-blindness", + "delta-e", + "gradient", +] +# MIT with an additional clause requiring substantial derivative works to be +# distributed under a different name; LicenseRef-* is the SPDX expression for +# non-standard/modified licenses (PEP 639). +license = "LicenseRef-MIT-Modified" +license-files = ["LICENSE"] +dependencies = [] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Topic :: Multimedia :: Graphics", + "Topic :: Software Development :: Libraries :: Python Modules", + "Typing :: Typed", +] + +[project.optional-dependencies] +dev = [ + "pytest>=8.0", + "ruff>=0.6", + "build>=1.2", + "twine>=5.0", +] + +[project.urls] +Homepage = "https://github.com/Infinitode/Hued" +Repository = "https://github.com/Infinitode/Hued" +Documentation = "https://infinitode-docs.gitbook.io/documentation/package-documentation/hued-package-documentation" +Issues = "https://github.com/Infinitode/Hued/issues" +Changelog = "https://github.com/Infinitode/Hued/blob/main/CHANGELOG.md" + +[tool.setuptools] +packages = ["hued"] + +[tool.setuptools.package-data] +hued = ["py.typed"] + +[tool.pytest.ini_options] +testpaths = ["Tests"] + +[tool.ruff] +line-length = 100 +target-version = "py39" +exclude = [".git", "build", "dist", "venv", ".venv"] + +[tool.ruff.lint] +select = ["E", "F", "W", "I", "B", "UP"] +ignore = ["E501", "E741"] diff --git a/readme.md b/readme.md index cf63faf..f378e7d 100644 --- a/readme.md +++ b/readme.md @@ -1,144 +1,166 @@ # Hued -![Python Version](https://img.shields.io/badge/python-3.12-blue.svg) -![Code Size](https://img.shields.io/github/languages/code-size/infinitode/hued) -![Downloads](https://pepy.tech/badge/hued) -![License Compliance](https://img.shields.io/badge/license-compliance-brightgreen.svg) -![PyPI Version](https://img.shields.io/pypi/v/hued) -An open-source Python library for color generation, conversion, and retrieval of common properties, palettes, and color information. +[![PyPI Version](https://img.shields.io/pypi/v/hued.svg)](https://pypi.org/project/hued/) +[![Python Versions](https://img.shields.io/pypi/pyversions/hued.svg)](https://pypi.org/project/hued/) +[![CI](https://github.com/Infinitode/Hued/actions/workflows/ci.yml/badge.svg)](https://github.com/Infinitode/Hued/actions/workflows/ci.yml) +[![PyPI Trusted Publishing](https://img.shields.io/badge/PyPI-Trusted%20Publishing-006dad?logo=pypi&logoColor=white)](https://pypi.org/project/hued/) +[![PEP 740 Provenance](https://img.shields.io/badge/provenance-PEP%20740%20verified-brightgreen?logo=sigstore&logoColor=white)](https://pypi.org/project/hued/) +[![SLSA Build Provenance](https://img.shields.io/badge/SLSA-build%20provenance-brightgreen?logo=github&logoColor=white)](https://github.com/Infinitode/Hued/attestations) +[![Code Size](https://img.shields.io/github/languages/code-size/Infinitode/Hued)](https://github.com/Infinitode/Hued) +[![Downloads](https://pepy.tech/badge/hued)](https://pepy.tech/project/hued) +[![License Compliance](https://img.shields.io/badge/license-MIT%20(Modified)-brightgreen.svg)](LICENSE) -### Changes in version 1.0.7: -- 2 new functions in `hued.analysis` for testing color visibility and quality, and simulating color blindness. +[Documentation](https://infinitode-docs.gitbook.io/documentation/package-documentation/hued-package-documentation) · [Changelog](CHANGELOG.md) · [PyPI](https://pypi.org/project/hued/) -> [!NOTE] -> New functions and methods won't be included in the `Tests` folder. View our documentation for the most recent and up-to-date use of this package, https://infinitode-docs.gitbook.io/documentation/package-documentation/hued-package-documentation. +An open-source, **zero-dependency** Python library for color space conversion, WCAG 2.1 accessibility analysis, perceptual color difference (CIEDE2000), color-blindness simulation, harmonious palette & gradient generation, and named color lookup. -### Changes in version 1.0.6: -- New functions under `ColorPalette` to create gradients and to export `ColorPalette` data as a CSV, TXT or JSON file. +## Changes in version 1.1.0 -### Changes in version 1.0.5: -- New conversion methods for `XYZ` / `CIE 1931 XYZ`. +See [CHANGELOG.md](CHANGELOG.md) for the full list of fixes and additions. -### Changes in version 1.0.4: -- Updated `colors.py` with 500+ new color names to map to. +- **Correctness & color-science fixes**: + - Fixed `xyz_to_rgb` (and `xyz_to_*`) crashing with `complex` numbers on pure red, pure green, and other saturated colors; updated sRGB ↔ XYZ conversions to the exact IEC 61966-2-1 D65 specification for lossless round-trips. + - Fixed `rgb_to_linear` and `get_luminance` to follow the exact IEC 61966-2-1 / WCAG 2.1 sRGB transfer function. + - Fixed `get_text_color_from_background` returning unreadable text on black, charcoal, yellow, cyan, lime, and silver backgrounds — now guarantees maximum WCAG 2.1 contrast. + - Fixed `check_color_quality` (previously always returned `True` for all 16.7M RGB colors), `simulate_color_blindness` (preserved exact neutral grays and linear luminance), `get_temperature`, `is_pastel`, `is_muted`, `hex_to_rgb` (added `#RGB` shorthand and strict validation), direct lossless `hsl_to_hsv`/`hsv_to_hsl`, `blend_colors`, and `ColorPalette` edge cases (`generate_monochromatic(1)`, `palette_to_hex()` on random palette dicts, rectangular `generate_tetradic()`, and `export_palette()` extension handling). + - Cleaned the named color catalog (removed scraped citation/vandalism artifacts, resolved duplicate names, preserved acronym casing, and added all missing W3C CSS Level 4 named colors including `Green`, `Orange`, `Purple`, `Brown`, `Gold`, and `Lavender`). +- **New features**: + - Full **CIE 1976 L\*a\*b\*** conversion suite (`rgb_to_lab`, `lab_to_rgb`, `hex_to_lab`, `lab_to_hex`, `xyz_to_lab`, `lab_to_xyz`, `hsl_to_lab`, `hsv_to_lab`, `cmyk_to_lab`, and inverses). + - Perceptual color difference `delta_e` (**CIEDE2000** and **CIE76**) and full WCAG 2.1 report `check_wcag_contrast`. + - Color utilities: `linear_to_rgb`, `invert_color`, `to_grayscale`, `adjust_lightness`, `adjust_saturation`, and linear-light `blend_colors(..., linear=True)`. + - Perceptual closest-color matching (`space="lab"` / `"cie2000"`), `get_color_by_hex`, `search_colors`, `get_random_color`, `add_color`, and `remove_color` on `ColorManager`. + - Perceptual gradients (`space="rgb" | "linear" | "lab" | "hsl"`) and `.css` custom-property export on `ColorPalette`. + - Full inline type annotations (`py.typed`), modern `pyproject.toml`, automated test suite, and **PyPI Trusted Publishing** with **PEP 740** & **SLSA** build provenance attestations. -### Changes in version 1.0.3: -- Created new functions for the `analiysis` module. Including `rgb_to_linear`, and other functions to return more color properties, like luminance and vibrancy. We've also added new functions to calculate the color contrast ratio between to colors, and an accessibility function to return if foreground text color should be `light`, or `dark`, based on the background color. -- Created a new `blend_colors` function in our `conversions` module, to blend 2 RGB colors based on a given ratio. Also created new color conversion functions to convert each format into another target format, instead of just `RGB`. -- Added 3 more color schemes to `palettes`. Created new functions under the `ColorPalette` class, for random color generation, and a batch HEX color generation function. +
+Earlier releases (1.0.3 – 1.0.7) -> [!TIP] -> Most functions rely on the **RGB** color format, but you can quickly convert between RGB, and other color formats, using the functions provided in the `conversions` module. +### Changes in version 1.0.7 +- 2 new functions in `hued.analysis` for testing color visibility/quality and simulating color blindness. -## Installation +### Changes in version 1.0.6 +- New methods under `ColorPalette` to create gradients and export `ColorPalette` data as CSV, TXT, or JSON. -You can install Hued using pip: +### Changes in version 1.0.5 +- Conversion functions for `XYZ` / `CIE 1931 XYZ`. -```bash -pip install hued -``` +### Changes in version 1.0.4 +- Updated `colors.py` with 500+ additional color names. -## Supported Python Versions +### Changes in version 1.0.3 +- Added `rgb_to_linear`, `get_luminance`, `get_vibrancy`, `color_contrast`, and `get_text_color_from_background` to `hued.analysis`. +- Added `blend_colors` and cross-format conversion helpers to `hued.conversions`. +- Added additional harmony schemes and random color generators to `ColorPalette`. -Hued supports the following Python versions: +
-- Python 3.6 -- Python 3.7 -- Python 3.8 -- Python 3.9 -- Python 3.10 -- Python 3.11 or later +## Installation -Please ensure that one of these Python versions is installed before using Hued. Hued may not work as expected on lower versions of Python than the supported. +```bash +pip install hued +``` + +**Supported Python versions:** Python **3.9+** (tested on 3.9, 3.10, 3.11, 3.12, and 3.13; compatible with 3.14). Zero external runtime dependencies. ## Features -- Color Generation: Generate random colors and palettes. -- Color Conversion: Convert between different color formats (RGB, HEX, HSL, etc.). -- Color Properties: Retrieve properties like brightness, temperature, and whether a color is muted, pastel, or vibrant. -- Color Names: Get relevant color names, based on HEX values, and convert between color names and HEX values. +- **Color Conversions**: Lossless and validated conversions across **RGB**, **HEX** (`#RRGGBB` and `#RGB`), **HSL**, **HSV**, **CMYK**, **Linear sRGB**, **CIE 1931 XYZ (D65)**, and **CIE 1976 L\*a\*b\* (D65)**, plus blending, inversion, grayscale, lightness, and saturation adjustments. +- **Accessibility & Analysis**: WCAG 2.1 relative luminance, contrast ratios, AA/AAA compliance checks, optimal foreground text selection, CIEDE2000 / CIE76 perceptual color difference (`delta_e`), color-blindness simulation, and temperature/pastel/muted/vibrant classification. +- **Color Palettes & Gradients**: Complementary, split-complementary, analogous, triadic, rectangular tetradic, square, and monochromatic harmonies; multi-space gradients (`rgb`, `linear`, `lab`, `hsl`); export to `.json`, `.csv`, `.txt`, and `.css`. +- **Named Colors**: 1,300+ named colors (including all 148 W3C CSS Color Level 4 names) with exact lookup, CSS-token matching, substring search, and RGB / L\*a\*b\* / CIEDE2000 closest-color matching. +- **Fully Typed**: Ships a PEP 561 `py.typed` marker and complete inline annotations. ## Usage -### Color Properties +### Named Colors ```python -from hued.colors import ColorManager +from hued import ColorManager -# Initialize the color manager -color_manager = ColorManager() +cm = ColorManager() -# Generate a random color -colorBlue = color_manager.get_color_by_name("Blue"); +blue = cm.get_color_by_name("Blue") +print(blue) # {'Name': 'Blue', 'Hex': '#0000FF', 'RGB': (0, 0, 255)} -print("Blue Hex:", colorBlue.get("Hex")); -``` +# Find the perceptually closest named color using CIEDE2000 +print(cm.closest_color_name("#FF5733", space="cie2000")) -> You can view more properties by going to Hued's [package documentation](https://infinitode-docs.gitbook.io/documentation/package-documentation/hued-package-documentation) +# Search and pick random named colors +print(len(cm.search_colors("cerulean"))) +print(cm.get_random_color()) +``` -### Color Conversion +### Color Conversion & Manipulation ```python -from hued.conversions import hex_to_rgb, rgb_to_hsl - -# Convert HEX to RGB -rgb_color = hex_to_rgb("FF0000"); # Red -print(f"Hex to RGB: {rgb_color}") - -# Convert RGB to HSL -hsl_color = rgb_to_hsl(255, 0, 0) # Red -print(f"RGB to HSL: {hsl_color}") +from hued import ( + adjust_lightness, + blend_colors, + hex_to_rgb, + rgb_to_hsl, + rgb_to_lab, +) + +rgb = hex_to_rgb("#FF5733") # (255, 87, 51) — 3-digit '#F53' also works +hsl = rgb_to_hsl(*rgb) # (10.59, 1.0, 0.6) +lab = rgb_to_lab(*rgb) # CIE 1976 L*a*b* (D65) + +mixed = blend_colors((255, 0, 0), (0, 255, 0), 0.5, linear=True) +lighter = adjust_lightness(rgb, 0.15) ``` -### Color Analysis +### Accessibility, Contrast & Perceptual Analysis ```python -from hued.analysis import get_temperature, is_pastel - -# Check if a color is a pastel color -pastel_color = (255, 200, 200) # Example pastel color -is_pastel = is_pastel(pastel_color) -print(f"Is Pastel: {is_pastel}") - -# Check if a color is vibrant -warm_color = (255, 0, 0) # Example warm color -temperature = get_temperature(warm_color) -print(f"The current color is: {temperature}") # Warm +from hued import ( + check_wcag_contrast, + delta_e, + get_temperature, + get_text_color_from_background, + is_pastel, + simulate_color_blindness, +) + +print(is_pastel((255, 200, 200))) # True +print(get_temperature((255, 215, 0))) # 'Warm' +print(get_text_color_from_background((255, 255, 0))) # 'dark' +print(check_wcag_contrast((20, 20, 20), (255, 255, 255))) +print(round(delta_e((255, 0, 0), (240, 15, 10)), 2)) # CIEDE2000 +print(simulate_color_blindness((220, 50, 80), "deuteranopia")) ``` -### Color Generation and Palettes +### Palettes, Gradients & Export ```python -from hued.palettes import ColorPalette - -base_color = (255, 60, 52) # Red +from hued import ColorPalette -# Initialize the ColorPalette with a base color (RGB) -palette = ColorPalette(base_color) +palette = ColorPalette((255, 60, 52)) +print(palette.generate_complementary()) +print(palette.generate_tetradic()) # Rectangular double-complementary -# Get the complementary color -complementary = palette.generate_complementary() -print(f"Complementary color of {base_color}: {complementary}") +# Perceptually smooth gradient in CIE L*a*b* space +gradient = palette.generate_gradient((255, 60, 52), (51, 247, 255), steps=5, space="lab") -# Generate a random palette, with calculated color schemes, and base color -random_palette = palette.generate_random_palette() -print(f"Generated color palette's base color: {random_palette.get('Base Color')}") +# Export palettes to .json, .csv, .txt, or .css +palette.export_palette("palette.css") ``` -> More functions are available for the `ColorPalette` class, including converting all contained colors to **Hex colors**. +## Release Provenance & Verification -## Contributing +Releases of `hued` are published directly from GitHub Actions using **PyPI OIDC Trusted Publishing** (no long-lived API tokens) with automatic **PEP 740** digital provenance attestations on [PyPI](https://pypi.org/project/hued/) and **SLSA v1.0** build provenance attestations on [GitHub](https://github.com/Infinitode/Hued/attestations). -Contributions are welcome! If you encounter any issues, have suggestions, or want to contribute to Hued, please open an issue or submit a pull request on [GitHub](https://github.com/infinitode/hued). +You can verify any downloaded distribution artifact with the GitHub CLI: -## License +```bash +gh attestation verify hued-*.whl --repo Infinitode/Hued +``` -Hued is released under the terms of the **MIT License (Modified)**. Please see the [LICENSE](https://github.com/infinitode/hued/blob/main/LICENSE) file for the full text. +## Contributing -**Modified License Clause** +Contributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup and testing instructions, or open an issue / pull request on [GitHub](https://github.com/Infinitode/Hued). -The modified license clause grants users the permission to make derivative works based on the Hued software. However, it requires any substantial changes to the software to be clearly distinguished from the original work and distributed under a different name. +## License -By enforcing this distinction, it aims to prevent direct publishing of the source code without changes while allowing users to create derivative works that incorporate the code but are not exactly the same. +Hued is released under the terms of the **MIT License (Modified)**. See [LICENSE](LICENSE) for the full text. -Please read the full license terms in the [LICENSE](https://github.com/infinitode/hued/blob/main/LICENSE) file for complete details. +**Modified License Clause:** Derivative works based on Hued are permitted provided that any substantial changes are clearly distinguished from the original work and distributed under a different name. diff --git a/setup.py b/setup.py deleted file mode 100644 index 9a36fe9..0000000 --- a/setup.py +++ /dev/null @@ -1,31 +0,0 @@ -from setuptools import setup, find_packages - -with open("readme.md", "r", encoding="utf-8") as fh: - long_description = fh.read() - -setup( - name='hued', - version='{{VERSION_PLACEHOLDER}}', - author='Infinitode Pty Ltd', - author_email='infinitode.ltd@gmail.com', - description='An open-source Python library for color processing, random color generation, conversion between common types, and retrieval of common color properties, color palettes, and color information.', - long_description=long_description, - long_description_content_type='text/markdown', - url='https://github.com/infinitode/hued', - packages=find_packages(), - classifiers=[ - 'Development Status :: 5 - Production/Stable', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: MIT License', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Programming Language :: Python :: 3.11', - 'Programming Language :: Python :: 3.12', - 'Programming Language :: Python :: 3.13', - ], - python_requires='>=3.6', -) \ No newline at end of file From b564381428f7aeb02eac47ee779383b800a18bd0 Mon Sep 17 00:00:00 2001 From: johanbeytell1 <107624055+johanbeytell1@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:16:05 +0000 Subject: [PATCH 2/2] ci: update Python test matrix for Ubuntu 26.04 runners (3.10-3.14) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- .github/workflows/ci.yml | 2 +- readme.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d1accbf..d32eeba 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -36,7 +36,7 @@ jobs: strategy: fail-fast: false matrix: - python-version: ${{ (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/master') && fromJSON('["3.9", "3.10", "3.11", "3.12", "3.13"]') || fromJSON('["3.9", "3.13"]') }} + python-version: ${{ (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/master') && fromJSON('["3.10", "3.11", "3.12", "3.13", "3.14"]') || fromJSON('["3.10", "3.14"]') }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: diff --git a/readme.md b/readme.md index f378e7d..cd2d73c 100644 --- a/readme.md +++ b/readme.md @@ -60,7 +60,7 @@ See [CHANGELOG.md](CHANGELOG.md) for the full list of fixes and additions. pip install hued ``` -**Supported Python versions:** Python **3.9+** (tested on 3.9, 3.10, 3.11, 3.12, and 3.13; compatible with 3.14). Zero external runtime dependencies. +**Supported Python versions:** Python **3.9+** (CI-tested across Python 3.10–3.14). Zero external runtime dependencies. ## Features