[
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\ngithub: [ChenglongMa] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]\nbuy_me_a_coffee: chenglongma\npatreon: # Replace with a single Patreon username\nopen_collective: # Replace with a single Open Collective username\nko_fi: # Replace with a single Ko-fi username\ntidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel\ncommunity_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry\nliberapay: # Replace with a single Liberapay username\nissuehunt: # Replace with a single IssueHunt username\notechie: # Replace with a single Otechie username\nlfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry\ncustom: [\"https://www.paypal.me/imchenglong\"] # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: \"[\\U0001F41B BUG] Please describe the bug briefly.\"\nlabels: bug\nassignees: ''\n\n---\n\n**Describe the bug**\nA clear and concise description of what the bug is.\n\n**To Reproduce**\nSteps to reproduce the behavior:\n1. Run commands in the command line, e.g., \n    ```bash\n    stone -i /path/to/images -d -t color ...\n    ```\n2. Or, import `stone` to other projects, e.g., \n    ```python\n    import stone\n    \n    stone.process('/path/to/images')\n    ```\n\n**Expected behavior**\nA clear and concise description of what you expected to happen.\n\n**Screenshots**\nIf applicable, add screenshots to help explain your problem.\n\n**Desktop (please complete the following information):**\n - OS: [e.g. iOS, Windows 10/11]\n - Python Version [e.g. 3.7]\n - Using Conda? [anaconda or miniconda]\n - Version [e.g. v1.1.0]\n\n**Additional context**\nAdd any other context about the problem here.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "content": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: \"[\\U0001F4A1 FEAT] Please describe what feature or solution you need.\"\nlabels: enhancement\nassignees: ''\n\n---\n\n**Is your feature request related to a problem? Please describe.**\nA clear and concise description of what the problem is. Ex. I'm always frustrated when [...]\n\n**Describe the solution you'd like**\nA clear and concise description of what you want to happen.\n\n**Describe alternatives you've considered**\nA clear and concise description of any alternative solutions or features you've considered.\n\n**Additional context**\nAdd any other context or screenshots about the feature request here.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/q-a.md",
    "content": "---\nname: Q&A\nabout: Have any questions about this project?\ntitle: \"[❓ Question] Please describe your question briefly.\"\nlabels: help wanted, question\nassignees: ''\n\n---\n\n# Before you start\n\n*NOTE: [Discussions](https://github.com/ChenglongMa/SkinToneClassifier/discussions) is a better place to find **Q&A** or other discussions*\n\n# Question\n*Description your question here*\n"
  },
  {
    "path": ".github/workflows/python-publish.yml",
    "content": "# This workflow will upload a Python Package using Twine when a release is created\n# For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries\n\n# This workflow uses actions that are not certified by GitHub.\n# They are provided by a third-party and are governed by\n# separate terms of service, privacy policy, and support\n# documentation.\n\nname: Upload Python Package\n\non:\n  release:\n    types: [published]\n\npermissions:\n  contents: read\n\njobs:\n  deploy:\n\n    runs-on: ubuntu-latest\n\n    steps:\n    - uses: actions/checkout@v4\n    - name: Set up Python\n      uses: actions/setup-python@v5\n      with:\n        python-version: '3.x'\n    - name: Install dependencies\n      run: |\n        python -m pip install --upgrade pip\n        pip install build\n    - name: Build package\n      run: python -m build\n    - name: Publish package\n      uses: pypa/gh-action-pypi-publish@v1.13.0\n      with:\n        user: __token__\n        password: ${{ secrets.PYPI_API_TOKEN }}\n"
  },
  {
    "path": ".github/workflows/test.yml",
    "content": "# this file is *not* meant to cover or endorse the use of GitHub Actions, but rather to\n# help test this project\n\nname: Test\n\non: [push, pull_request]\n\njobs:\n  test:\n    strategy:\n      matrix:\n        python: ['3.9', '3.10', '3.11', '3.12']\n        platform: [ubuntu-latest, macos-latest, windows-latest]\n    runs-on: ${{ matrix.platform }}\n    steps:\n    - name: Checkout\n      uses: actions/checkout@v4\n    - name: Set up Python ${{ matrix.python }}\n      uses: actions/setup-python@v5\n      with:\n        python-version: ${{ matrix.python }}\n    - name: Install test dependencies\n      run: python -m pip install -U tox\n    - name: Test\n      run: python -m tox -e py\n"
  },
  {
    "path": ".github/workflows/toc.yml",
    "content": "name: TOC Generator\non:\n  push:\n    branches: [main]\n    paths:\n    - 'README.md'\njobs:\n  generateTOC:\n    name: TOC Generator\n    runs-on: ubuntu-latest\n    steps:\n      - name: Check out repository\n        uses: actions/checkout@v2\n\n      - uses: technote-space/toc-generator@v4\n        with:\n          FOLDING: false\n"
  },
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n\n.idea/shelf/\n.idea/workspace.xml\n# Editor-based HTTP Client requests\n.idea/httpRequests/\n# Datasource local storage ignored files\n.idea/dataSources/\n.idea/dataSources.local.xml\ndebug*/\nlog/\nresult*.csv\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\npip-wheel-metadata/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n.python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n\nimages/\ntemp*\nexcluded/"
  },
  {
    "path": ".idea/.gitignore",
    "content": "# Default ignored files\n/shelf/\n/workspace.xml\n# Editor-based HTTP Client requests\n/httpRequests/\n# Datasource local storage ignored files\n/dataSources/\n/dataSources.local.xml\n"
  },
  {
    "path": ".idea/SkinToneClassifier.iml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<module type=\"PYTHON_MODULE\" version=\"4\">\n  <component name=\"NewModuleRootManager\">\n    <content url=\"file://$MODULE_DIR$\">\n      <sourceFolder url=\"file://$MODULE_DIR$/src\" isTestSource=\"false\" />\n      <sourceFolder url=\"file://$MODULE_DIR$/tests\" isTestSource=\"true\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/build\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/dist\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/excluded\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/src/skin_tone_classifier.egg-info\" />\n      <excludeFolder url=\"file://$MODULE_DIR$/.venv\" />\n    </content>\n    <orderEntry type=\"jdk\" jdkName=\"uv (SkinToneClassifier)\" jdkType=\"Python SDK\" />\n    <orderEntry type=\"sourceFolder\" forTests=\"false\" />\n  </component>\n  <component name=\"PackageRequirementsSettings\">\n    <option name=\"versionSpecifier\" value=\"Strong equality (==x.y.z)\" />\n  </component>\n</module>"
  },
  {
    "path": ".idea/inspectionProfiles/Project_Default.xml",
    "content": "<component name=\"InspectionProjectProfileManager\">\n  <profile version=\"1.0\">\n    <option name=\"myName\" value=\"Project Default\" />\n    <inspection_tool class=\"PyPep8NamingInspection\" enabled=\"true\" level=\"WEAK WARNING\" enabled_by_default=\"true\">\n      <option name=\"ignoredErrors\">\n        <list>\n          <option value=\"N806\" />\n          <option value=\"N803\" />\n          <option value=\"N802\" />\n        </list>\n      </option>\n    </inspection_tool>\n  </profile>\n</component>"
  },
  {
    "path": ".idea/inspectionProfiles/profiles_settings.xml",
    "content": "<component name=\"InspectionProjectProfileManager\">\n  <settings>\n    <option name=\"USE_PROJECT_PROFILE\" value=\"false\" />\n    <version value=\"1.0\" />\n  </settings>\n</component>"
  },
  {
    "path": ".idea/misc.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project version=\"4\">\n  <component name=\"Black\">\n    <option name=\"cmdArguments\" value=\"--line-length=120\" />\n    <option name=\"enabledOnReformat\" value=\"true\" />\n    <option name=\"sdkName\" value=\"other\" />\n  </component>\n  <component name=\"ProjectRootManager\" version=\"2\" project-jdk-name=\"uv (SkinToneClassifier)\" project-jdk-type=\"Python SDK\" />\n  <component name=\"PythonCompatibilityInspectionAdvertiser\">\n    <option name=\"version\" value=\"3\" />\n  </component>\n</project>"
  },
  {
    "path": ".idea/modules.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project version=\"4\">\n  <component name=\"ProjectModuleManager\">\n    <modules>\n      <module fileurl=\"file://$PROJECT_DIR$/.idea/SkinToneClassifier.iml\" filepath=\"$PROJECT_DIR$/.idea/SkinToneClassifier.iml\" />\n    </modules>\n  </component>\n</project>"
  },
  {
    "path": ".idea/other.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project version=\"4\">\n  <component name=\"PySciProjectComponent\">\n    <option name=\"PY_SCI_VIEW_SUGGESTED\" value=\"true\" />\n  </component>\n</project>"
  },
  {
    "path": ".idea/runConfigurations/build.xml",
    "content": "<component name=\"ProjectRunConfigurationManager\">\n  <configuration default=\"false\" name=\"build\" type=\"PythonConfigurationType\" factoryName=\"Python\" nameIsGenerated=\"true\">\n    <module name=\"SkinToneClassifier\" />\n    <option name=\"ENV_FILES\" value=\"\" />\n    <option name=\"INTERPRETER_OPTIONS\" value=\"\" />\n    <option name=\"PARENT_ENVS\" value=\"true\" />\n    <envs>\n      <env name=\"PYTHONUNBUFFERED\" value=\"1\" />\n    </envs>\n    <option name=\"SDK_HOME\" value=\"\" />\n    <option name=\"SDK_NAME\" value=\"stone\" />\n    <option name=\"WORKING_DIRECTORY\" value=\"$ContentRoot$\" />\n    <option name=\"IS_MODULE_SDK\" value=\"false\" />\n    <option name=\"ADD_CONTENT_ROOTS\" value=\"true\" />\n    <option name=\"ADD_SOURCE_ROOTS\" value=\"true\" />\n    <EXTENSION ID=\"PythonCoverageRunConfigurationExtension\" runner=\"coverage.py\" />\n    <option name=\"SCRIPT_NAME\" value=\"build\" />\n    <option name=\"PARAMETERS\" value=\"\" />\n    <option name=\"SHOW_COMMAND_LINE\" value=\"false\" />\n    <option name=\"EMULATE_TERMINAL\" value=\"false\" />\n    <option name=\"MODULE_MODE\" value=\"true\" />\n    <option name=\"REDIRECT_INPUT\" value=\"false\" />\n    <option name=\"INPUT_FILE\" value=\"\" />\n    <method v=\"2\">\n      <option name=\"RunConfigurationTask\" enabled=\"true\" run_configuration_name=\"pre-build\" run_configuration_type=\"PythonConfigurationType\" />\n      <option name=\"RunConfigurationTask\" enabled=\"true\" run_configuration_name=\"clean-up.ps1\" run_configuration_type=\"PowerShellRunType\" />\n    </method>\n  </configuration>\n</component>"
  },
  {
    "path": ".idea/runConfigurations/install_test.xml",
    "content": "<component name=\"ProjectRunConfigurationManager\">\n  <configuration default=\"false\" name=\"install test\" type=\"PythonConfigurationType\" factoryName=\"Python\">\n    <module name=\"SkinToneClassifier\" />\n    <option name=\"ENV_FILES\" value=\"\" />\n    <option name=\"INTERPRETER_OPTIONS\" value=\"\" />\n    <option name=\"PARENT_ENVS\" value=\"true\" />\n    <envs>\n      <env name=\"PYTHONUNBUFFERED\" value=\"1\" />\n    </envs>\n    <option name=\"SDK_HOME\" value=\"\" />\n    <option name=\"SDK_NAME\" value=\"stone\" />\n    <option name=\"WORKING_DIRECTORY\" value=\"$ContentRoot$\" />\n    <option name=\"IS_MODULE_SDK\" value=\"false\" />\n    <option name=\"ADD_CONTENT_ROOTS\" value=\"true\" />\n    <option name=\"ADD_SOURCE_ROOTS\" value=\"true\" />\n    <EXTENSION ID=\"PythonCoverageRunConfigurationExtension\" runner=\"coverage.py\" />\n    <option name=\"SCRIPT_NAME\" value=\"pip\" />\n    <option name=\"PARAMETERS\" value=\"install -i https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ skin-tone-classifier==1.2.3.dev0 --force-reinstall --upgrade\" />\n    <option name=\"SHOW_COMMAND_LINE\" value=\"false\" />\n    <option name=\"EMULATE_TERMINAL\" value=\"false\" />\n    <option name=\"MODULE_MODE\" value=\"true\" />\n    <option name=\"REDIRECT_INPUT\" value=\"false\" />\n    <option name=\"INPUT_FILE\" value=\"\" />\n    <method v=\"2\" />\n  </configuration>\n</component>"
  },
  {
    "path": ".idea/runConfigurations/pre_build.xml",
    "content": "<component name=\"ProjectRunConfigurationManager\">\n  <configuration default=\"false\" name=\"pre-build\" type=\"PythonConfigurationType\" factoryName=\"Python\">\n    <module name=\"SkinToneClassifier\" />\n    <option name=\"ENV_FILES\" value=\"\" />\n    <option name=\"INTERPRETER_OPTIONS\" value=\"\" />\n    <option name=\"PARENT_ENVS\" value=\"true\" />\n    <envs>\n      <env name=\"PYTHONUNBUFFERED\" value=\"1\" />\n    </envs>\n    <option name=\"SDK_HOME\" value=\"\" />\n    <option name=\"SDK_NAME\" value=\"stone\" />\n    <option name=\"WORKING_DIRECTORY\" value=\"$ContentRoot$\" />\n    <option name=\"IS_MODULE_SDK\" value=\"false\" />\n    <option name=\"ADD_CONTENT_ROOTS\" value=\"true\" />\n    <option name=\"ADD_SOURCE_ROOTS\" value=\"true\" />\n    <EXTENSION ID=\"PythonCoverageRunConfigurationExtension\" runner=\"coverage.py\" />\n    <option name=\"SCRIPT_NAME\" value=\"pip\" />\n    <option name=\"PARAMETERS\" value=\"install --upgrade build twine\" />\n    <option name=\"SHOW_COMMAND_LINE\" value=\"false\" />\n    <option name=\"EMULATE_TERMINAL\" value=\"false\" />\n    <option name=\"MODULE_MODE\" value=\"true\" />\n    <option name=\"REDIRECT_INPUT\" value=\"false\" />\n    <option name=\"INPUT_FILE\" value=\"\" />\n    <method v=\"2\" />\n  </configuration>\n</component>"
  },
  {
    "path": ".idea/runConfigurations/pre_test.xml",
    "content": "<component name=\"ProjectRunConfigurationManager\">\n  <configuration default=\"false\" name=\"pre-test\" type=\"PythonConfigurationType\" factoryName=\"Python\">\n    <module name=\"SkinToneClassifier\" />\n    <option name=\"ENV_FILES\" value=\"\" />\n    <option name=\"INTERPRETER_OPTIONS\" value=\"\" />\n    <option name=\"PARENT_ENVS\" value=\"true\" />\n    <envs>\n      <env name=\"PYTHONUNBUFFERED\" value=\"1\" />\n    </envs>\n    <option name=\"SDK_HOME\" value=\"\" />\n    <option name=\"SDK_NAME\" value=\"stone\" />\n    <option name=\"WORKING_DIRECTORY\" value=\"$ContentRoot$\" />\n    <option name=\"IS_MODULE_SDK\" value=\"false\" />\n    <option name=\"ADD_CONTENT_ROOTS\" value=\"true\" />\n    <option name=\"ADD_SOURCE_ROOTS\" value=\"true\" />\n    <EXTENSION ID=\"PythonCoverageRunConfigurationExtension\" runner=\"coverage.py\" />\n    <option name=\"SCRIPT_NAME\" value=\"pip\" />\n    <option name=\"PARAMETERS\" value=\"install --upgrade tox\" />\n    <option name=\"SHOW_COMMAND_LINE\" value=\"false\" />\n    <option name=\"EMULATE_TERMINAL\" value=\"false\" />\n    <option name=\"MODULE_MODE\" value=\"true\" />\n    <option name=\"REDIRECT_INPUT\" value=\"false\" />\n    <option name=\"INPUT_FILE\" value=\"\" />\n    <method v=\"2\" />\n  </configuration>\n</component>"
  },
  {
    "path": ".idea/runConfigurations/publish_pypi.xml",
    "content": "<component name=\"ProjectRunConfigurationManager\">\n  <configuration default=\"false\" name=\"publish pypi\" type=\"PythonConfigurationType\" factoryName=\"Python\">\n    <module name=\"SkinToneClassifier\" />\n    <option name=\"ENV_FILES\" value=\"\" />\n    <option name=\"INTERPRETER_OPTIONS\" value=\"\" />\n    <option name=\"PARENT_ENVS\" value=\"true\" />\n    <envs>\n      <env name=\"PYTHONUNBUFFERED\" value=\"1\" />\n    </envs>\n    <option name=\"SDK_HOME\" value=\"\" />\n    <option name=\"SDK_NAME\" value=\"stone\" />\n    <option name=\"WORKING_DIRECTORY\" value=\"$ContentRoot$\" />\n    <option name=\"IS_MODULE_SDK\" value=\"false\" />\n    <option name=\"ADD_CONTENT_ROOTS\" value=\"true\" />\n    <option name=\"ADD_SOURCE_ROOTS\" value=\"true\" />\n    <EXTENSION ID=\"PythonCoverageRunConfigurationExtension\" runner=\"coverage.py\" />\n    <option name=\"SCRIPT_NAME\" value=\"twine\" />\n    <option name=\"PARAMETERS\" value=\"upload dist/*\" />\n    <option name=\"SHOW_COMMAND_LINE\" value=\"false\" />\n    <option name=\"EMULATE_TERMINAL\" value=\"false\" />\n    <option name=\"MODULE_MODE\" value=\"true\" />\n    <option name=\"REDIRECT_INPUT\" value=\"false\" />\n    <option name=\"INPUT_FILE\" value=\"\" />\n    <method v=\"2\">\n      <option name=\"RunConfigurationTask\" enabled=\"false\" run_configuration_name=\"build\" run_configuration_type=\"PythonConfigurationType\" />\n    </method>\n  </configuration>\n</component>"
  },
  {
    "path": ".idea/runConfigurations/publish_test.xml",
    "content": "<component name=\"ProjectRunConfigurationManager\">\n  <configuration default=\"false\" name=\"publish test\" type=\"PythonConfigurationType\" factoryName=\"Python\">\n    <module name=\"SkinToneClassifier\" />\n    <option name=\"ENV_FILES\" value=\"\" />\n    <option name=\"INTERPRETER_OPTIONS\" value=\"\" />\n    <option name=\"PARENT_ENVS\" value=\"true\" />\n    <envs>\n      <env name=\"PYTHONUNBUFFERED\" value=\"1\" />\n    </envs>\n    <option name=\"SDK_HOME\" value=\"\" />\n    <option name=\"SDK_NAME\" value=\"uv (SkinToneClassifier)\" />\n    <option name=\"WORKING_DIRECTORY\" value=\"$ContentRoot$\" />\n    <option name=\"IS_MODULE_SDK\" value=\"false\" />\n    <option name=\"ADD_CONTENT_ROOTS\" value=\"true\" />\n    <option name=\"ADD_SOURCE_ROOTS\" value=\"true\" />\n    <EXTENSION ID=\"PythonCoverageRunConfigurationExtension\" runner=\"coverage.py\" />\n    <option name=\"SCRIPT_NAME\" value=\"twine\" />\n    <option name=\"PARAMETERS\" value=\"upload --repository testpypi dist/*\" />\n    <option name=\"SHOW_COMMAND_LINE\" value=\"false\" />\n    <option name=\"EMULATE_TERMINAL\" value=\"false\" />\n    <option name=\"MODULE_MODE\" value=\"true\" />\n    <option name=\"REDIRECT_INPUT\" value=\"false\" />\n    <option name=\"INPUT_FILE\" value=\"\" />\n    <method v=\"2\">\n      <option name=\"RunConfigurationTask\" enabled=\"true\" run_configuration_name=\"build\" run_configuration_type=\"PythonConfigurationType\" />\n      <option name=\"RunConfigurationTask\" enabled=\"true\" run_configuration_name=\"tox test\" run_configuration_type=\"PythonConfigurationType\" />\n    </method>\n  </configuration>\n</component>"
  },
  {
    "path": ".idea/runConfigurations/tox_test.xml",
    "content": "<component name=\"ProjectRunConfigurationManager\">\n  <configuration default=\"false\" name=\"tox test\" type=\"PythonConfigurationType\" factoryName=\"Python\">\n    <module name=\"SkinToneClassifier\" />\n    <option name=\"ENV_FILES\" value=\"\" />\n    <option name=\"INTERPRETER_OPTIONS\" value=\"\" />\n    <option name=\"PARENT_ENVS\" value=\"true\" />\n    <envs>\n      <env name=\"PYTHONUNBUFFERED\" value=\"1\" />\n    </envs>\n    <option name=\"SDK_HOME\" value=\"\" />\n    <option name=\"SDK_NAME\" value=\"stone\" />\n    <option name=\"WORKING_DIRECTORY\" value=\"$ContentRoot$\" />\n    <option name=\"IS_MODULE_SDK\" value=\"false\" />\n    <option name=\"ADD_CONTENT_ROOTS\" value=\"true\" />\n    <option name=\"ADD_SOURCE_ROOTS\" value=\"true\" />\n    <EXTENSION ID=\"PythonCoverageRunConfigurationExtension\" runner=\"coverage.py\" />\n    <option name=\"SCRIPT_NAME\" value=\"tox\" />\n    <option name=\"PARAMETERS\" value=\"-e py\" />\n    <option name=\"SHOW_COMMAND_LINE\" value=\"false\" />\n    <option name=\"EMULATE_TERMINAL\" value=\"false\" />\n    <option name=\"MODULE_MODE\" value=\"true\" />\n    <option name=\"REDIRECT_INPUT\" value=\"false\" />\n    <option name=\"INPUT_FILE\" value=\"\" />\n    <method v=\"2\">\n      <option name=\"RunConfigurationTask\" enabled=\"true\" run_configuration_name=\"pre-test\" run_configuration_type=\"PythonConfigurationType\" />\n    </method>\n  </configuration>\n</component>"
  },
  {
    "path": ".idea/vcs.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project version=\"4\">\n  <component name=\"VcsDirectoryMappings\">\n    <mapping directory=\"$PROJECT_DIR$\" vcs=\"Git\" />\n  </component>\n</project>"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Changelogs\n\n## v1.2.6\n\n<details markdown=\"1\" open>\n  <summary><i>Click here to show more.</i></summary>\n\nIn this version, we have made the following changes:\n\n1. ✨ **NEW!**: We have added one new built-in skin tone palette: Monk Skin Tone Palette.\n\n</details>\n\n## v1.2.5\n\n<details markdown=\"1\" open>\n  <summary><i>Click here to show more.</i></summary>\n\nIn this version, we have made the following changes:\n\n1. ✨ **NEW!**: We have added two new built-in skin tone palettes.\n    * The all available colored palettes are `perla`, `yadon-ostfeld`, `proder`.\n    * You can use the `-p` option to specify the palette for the processed images.\n      - For example, `stone -i ./path/to/images/ -p yadon-ostfeld`.\n    * The default palette `perla` is used for color images, and the `bw` palette is used for black/white\n      images.\n2. ✨ **NEW!**: We have added some new use cases like Web API based projects in the documentation.\n\n</details>\n\n## v1.2.4\n\n<details markdown=\"1\">\n  <summary><i>Click here to show more.</i></summary>\n\nIn this version, we have made the following changes:\n\n1. 🐛 **FIX!**: We fixed a bug where the app will crash when using the `-bw` option.\n     \nThanks [ergo70](https://github.com/ergo70)'s feedback in [issue#25](https://github.com/ChenglongMa/SkinToneClassifier/issues/25).\n\n</details>\n\n## v1.2.3\n\n<details markdown=\"1\">\n  <summary><i>Click here to show more.</i></summary>\n\nIn this version, we have made the following changes:\n\n1. 🧬 **CHANGE!**: We change the GUI mode to **optional**.\n    * Now, you can install the GUI mode by running:\n      * ```bash\n        pip install skin-tone-classifier[all] --upgrade\n        ```\n      * It will support both the **CLI** mode and the **GUI** mode.\n    * If you don't specify the `[all]` option, the app will install the CLI mode only.\n2. 🧬 **CHANGE!**: [For developer]. We base the project to `project.toml` instead of `setup.py`.\n     \n\n</details>\n\n## v1.2.0\n\n<details markdown=\"1\">\n  <summary><i>Click here to show more.</i></summary>\n\nIn this version, we have made the following changes:\n\n1. ✨ **NEW!**: We add a GUI version of `stone` for users who are not familiar with the command line interface.\n    * You can use the config GUI of `stone` to process the images.\n    * See more information at [here](#use-stone-in-a-gui).\n2. ✨ **NEW!**: We add new **patterns** in the `-l` (or `--labels`) option to set the skin tone labels.\n    * Now, you can use the following patterns to set the skin tone labels:\n        * **Default value**: the uppercase alphabet list leading by the image type (`C` for `color`; `B`\n          for `Black&White`).\n        * Specify the labels directly using _a space_ as delimiters, e.g., `-l A B C D E` or `-l 1 2 3 4 5`.\n        * Specify the range of labels using _a hyphen_ as delimiters, e.g.,\n            * `-l A-E` (equivalent to `-l A B C D E`);\n            * `-l A-E-2` (equivalent to `-l A C E`);\n            * `-l 1-5` (equivalent to `-l 1 2 3 4 5`);\n            * `-l 1-10-3` (equivalent to `-l 1 4 7 10`);\n    * **NB**: The number of skin tone labels should be equal to the number of colors in the palette.\n\n</details>\n\n## v1.1.2\n\n<details markdown=\"1\">\n  <summary><i>Click here to show more.</i></summary>\n\nIn this version, we have made the following changes:\n\n1. 🐛 **FIX!**: We fixed a bug where the app will crash when using the `-bw` option.\n   Error message: `cannot reshape array of size 62500 into shape (3)`.\n2. 🐛 **FIX!**: We fixed a bug where the app may identify the image type as `color` when using the `-bw` option.\n\n</details>\n\n## v1.1.1\n\n<details markdown=\"1\">\n  <summary><i>Click here to show more.</i></summary>\n\nIn this version, we have made the following changes:\n\n1. ✨ **NEW!**: We add the `-v` (or `--version`) option to show the version number.\n2. ✨ **NEW!**: We add the `-r` (or `--recursive`) option to **enable** recursive search for images.\n    * For example, `stone -i ./path/to/images/ -r` will search all images in the `./path/to/images/` directory **and its\n      subdirectories**.\n    * `stone -i ./path/to/images/` will only search images in the `./path/to/images/` directory.\n3. 🐛 **FIX!**: We fixed a bug where the app cannot correctly identify the current folder if `-i` option is not\n   specified.\n\n</details>\n\n## v1.1.0\n\n<details markdown=\"1\">\n  <summary><i>Click here to show more.</i></summary>\n\nIn this version, we have made the following changes:\n\n1. ✨ **NEW!**: Now, `stone` can not only be run on **the command line**, but can also be **imported** into other\n   projects for use. Check [this](#9-used-as-a-library-by-importing-into-other-projects) for more details.\n    * We expose the `process` and `show` functions in the `stone` package.\n2. ✨ **NEW!**: We add `URL` support for the input images.\n    * Now, you can specify the input image as a URL, e.g., `https://example.com/images/pic.jpg`. Of course, you can mix\n      the URLs and local filenames.\n3. ✨ **NEW!**: We add **recursive search** support for the input images.\n    * Now, when you specify the input image as a directory, e.g., `./path/to/images/`.\n      The app will search all images in the directory recursively.\n4. 🧬 **CHANGE!**: We change the column header in `result.csv`:\n    * `prop` => `percent`\n    * `PERLA` => `tone label`\n5. 🐛 **FIX!**: We fixed a bug where the app would not correctly sort files that did not contain numbers in their\n   filenames.\n\n</details>\n\n## v1.0.1\n\n<details markdown=\"1\">\n  <summary><i>Click here to show more.</i></summary>\n\n1. 👋 **BYE**: We have removed the function to pop up a resulting window when processing a **single** image.\n\n    * It can raise an error when running the app in a **web browser** environment, e.g., Jupyter Notebook or Google\n      Colab.\n    * If you want to see the processed image, please use the `-d` option to store the report image in the `./debug`\n      folder.\n\n</details>\n\n## v1.0.0\n\n<details markdown=\"1\">\n  <summary><i>Click here to show more.</i></summary>\n\n🎉**We have officially released the 1.0.0 version of the library!** In this version, we have made the following changes:\n\n1. ✨ **NEW!**: We add the `threshold` parameter to control the minimum percentage of required face areas (Defaults to\n   0.15).\n    * In previous versions, the library could incorrectly identify non-face areas as faces, such as shirts, collars,\n      necks, etc.\n      In order to improve its accuracy, the new version will further calculate the proportion of skin in the recognized\n      area\n      after recognizing the facial area. If it is less than the `threshold` value, the recognition area will be ignored.\n      (While it's still not perfect, it's an improvement over what it was before.)\n2. ✨ **NEW!**: Now, we will back up the previous results if it already exists.\n   The backup file will be named as `result_bak_<current_timestamp>.csv`.\n3. 🐛 **FIX!**: We fix the bug that the `image_type` option does not work in the previous version.\n4. 🐛 **FIX!**: We fix the bug that the library will create an empty `log` folder when checking the help information by\n   running `stone -h`.\n\n</details>\n\n## v0.2.0\n\n<details markdown=\"1\">\n  <summary><i>Click here to show more.</i></summary>\n\nIn this version, we have made the following changes:\n\n1. ✨ **NEW!**: Now we support skin tone classification for **black and white** images.\n    * In this case, the app will use different skin tone palettes for color images and black/white images.\n    * We use a new parameter `-t` or `--image_type` to specify the type of the input image.\n      It can be `color`, `bw` or `auto`(default).\n      `auto` will let the app automatically detect whether the input is color or black/white image.\n    * We use a new parameter `-bw` or `--black_white` to specify whether to convert the input to black/white image.\n      If so, the app will convert the input to black/white image and then classify the skin tones based on the\n      black/white palette.\n\n      For example:\n      <div style=\"display: flex; align-items: center;\">\n         <img src=\"https://raw.githubusercontent.com/ChenglongMa/SkinToneClassifier/main/docs/demo-1.png\" alt=\"Processing color image\" style=\"display: block; margin: 20px\">\n         <img src=\"https://raw.githubusercontent.com/ChenglongMa/SkinToneClassifier/main/docs/demo_bw-1.png\" alt=\"Processing black/white image\" style=\"display: block; margin: 20px\">\n      </div>\n\n2. ✨ **NEW!**: Now we support **multiprocessing** for processing the images. It will largely speed up the processing.\n    * The number of processes is set to the number of CPU cores by default.\n    * You can specify the number of processes by `--n_workers` parameter.\n3. 🧬 **CHANGE!**: We add more details in the report image to facilitate the debugging, as shown above.\n    * We add the face id in the report image.\n    * We add the effective face or skin area in the report image. In this case, the other areas are blurred.\n4. 🧬 **CHANGE!**: Now, we save the report images into different folders based on their `image_type` (color or\n   black/white) and the number of detected faces.\n    * For example, if the input image is **color** and there are **2 faces** detected, the report image will be saved\n      in `./debug/color/faces_2/` folder.\n    * If the input image is **black/white** and no face has been detected, the report image will be saved\n      in `./debug/bw/faces_0/` folder.\n    * You can easily to tune the parameters and rerun the app based on the report images in the corresponding folder.\n5. 🐛 **FIX!**: We fix the bug that the app will crash when the input image has dimensionality errors.\n    * Now, the app won't crash and will report the error message in `./result.csv`.\n\n</details>"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "MANIFEST.in",
    "content": "include README.md\ninclude LICENSE\ninclude MANIFEST.in\nrecursive-include src/stone/ui *\nrecursive-exclude * *.py[co]\nexclude .idea/*\nexclude CHANGELOG.md\nexclude _config.yml\nexclude docs/*\nexclude requirements.txt\n"
  },
  {
    "path": "README.md",
    "content": "<head>\n    <link rel=\"icon\" type=\"image/png\" href=\"https://raw.githubusercontent.com/ChenglongMa/SkinToneClassifier/main/docs/icon.svg\">\n</head>\n\n<div style=\"text-align:center;\">\n    <img src=\"https://raw.githubusercontent.com/ChenglongMa/SkinToneClassifier/main/docs/stone-logo.png\" alt=\"stone logo\">\n    <img src=\"https://raw.githubusercontent.com/ChenglongMa/SkinToneClassifier/main/docs/illustration.svg\" alt=\"model illustration\">\n</div>\n\n![PyPI - Python Version](https://img.shields.io/pypi/pyversions/skin-tone-classifier)\n[![PyPI](https://img.shields.io/pypi/v/skin-tone-classifier)](https://pypi.org/project/skin-tone-classifier/)\n[![PyPI - Downloads](https://img.shields.io/pypi/dm/skin-tone-classifier)](https://pypi.org/project/skin-tone-classifier/)\n[![PyPI Downloads](https://static.pepy.tech/badge/skin-tone-classifier)](https://pepy.tech/projects/skin-tone-classifier)\n[![GitHub release (latest by date including pre-releases)](https://img.shields.io/github/v/release/ChenglongMa/SkinToneClassifier?include_prereleases)](https://github.com/ChenglongMa/SkinToneClassifier/releases/latest)\n[![GitHub License](https://img.shields.io/github/license/ChenglongMa/SkinToneClassifier)](https://github.com/ChenglongMa/SkinToneClassifier/blob/main/LICENSE)\n[![youtube](https://img.shields.io/badge/YouTube-Skin_Tone_Classifier-FF0000?logo=youtube)](https://youtube.com/playlist?list=PLYRpHlp-9V_E5ZLhW1hbNaVjS5Zg6b6kQ&si=ezxUR7McUbZa4clT)\n[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1k-cryEZ9PInJRXWIi17ib66ufYV2Ikwe?usp=sharing)\n[![GitHub Repo stars](https://img.shields.io/github/stars/ChenglongMa/SkinToneClassifier)](https://github.com/ChenglongMa/SkinToneClassifier)\n\nAn easy-to-use library for skin tone classification.\n\nThis can be used to detect **face** or **skin area** in the specified images.\nThe detected skin tones are then classified into the specified color categories.\nThe library finally generates results to report the detected faces (if any),\ndominant skin tones and color categories.\n\nCheck out the [Changelog](https://github.com/ChenglongMa/SkinToneClassifier/blob/main/CHANGELOG.md) for the latest updates.\n\n*If you find this project helpful, please\nconsider [giving it a star](https://github.com/ChenglongMa/SkinToneClassifier)* ⭐. *It would be a great encouragement\nfor me!*\n\n---\n\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n**Table of Contents**\n\n- [Showcases](#showcases)\n  - [PERLA Palette (default)](#perla-palette-default)\n  - [YADON-OSTFELD Palette](#yadon-ostfeld-palette)\n  - [PRODER Palette](#proder-palette)\n- [Video tutorials](#video-tutorials)\n  - [Playlist](#playlist)\n  - [1. How to install Python and `stone`](#1-how-to-install-python-and-stone)\n  - [2. Use `stone` in GUI mode](#2-use-stone-in-gui-mode)\n  - [3. Use `stone` in CLI mode](#3-use-stone-in-cli-mode)\n  - [4. Use `stone` in Python scripts](#4-use-stone-in-python-scripts)\n- [Installation](#installation)\n  - [Install from pip](#install-from-pip)\n    - [Install the CLI mode only](#install-the-cli-mode-only)\n    - [Install the CLI mode and the GUI mode](#install-the-cli-mode-and-the-gui-mode)\n  - [Install from source](#install-from-source)\n- [HOW TO USE](#how-to-use)\n  - [Quick Start](#quick-start)\n    - [Use `stone` in a GUI](#use-stone-in-a-gui)\n    - [Use `stone` in command line interface (CLI)](#use-stone-in-command-line-interface-cli)\n    - [Interpretation of the table](#interpretation-of-the-table)\n  - [Detailed Usage](#detailed-usage)\n    - [Use Cases](#use-cases)\n      - [1. Process multiple images](#1-process-multiple-images)\n      - [2. Specify color palette](#2-specify-color-palette)\n      - [3. Specify category labels](#3-specify-category-labels)\n      - [4. Specify output folder](#4-specify-output-folder)\n      - [5. Store report images for debugging](#5-store-report-images-for-debugging)\n      - [6. Specify the types of the input image(s)](#6-specify-the-types-of-the-input-images)\n      - [7. Convert the `color` images to `black/white` images](#7-convert-the-color-images-to-blackwhite-images)\n      - [8. Tune parameters of face detection](#8-tune-parameters-of-face-detection)\n      - [9. Multiprocessing settings](#9-multiprocessing-settings)\n      - [10. Used as a library by importing into other projects](#10-used-as-a-library-by-importing-into-other-projects)\n      - [11. Used in a FAST API project](#11-used-in-a-fast-api-project)\n- [Citation](#citation)\n- [Contributing](#contributing)\n- [Disclaimer](#disclaimer)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n\n# Showcases\n\nThe following are some examples of the classification results using different palettes.\n\n## PERLA Palette (default)\n\n![PERLA Palette](https://raw.githubusercontent.com/ChenglongMa/SkinToneClassifier/main/docs/palette-perla.svg)\n\n![PERLA](https://raw.githubusercontent.com/ChenglongMa/SkinToneClassifier/main/docs/demo-perla.png)\n\n## YADON-OSTFELD Palette\n\n![YADON-OSTFELD Palette](https://raw.githubusercontent.com/ChenglongMa/SkinToneClassifier/main/docs/palette-yadon-ostfeld.svg)\n\n![YADON-OSTFELD](https://raw.githubusercontent.com/ChenglongMa/SkinToneClassifier/main/docs/demo-yadon-ostfeld.png)\n\n## PRODER Palette\n\n![PRODER Palette](https://raw.githubusercontent.com/ChenglongMa/SkinToneClassifier/main/docs/palette-proder.svg)\n\n![PRODER](https://raw.githubusercontent.com/ChenglongMa/SkinToneClassifier/main/docs/demo-proder.png)\n\n# Video tutorials\n\n[![youtube](https://img.shields.io/badge/YouTube-Skin_Tone_Classifier-FF0000?logo=youtube)](https://youtube.com/playlist?list=PLYRpHlp-9V_E5ZLhW1hbNaVjS5Zg6b6kQ&si=ezxUR7McUbZa4clT)\n\nPlease visit the following video tutorials if you have no programming background or are unfamiliar with how to use Python and this library 💖\n\n## Playlist\n\n[![playlist](https://img.youtube.com/vi/vu6whI0qcmU/0.jpg)](https://youtube.com/playlist?list=PLYRpHlp-9V_E5ZLhW1hbNaVjS5Zg6b6kQ&si=ezxUR7McUbZa4clT)\n\n<details markdown=\"1\">\n  <summary><i>Click here to show more.</i></summary>\n    \n## 1. How to install Python and `stone`\n\n[![YouTube Video Views](https://img.shields.io/youtube/views/vu6whI0qcmU)](https://www.youtube.com/watch?v=vu6whI0qcmU&list=PLYRpHlp-9V_E5ZLhW1hbNaVjS5Zg6b6kQ&index=1)\n\n[![installation](https://img.youtube.com/vi/vu6whI0qcmU/0.jpg)](https://www.youtube.com/watch?v=vu6whI0qcmU&list=PLYRpHlp-9V_E5ZLhW1hbNaVjS5Zg6b6kQ&index=1)\n\n## 2. Use `stone` in GUI mode\n\n[![YouTube Video Views](https://img.shields.io/youtube/views/08apMEogZgs)](https://www.youtube.com/watch?v=08apMEogZgs&list=PLYRpHlp-9V_E5ZLhW1hbNaVjS5Zg6b6kQ&index=2)\n\n[![use gui mode](https://img.youtube.com/vi/08apMEogZgs/0.jpg)](https://www.youtube.com/watch?v=08apMEogZgs&list=PLYRpHlp-9V_E5ZLhW1hbNaVjS5Zg6b6kQ&index=2)\n\n## 3. Use `stone` in CLI mode\n\n[![YouTube Video Views](https://img.shields.io/youtube/views/rqJ62DijQaw)](https://www.youtube.com/watch?v=rqJ62DijQaw&list=PLYRpHlp-9V_E5ZLhW1hbNaVjS5Zg6b6kQ&index=3)\n\n[![use cli mode](https://img.youtube.com/vi/rqJ62DijQaw/0.jpg)](https://www.youtube.com/watch?v=rqJ62DijQaw&list=PLYRpHlp-9V_E5ZLhW1hbNaVjS5Zg6b6kQ&index=3)\n\n## 4. Use `stone` in Python scripts\n\nPlease refer to this notebook [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1k-cryEZ9PInJRXWIi17ib66ufYV2Ikwe?usp=sharing) for more information.\n\n_More videos are coming soon..._\n\n</details>\n\n# Installation\n\n> [!TIP]\n> \n> Since v1.2.3, we have made the GUI mode **optional**.\n> \n\n\n## Install from pip\n\n### Install the CLI mode only\n\n```shell\npip install skin-tone-classifier --upgrade\n```\n\nIt is useful for users who want to use this library in non-GUI environments, e.g., servers or [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1k-cryEZ9PInJRXWIi17ib66ufYV2Ikwe?usp=sharing).\n\n### Install the CLI mode and the GUI mode\n\n```shell\npip install skin-tone-classifier[all] --upgrade\n```\n\nIt is useful for users who are not familiar with the command line interface and want to use the GUI mode.\n\n## Install from source\n\n```shell\ngit clone git@github.com:ChenglongMa/SkinToneClassifier.git\ncd SkinToneClassifier\npip install -e . --verbose\n```\n\n> [!TIP]\n>\n> If you encounter the following problem:\n> \n> [`ImportError: DLL load failed while importing _core: The specified module could not be found`](https://stackoverflow.com/q/52306805/8860079)\n> \n> Please download and install **Visual C++ Redistributable** at [here](https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist?view=msvc-170#visual-studio-2015-2017-2019-and-2022).\n>\n> Then this error will be gone.\n\n# HOW TO USE\n\n> [!TIP]\n>\n> You can combine the following documents, [the video tutorials above](#video-tutorials)\n> and the running examples [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1k-cryEZ9PInJRXWIi17ib66ufYV2Ikwe?usp=sharing)\n> to understand the usage of this library more intuitively.\n> \n\n## Quick Start\n\n### Use `stone` in a GUI\n\n✨ Since v1.2.0, we have provided a GUI version of `stone` for users who are not familiar with the command line\ninterface.\n\n![stone GUI](https://raw.githubusercontent.com/ChenglongMa/SkinToneClassifier/main/docs/gui.png)\n\nInstead of typing commands in the terminal, you can use the config GUI of `stone` to process the images.\n\nSteps:\n\n1. Open the terminal that can run `stone` (e.g., `PowerShell` in Windows or `Terminal` in macOS).\n2. Type `stone` (without any parameters) or `stone --gui` and press <kbd>Enter</kbd> to open the GUI.\n3. Specify the parameters in each tab.\n4. Click the `Start` button to start processing the images.\n\nHopefully, this can make it easier for you to use `stone` 🍻!\n\n> [!TIP]\n> \n> 1. It is recommended to install v1.2.3+, which supports Python 3.9+.\n> \n>    If you have installed v1.2.0, please upgrade to v1.2.3+ by running \n> \n>    `pip install skin-tone-classifier[all] --upgrade`\n>\n> 2. If you encounter the following problem:\n>    > This program needs access to the screen. Please run with a Framework\n>    > build of python, and only when you are logged in on the main display\n>    > of your Mac.\n> \n>    Please launch the GUI by running `pythonw -m stone` in the terminal.\n>    References: \n>       * [stackoverflow](https://stackoverflow.com/a/52732858/8860079)\n>       * [python-using-mac](https://docs.python.org/3/using/mac.html)\n\n### Use `stone` in command line interface (CLI)\n\nTo detect the skin tone in a portrait, e.g.,\n\n<div align=\"center\">\n   <img src=\"https://raw.githubusercontent.com/ChenglongMa/SkinToneClassifier/main/docs/demo.png\"  alt=\"Demo picture\" style=\"display: block; margin: auto\"/>\n</div>\n\nJust run:\n\n```shell\nstone -i /path/to/demo.png --debug\n```\n\nThen, you can find the processed image in `./debug/color/faces_1` folder, e.g.,\n\n<div align=\"center\">\n   <img src=\"https://raw.githubusercontent.com/ChenglongMa/SkinToneClassifier/main/docs/demo-1.png\"  alt=\"processed demo picture\" style=\"display: block; margin: auto\"/>\n</div>\n\nIn this image, from left to right you can find the following information:\n\n1. detected face with a label (*Face 1*) enclosed by a rectangle.\n2. dominant colors.\n    1. _The number of colors depends on settings (default is 2), and their sizes depend on their proportion._\n3. specified color palette and the target label is enclosed by a rectangle.\n4. you can find a summary text at the bottom.\n\nFurthermore, there will be a report file named `result.csv` which contains more detailed information, e.g.,\n\n| file     | image type | face id | dominant 1 | percent 1 | dominant 2 | percent 2 | skin tone | tone label | accuracy(0-100) |\n|----------|------------|---------|------------|-----------|------------|-----------|-----------|------------|-----------------|\n| demo.png | color      | 1       | #C99676    | 0.67      | #805341    | 0.33      | #9D7A54   | CF         | 86.27           |\n\n### Interpretation of the table\n\n1. `file`: the filename of the processed image.\n    * **NB: The filename pattern of report image is `<file>-<face id>.<extension>`**\n2. `image type`: the type of the processed image, i.e., `color` or `bw` (black/white).\n3. `face id`: the id of the detected face, which matches the reported image. `NA` means no face has been detected.\n4. `dominant n`: the `n`-th dominant color of the detected face.\n5. `percent n`: the percentage of the `n`-th dominant color, (0~1.0).\n6. `skin tone`: the skin tone category of the detected face.\n7. `tone label`: the **label** of skin tone category of the detected face.\n8. `accuracy`: the accuracy of the skin tone category of the detected face, (0~100). The larger, the better.\n\n## Detailed Usage\n\nTo see the usage and parameters, run:\n\n```shell\nstone -h (or --help)\n```\n\nDetailed usage:\n\n| Short Option | Long Option   | Definition                                                                                                                                                                                                                                                                                                                                                                        |\n|--------------|---------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| -h           | --help        | Show this help message and exit.                                                                                                                                                                                                                                                                                                                                                  |\n| -i           | --images      | Image filename(s) or URLs to process. <br>Supports multiple values separated by **space**, e.g., `a.jpg b.png`. <br>Supports directory or file name(s), e.g., `./path/to/images/ a.jpg`. <br>Supports URL(s), e.g., `https://example.com/images/pic.jpg` since v1.1.0+. <br>If you don't specify this option, the app will search all images in the current directory by default. |\n| -r           | --recursive   | Whether to search images **recursively** in the specified directory.                                                                                                                                                                                                                                                                                                              |\n| -t           | --image_type  | Specify whether the input image(s) is/are **colored** or **black/white**. <br>Valid choices are: `auto`, `color`, or `bw`. <br>Defaults to `auto`, which will be detected **automatically**.                                                                                                                                                                                      |\n| -p           | --palette     | Skin tone palette. <br>Valid choices can be `perla`, `yadon-ostfeld`, `proder`; <br>You can also input RGB **hex** values starting with `#` <br>or **RGB** values separated by **commas**, <br>e.g., `-p #373028 #422811` or `-p 255,255,255 100,100,100`.                                                                                                                        |\n| -l           | --labels      | Skin tone labels. <br>Default values are the **UPPERCASE** alphabet list leading by the image type <br>(`C` for `color`; `B` for `Black&White`), <br>e.g., `['CA', 'CB', ..., 'CZ']` or `['BA', 'BB', ..., 'BZ']`.                                                                                                                                                                |\n| -d           | --debug       | Whether to generate report images, used for debugging and verification. <br>The report images will be saved in the `./debug` directory.                                                                                                                                                                                                                                           |\n| -bw          | --black_white | Whether to convert the input to **black/white** image(s). <br>If `true`, the app will use a **black/white palette** to classify the image.                                                                                                                                                                                                                                        |\n| -o           | --output      | The path of the output file, defaults to **the current directory**.                                                                                                                                                                                                                                                                                                               |\n|              | --n_workers   | The number of workers to process the images, <br>defaults to **the number of CPUs** in the system.                                                                                                                                                                                                                                                                                |\n|              | --n_colors    | CONFIG: the number of dominant colors to be extracted, defaults to 2.                                                                                                                                                                                                                                                                                                             |\n|              | --new_width   | CONFIG: resize the images with the specified width. <br>**Negative value will be ignored**, defaults to 250.                                                                                                                                                                                                                                                                      |\n|              | --scale       | CONFIG: how much the image size is reduced at each image scale, defaults to 1.1.                                                                                                                                                                                                                                                                                                  |\n|              | --min_nbrs    | CONFIG: how many neighbors each candidate rectangle should have to retain it. <br>**Higher value results in fewer detections but with higher quality**, defaults to 5.                                                                                                                                                                                                            |\n|              | --min_size    | CONFIG: minimum possible face size. **Faces smaller than that are ignored**. <br>Valid format: `width height`, defaults to `90 90`.                                                                                                                                                                                                                                               |\n|              | --threshold   | CONFIG: what percentage of the skin area is required to identify the face, <br>defaults to 0.15.                                                                                                                                                                                                                                                                                  |\n| -v           | --version     | Show the version number and exit.                                                                                                                                                                                                                                                                                                                                                 |\n\n### Use Cases\n\n#### 1. Process multiple images\n\n1.1 Multiple filenames\n\n```shell\nstone -i (or --images) a.jpg b.png https://example.com/images/pic.jpg\n```\n\n1.2 Images in some folder(s)\n\n```shell\nstone -i ./path/to/images/\n```\n\nNB: Supported image formats: `.jpg, .gif, .png, .jpeg, .webp, .tif`.\n\nIn default (i.e., `stone` without `-i` option), the app will search images in current folder.\n\n#### 2. Specify color palette\n\n2.1 Use the built-in palettes\n\nThe built-in palettes are: `perla`, `yadon-ostfeld`, `proder` and `bw`.\n\nNB: The `bw` palette is used to classify the **black/white** images only.\n\nFor example:\n```shell\nstone -p (or --palette) perla\n```\n\nThe HEX values of each palette are:\n\n![PERLA](https://raw.githubusercontent.com/ChenglongMa/SkinToneClassifier/main/docs/palette-perla.svg)\n\n* `perla`:\n    * `#373028`, `#422811`, `#513B2E`, `#6F503C`, `#81654F`, `#9D7A54`, `#BEA07E`, `#E5C8A6`, `#E7C1B8`, `#F3DAD6`, `#FBF2F3`\n    * Citation: Rejón Piña, R. A., & Ma, C. (2021). Classification Algorithm for Skin Color (CASCo): A new tool to measure skin color in social science research.\n\n![YADON-OSTFELD](https://raw.githubusercontent.com/ChenglongMa/SkinToneClassifier/main/docs/palette-yadon-ostfeld.svg)\n\n* `yadon-ostfeld`:\n    * `#36251d`, `#48352c`, `#614539`, `#755848`, `#886958`, `#9b7966`, `#b18972`, `#c29c88`, `#d4afa3`, `#e6c6bf`\n    * Citation: Ostfeld, M. C., & Yadon, N. (2022). Skin color, power, and politics in America. Russell Sage Foundation.\n\n![PRODER](https://raw.githubusercontent.com/ChenglongMa/SkinToneClassifier/main/docs/palette-proder.svg)\n\n* `proder`:\n    * `#654d3e`, `#775741`, `#876249`, `#946c51`, `#a0765a`, `#a87f64`, `#b1886c`, `#b69279`, `#be9d86`, `#c5a691`, `#c8ac99`\n    * Citation: Proyecto sobre discriminación étnico-racial en México (PRODER). El Colegio de México. https://discriminacion.colmex.mx/encuesta-proder/\n\n![BW](https://raw.githubusercontent.com/ChenglongMa/SkinToneClassifier/main/docs/palette-bw.svg)\n\n* `bw`:\n    * `#FFFFFF`, `#F0F0F0`, `#E0E0E0`, `#D0D0D0`, `#C0C0C0`, `#B0B0B0`, `#A0A0A0`, `#909090`, `#808080`, `#707070`, `#606060`, `#505050`, `#404040`, `#303030`, `#202020`, `#101010`, `#000000`\n    * Citation: Leigh, A., & Susilo, T. (2009). Is voting skin-deep? Estimating the effect of candidate ballot photographs on election outcomes. Journal of Economic Psychology, 30(1), 61-70.\n\n2.2 Use HEX values\n\n```shell\nstone -p #373028 #422811 #513B2E\n```\n\nNB: Values start with **'#'** and are separated by **space**.\n\n2.3 Use RGB tuple values\n\n```shell\nstone -p 55,48,40 66,40,17 251,242,243\n```\n\nNB: Values split by **comma ','**, multiple values are still separated by **space**.\n\n#### 3. Specify category labels\n\nYou can assign the labels for the skin tone categories, for example:\n\n```text\n\"CA\": \"#373028\",\n\"CB\": \"#422811\",\n\"CC\": \"#513B2E\",\n...\n```\n\nTo achieve this, you can use the `-l` (or `--labels`) option:\n\n3.1 Specify the labels directly using __spaces__ as delimiters, e.g.,\n\n```shell\nstone -l A B C D E F G H\n```\n\n3.2 Specify the range of labels based on this pattern: `<start><sep><end><sep><step>`.\n\nSpecifically,\n\n* `<start>`: the **start** label, can be a letter (e.g., `A`) or a number (e.g., `1`);\n* `<end>`: the **end** label, can be a letter (e.g., `H`) or a number (e.g., `8`);\n* `<step>`: the **step** to generate the label sequence, can be a number (e.g., `2` or `-1`), **defaults to `1`**.\n* `<sep>`: the **separator** between `<start>` and `<end>`, can be one of these symbols: `-`, `,`, `~`, `:`, `;`, `_`.\n\nExamples:\n\n```shell\nstone -l A-H-1\n```\n\nwhich is equivalent to `stone -l A-H` and `stone -l A B C D E F G H`.\n\n```shell\nstone -l A-H-2\n```\n\nwhich is equivalent to `stone -l A C E G`.\n\n```shell\nstone -l 1-8\n```\n\nwhich is equivalent to `stone -l 1 2 3 4 5 6 7 8`.\n\n```shell\nstone -l 1-8-3\n```\n\nwhich is equivalent to `stone -l 1 4 7`.\n\n\n> [!IMPORTANT]\n>\n> Please make sure the number of labels is equal to the number of colors in the palette.\n\n#### 4. Specify output folder\n\nThe app puts the final report (`result.csv`) in current folder in default.\n\nTo change the output folder:\n\n```shell\nstone -o (or --output) ./path/to/output/\n```\n\nThe output folder will be created if it does not exist.\n\nIn `result.csv`, each row is showing the color information of each detected face.\nIf more than one faces are detected, there will be multiple rows for that image.\n\n#### 5. Store report images for debugging\n\n```shell\nstone -d (or --debug)\n```\n\nThis option will store the report image (like the demo portrait above) in\n`./path/to/output/debug/<image type>/faces_<n>` folder,\nwhere `<image type>` indicates if the image is `color` or `bw` (black/white);\n`<n>` is the number of faces detected in the image.\n\n**By default, to save storage space, the app does not store report images.**\n\nLike in the `result.csv` file, there will be more than one report images if 2 or more faces were detected.\n\n#### 6. Specify the types of the input image(s)\n\n6.1 The input are color images\n\n```shell\nstone -t (or --image_type) color\n```\n\n6.2 The input are black/white images\n\n```shell\nstone -t (or --image_type) bw\n```\n\n6.3 **In default**, the app will detect the image type automatically, i.e.,\n\n```shell\nstone -t (or --image_type) auto\n```\n\n#### 7. Convert the `color` images to `black/white` images\n\nand then do the classification using `bw` palette\n\n```shell\nstone -bw (or --black_white)\n```\n\nFor example:\n\n<div style=\"display: flex; justify-content: center;align-items:flex-end;\">\n    <div style=\"text-align: center;flex:1; margin:10px;\">\n        <img src=\"https://raw.githubusercontent.com/ChenglongMa/SkinToneClassifier/main/docs/demo.png\"  alt=\"Demo picture\" />\n        <p>1. Input</p>\n    </div>\n    <div style=\"text-align: center;flex:1; margin:10px;\">\n        <img src=\"https://raw.githubusercontent.com/ChenglongMa/SkinToneClassifier/main/docs/demo_bw.png\"  alt=\"Black/white Demo picture\" />\n        <p>2. Convert to black/white image</p>\n    </div>\n    <div style=\"text-align: center;flex:1; margin:10px;\">\n        <img src=\"https://raw.githubusercontent.com/ChenglongMa/SkinToneClassifier/main/docs/demo_bw-1.png\"  alt=\"Report image\" />\n        <p>3. The final report image</p>\n    </div>\n</div>\n\nNB: we did not do the opposite, i.e., convert `black/white` images to `color` images\nbecause the current AI models cannot accurately \"guess\" the color of the skin from a `black/white` image.\nIt can further bias the analysis results.\n\n#### 8. Tune parameters of face detection\n\nThe rest parameters of `CONFIG` are used to detect face.\nPlease refer to https://stackoverflow.com/a/20805153/8860079 for detailed information.\n\n#### 9. Multiprocessing settings\n\n```shell\nstone --n_workers <Any Positive Integer>\n```\n\nUse `--n_workers` to specify the number of workers to process images in parallel, defaults to the number of CPUs in your\nsystem.\n\n#### 10. Used as a library by importing into other projects\n\nYou can refer to [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1k-cryEZ9PInJRXWIi17ib66ufYV2Ikwe?usp=sharing) or the following code snippet:\n\n```python\nimport stone\nfrom json import dumps\n\n# process the image\nresult = stone.process(image_path, image_type, palette, *other_args, return_report_image=True)\n# show the report image\nreport_images = result.pop(\"report_images\")  # obtain and remove the report image from the `result`\nface_id = 1\nstone.show(report_images[face_id])\n\n# convert the result to json\nresult_json = dumps(result)\n```\n\n`stone.process` is the main function to process the image.\nIt has the same parameters as the command line version.\n\nIt will return a `dict`, which contains the process result and report image(s) (if required,\ni.e., `return_report_image=True`).\n\nYou can further use `stone.show` to show the report image(s).\nAnd convert the result to `json` format.\n\nThe `result_json` will be like:\n\n```json\n{\n  \"basename\": \"demo\",\n  \"extension\": \".png\",\n  \"image_type\": \"color\",\n  \"faces\": [\n    {\n      \"face_id\": 1,\n      \"dominant_colors\": [\n        {\n          \"color\": \"#C99676\",\n          \"percent\": \"0.67\"\n        },\n        {\n          \"color\": \"#805341\",\n          \"percent\": \"0.33\"\n        }\n      ],\n      \"skin_tone\": \"#9D7A54\",\n      \"tone_label\": \"CF\",\n      \"accuracy\": 86.27\n    }\n  ]\n}\n```\n\n#### 11. Used in a FAST API project\n\n`stone` can be used in a FAST API project to classify the skin tone of the uploaded image(s) via `POST` method.\n\nPlease refer to the following code snippet:\n\n```python\n# Description: This is a simple FastAPI server that receives an image file \n# and processes it using the skin-tone-classifier library.\n\n# requirements.txt:\n#     fastapi\n#     uvicorn\n#     skin-tone-classifier\n#     python-multipart\n\n# Run the server:\n#     uvicorn main:app --reload\n\nfrom typing import Literal\n\nimport stone\nfrom fastapi import FastAPI, UploadFile, HTTPException\nfrom fastapi.responses import JSONResponse\n\napp = FastAPI()\n\n\n@app.post(\"/stone\")\nasync def process_image(\n        image_file: UploadFile,\n        image_type: Literal[\"auto\", \"color\", \"bw\"] = \"auto\",\n        tone_palette: list = None,\n        tone_labels: list = None,\n        # other parameters...\n):\n    image_data = await image_file.read()\n    temp_file_path = \"/tmp/temp_image.jpg\"\n    with open(temp_file_path, \"wb\") as temp_file:\n        temp_file.write(image_data)\n    try:\n        result = stone.process(\n            temp_file_path,\n            image_type=image_type,\n            tone_palette=tone_palette,\n            tone_labels=tone_labels,\n            # other parameters...\n        )\n        result = JSONResponse(content=result)\n    except Exception as e:\n        raise HTTPException(status_code=500, detail=str(e))\n    return result\n```\n\nTo run the demo, please follow these steps:\n\n1. Install required packages:\n    * skin-tone-classifier\n    * [fastapi](https://fastapi.tiangolo.com/)\n    * [uvicorn](https://www.uvicorn.org/)\n    * [python-multipart](https://pypi.org/project/python-multipart/)\n2. Run the server:\n   `uvicorn main:app --reload`\n3. You can refine the implementation according to your project requirements. \n4. Finally, you can use [Postman](https://www.postman.com/) or other HTTP Clients to test the API.\n\n# Citation\n\nIf you are interested in our work, please cite:\n\n```bibtex\n@article{https://doi.org/10.1111/ssqu.13242,\n    author = {Rej\\'{o}n Pi\\tilde{n}a, Ren\\'{e} Alejandro and Ma, Chenglong},\n    title = {Classification Algorithm for Skin Color (CASCo): A new tool to measure skin color in social science research},\n    journal = {Social Science Quarterly},\n    volume = {n/a},\n    number = {n/a},\n    pages = {},\n    keywords = {colorism, measurement, photo elicitation, racism, skin color, spectrometers},\n    doi = {https://doi.org/10.1111/ssqu.13242},\n    url = {https://onlinelibrary.wiley.com/doi/abs/10.1111/ssqu.13242},\n    eprint = {https://onlinelibrary.wiley.com/doi/pdf/10.1111/ssqu.13242},\n    abstract = {Abstract Objective A growing body of literature reveals that skin color has significant effects on people's income, health, education, and employment. However, the ways in which skin color has been measured in empirical research have been criticized for being inaccurate, if not subjective and biased. Objective Introduce an objective, automatic, accessible and customizable Classification Algorithm for Skin Color (CASCo). Methods We review the methods traditionally used to measure skin color (verbal scales, visual aids or color palettes, photo elicitation, spectrometers and image-based algorithms), noting their shortcomings. We highlight the need for a different tool to measure skin color Results We present CASCo, a (social researcher-friendly) Python library that uses face detection, skin segmentation and k-means clustering algorithms to determine the skin tone category of portraits. Conclusion After assessing the merits and shortcomings of all the methods available, we argue CASCo is well equipped to overcome most challenges and objections posed against its alternatives. While acknowledging its limitations, we contend that CASCo should complement researchers. toolkit in this area.}\n}\n```\n\n# Contributing\n\n👋 Welcome to **SkinToneClassifier**! We're excited to have your contributions. Here's how you can get involved:\n\n1. 💡 **Discuss New Ideas**: Have a creative idea or suggestion? Start a discussion in\n   the [Discussions](https://github.com/ChenglongMa/SkinToneClassifier/discussions) tab to share your thoughts and\n   gather feedback from the community.\n\n2. ❓ **Ask Questions**: Got questions or need clarification on something in the repository? Feel free to open\n   an [Issue](https://github.com/ChenglongMa/SkinToneClassifier/issues) labeled as a \"question\" or participate\n   in [Discussions](https://github.com/ChenglongMa/SkinToneClassifier/discussions).\n\n3. 🐛 **Issue a Bug**: If you've identified a bug or an issue with the code, please open a\n   new [Issue](https://github.com/ChenglongMa/SkinToneClassifier/issues) with a clear description of the problem, steps\n   to reproduce it, and your environment details.\n\n4. ✨ **Introduce New Features**: Want to add a new feature or enhancement to the project? Fork the repository, create a\n   new branch, and submit a [Pull Request](https://github.com/ChenglongMa/SkinToneClassifier/pulls) with your changes.\n   Make sure to follow our contribution guidelines.\n\n5. 💖 **Funding**: If you'd like to financially support the project, you can do so\n   by [sponsoring the repository on GitHub](https://github.com/sponsors/ChenglongMa). Your contributions help us\n   maintain and improve the project.\n\n# Disclaimer\n\nThe images used in this project are from [Flickr-Faces-HQ Dataset (FFHQ)](https://github.com/NVlabs/ffhq-dataset), \nwhich is licensed under the [Creative Commons BY-NC-SA 4.0 license](https://github.com/NVlabs/ffhq-dataset/blob/master/LICENSE.txt).\n\nThank you for considering contributing to **SkinToneClassifier**. \nWe value your input and look forward to collaborating with you!\n"
  },
  {
    "path": "_config.yml",
    "content": "theme: jekyll-theme-cayman\ntitle: Skin Tone Classifier\ndescription: An easy-to-use library for skin tone classification."
  },
  {
    "path": "pyproject.toml",
    "content": "[project]\n# This is the name of your project. The first time you publish this\n# package, this name will be registered for you. It will determine how\n# users can install this project, e.g.:\n#\n# $ pip install sampleproject\n#\n# And where it will live on PyPI: https://pypi.org/project/sampleproject/\n#\n# There are some restrictions on what makes a valid project name\n# specification here:\n# https://packaging.python.org/specifications/core-metadata/#name\nname = \"skin-tone-classifier\"  # Required\n\ndynamic = [\"version\"]\n# https://setuptools.pypa.io/en/latest/userguide/pyproject_config.html#dynamic-metadata\n# \"dependencies\", \"optional-dependencies\" are BETA features currently\n#dynamic = [\"version\", \"dependencies\", \"optional-dependencies\"]\n\n# Versions should comply with PEP 440:\n# https://www.python.org/dev/peps/pep-0440/\n#\n# For a discussion on single-sourcing the version, see\n# https://packaging.python.org/guides/single-sourcing-package-version/\n#https://packaging.python.org/en/latest/specifications/version-specifiers/#version-specifiers\n#version = \"1.2.3\"  # Required\n\n# This is a one-line description or tagline of what your project does. This\n# corresponds to the \"Summary\" metadata field:\n# https://packaging.python.org/specifications/core-metadata/#summary\ndescription = \"An easy-to-use library for skin tone classification\"  # Optional\n\n# This is an optional longer description of your project that represents\n# the body of text which users will see when they visit PyPI.\n#\n# Often, this is the same as your README, so you can just read it in from\n# that file directly (as we have already done above)\n#\n# This field corresponds to the \"Description\" metadata field:\n# https://packaging.python.org/specifications/core-metadata/#description-optional\nreadme = \"README.md\" # Optional\n\n# Specify which Python versions you support. In contrast to the\n# 'Programming Language' classifiers above, 'pip install' will check this\n# and refuse to install the project if the version does not match. See\n# https://packaging.python.org/guides/distributing-packages-using-setuptools/#python-requires\nrequires-python = \">=3.9\"\n\n# This is either text indicating the license for the distribution, or a file\n# that contains the license\n# https://packaging.python.org/en/latest/specifications/core-metadata/#license\n#license = { file = \"LICENSE\" }\n\n# This field adds keywords for your project which will appear on the\n# project page. What does your project relate to?\n#\n# Note that this is a list of additional keywords, separated\n# by commas, to be used to assist searching for the distribution in a\n# larger catalog.\nkeywords = [\"skin tone\", \"image recognition\", \"face detection\", \"skin detection\", \"image segmentation\"]  # Optional\n\n# This should be your name or the name of the organization who originally\n# authored the project, and a valid email address corresponding to the name\n# listed.\nauthors = [\n    { name = \"Chenglong Ma\", email = \"chenglong.m@outlook.com\" } # Optional\n]\n\n# This should be your name or the names of the organization who currently\n# maintains the project, and a valid email address corresponding to the name\n# listed.\nmaintainers = [\n    { name = \"Chenglong Ma\", email = \"chenglong.m@outlook.com\" } # Optional\n]\n\n# Classifiers help users find your project by categorizing it.\n#\n# For a list of valid classifiers, see https://pypi.org/classifiers/\nclassifiers = [# Optional\n    \"Development Status :: 5 - Production/Stable\",\n    \"Intended Audience :: End Users/Desktop\",\n    \"Intended Audience :: Information Technology\",\n    \"Intended Audience :: Science/Research\",\n    \"Programming Language :: Python :: 3.9\",\n    \"Programming Language :: Python :: 3.10\",\n    \"Programming Language :: Python :: 3.11\",\n    \"Programming Language :: Python :: 3.12\",\n    \"Programming Language :: Python :: 3.13\",\n    \"License :: OSI Approved :: GNU General Public License v3 (GPLv3)\",\n    \"Operating System :: OS Independent\",\n    \"Topic :: Scientific/Engineering :: Image Recognition\",\n    \"Topic :: Scientific/Engineering :: Image Processing\",\n    \"Topic :: Scientific/Engineering :: Artificial Intelligence\",\n    \"Topic :: Scientific/Engineering :: Information Analysis\",\n    \"Topic :: Scientific/Engineering :: Visualization\",\n    \"Topic :: Sociology\",\n    \"Topic :: Multimedia :: Graphics\",\n    \"Topic :: Software Development :: Libraries :: Python Modules\",\n    \"Topic :: Terminals\",\n    \"Environment :: Console\",\n    \"Environment :: Web Environment\",\n    \"Environment :: Win32 (MS Windows)\",\n    \"Environment :: MacOS X\",\n    \"Environment :: Other Environment\",\n]\n\n# This field lists other packages that your project depends on to run.\n# Any package you put here will be installed by pip when your project is\n# installed, so they must be valid existing projects.\n#\n# For an analysis of this field vs pip's requirements files see:\n# https://packaging.python.org/discussions/install-requires-vs-requirements/\ndependencies = [# Optional\n    \"opencv-python>=4.9.0.80\",\n    \"numpy>=1.21.5\",\n    \"colormath>=3.0.0\",\n    \"tqdm>=4.64.0\",\n    \"colorama>=0.4.6\",\n    \"packaging>=23.1\",\n    \"requests>=2.31.0\",\n]\n\n# List additional groups of dependencies here (e.g. development\n# dependencies). Users will be able to install these using the \"extras\"\n# syntax, for example:\n#\n#   $ pip install sampleproject[dev]\n#\n# Similar to `dependencies` above, these must be valid existing\n# projects.\n[project.optional-dependencies] # Optional\nall = [\n    \"gooey>=1.0.8.1\",\n    \"re-wx==0.0.10\",\n    # https://github.com/chriskiehl/Gooey/issues/887#issuecomment-1680192972\n    \"colored==1.4.4\",\n]\n\n# List URLs that are relevant to your project\n#\n# This field corresponds to the \"Project-URL\" and \"Home-Page\" metadata fields:\n# https://packaging.python.org/specifications/core-metadata/#project-url-multiple-use\n# https://packaging.python.org/specifications/core-metadata/#home-page-optional\n#\n# Examples listed include a pattern for specifying where the package tracks\n# issues, where the source is hosted, where to say thanks to the package\n# maintainers, and where to support the project financially. The key is\n# what's used to render the link text on PyPI.\n[project.urls]  # Optional\n\"Homepage\" = \"https://chenglongma.com/SkinToneClassifier/\"\n\"Bug Reports\" = \"https://github.com/ChenglongMa/SkinToneClassifier/issues\"\n\"Funding\" = \"https://github.com/sponsors/ChenglongMa\"\n\"Say Thanks!\" = \"https://saythanks.io/to/ChenglongMa\"\n\"Repository\" = \"https://github.com/ChenglongMa/SkinToneClassifier/\"\nChangelog = \"https://github.com/ChenglongMa/SkinToneClassifier/blob/main/CHANGELOG.md\"\n\n# The following would provide a command line executable called `sample`\n# which executes the function `main` from this package when invoked.\n[project.scripts]  # Optional\nstone = \"stone.__main__:main\"\n\n[project.gui-scripts]\nstone-gui = \"stone.__main__:main\"\n\n# This is configuration specific to the `setuptools` build backend.\n# If you are using a different build backend, you will need to change this.\n[tool.setuptools]\n# If there are data files included in your packages that need to be\n# installed, specify them here.\npackage-dir = { \"\" = \"src\" }\nlicense-files = [\"LICENSE\"]\n\n[tool.setuptools.dynamic]\nversion = { attr = \"stone.package.__version__\" }\n\n[build-system]\n# These are the assumed default build requirements from pip:\n# https://pip.pypa.io/en/stable/reference/pip/#pep-517-and-518-support\nrequires = [\"setuptools>=66.1.0\", \"wheel\"]\nbuild-backend = \"setuptools.build_meta\"\n"
  },
  {
    "path": "requirements.txt",
    "content": "opencv-python~=4.10.0.84\nnumpy~=2.2.1\ncolormath~=3.0.0\ntqdm~=4.67.1\nsetuptools>=65.6.3\ncolorama>=0.4.6\npackaging~=24.2\nrequests~=2.32.3\n# For GUI\ngooey~=1.0.8.1\n# https://github.com/chriskiehl/Gooey/issues/887#issuecomment-1680192972\ncolored==1.4.4\nre-wx==0.0.10"
  },
  {
    "path": "src/stone/__init__.py",
    "content": "import numpy as np\nfrom stone.api import process\nfrom stone.image import DEFAULT_TONE_PALETTE, show\nfrom stone.utils import __version__, check_version\n\nsetattr(np, \"asscalar\", lambda x: np.asarray(x).item())\n\n__all__ = [\"process\", \"DEFAULT_TONE_PALETTE\", \"show\", \"__version__\"]\n\ncheck_version()\n"
  },
  {
    "path": "src/stone/__main__.py",
    "content": "import functools\nimport logging\nimport os\nimport shutil\nimport sys\nimport threading\nfrom datetime import datetime\nfrom multiprocessing import freeze_support, cpu_count, Pool\nfrom typing import List\n\nimport cv2\nimport numpy as np\nfrom tqdm import tqdm\nfrom tqdm.contrib.logging import logging_redirect_tqdm\n\nfrom stone.api import process\nfrom stone.package import (\n    __app_name__,\n    __version__,\n    __description__,\n    __copyright__,\n    __url__,\n    __author__,\n    __license__,\n    __code__,\n    __issues__,\n    __package_name__,\n)\nfrom stone.utils import (\n    build_arguments,\n    build_image_paths,\n    is_windows,\n    ArgumentError,\n    is_debugging,\n    resolve_labels,\n)\n\nLOG = logging.getLogger(__name__)\nlock = threading.Lock()\n\nuse_cli = len(sys.argv) > 1 and \"--gui\" not in sys.argv\n\n\ndef process_in_main(\n    filename_or_url,\n    image_type,\n    tone_palette,\n    tone_labels,\n    convert_to_black_white,\n    n_dominant_colors=2,\n    new_width=250,\n    scale=1.1,\n    min_nbrs=5,\n    min_size=(90, 90),\n    threshold=0.3,\n    return_report_image=False,\n):\n    \"\"\"\n    This is a wrapper function that calls process() in the main process to avoid pickling error.\n    :param filename_or_url:\n    :param image_type:\n    :param tone_palette:\n    :param tone_labels:\n    :param convert_to_black_white:\n    :param n_dominant_colors:\n    :param new_width:\n    :param scale:\n    :param min_nbrs:\n    :param min_size:\n    :param threshold:\n    :param return_report_image:\n    :return:\n    \"\"\"\n    try:\n        return process(\n            filename_or_url,\n            image_type=image_type,\n            tone_palette=tone_palette,\n            tone_labels=tone_labels,\n            convert_to_black_white=convert_to_black_white,\n            n_dominant_colors=n_dominant_colors,\n            new_width=new_width,\n            scale=scale,\n            min_nbrs=min_nbrs,\n            min_size=min_size,\n            threshold=threshold,\n            return_report_image=return_report_image,\n        )\n    except ArgumentError as e:\n        # Abort the app if any argument error occurs\n        raise e\n    except Exception as e:\n        msg = f\"Error processing image {filename_or_url}: {str(e)}\"\n        LOG.error(msg)\n        return {\n            \"filename\": filename_or_url,\n            \"message\": msg,\n        }\n\n\ndef main():\n    args = build_arguments()\n    # Setup logger\n    now = datetime.now()\n    output_dir = args.output\n    log_dir = os.path.join(output_dir, \"./log\")\n    os.makedirs(log_dir, exist_ok=True)\n\n    logging.basicConfig(\n        filename=now.strftime(f\"{log_dir}/log-%y%m%d%H%M.log\"),\n        level=logging.INFO,\n        format=\"[%(asctime)s] {%(filename)s:%(lineno)4d} %(levelname)s - %(message)s\",\n        datefmt=\"%H:%M:%S\",\n    )\n\n    image_paths = build_image_paths(args.images, args.recursive)\n\n    debug: bool = args.debug\n    to_bw: bool = args.black_white\n\n    specified_palette: List[str] = args.palette\n\n    specified_tone_labels = resolve_labels(args.labels)\n\n    new_width = args.new_width\n    n_dominant_colors = args.n_colors\n    min_size = args.min_size[:2]\n    scale = args.scale\n    min_nbrs = args.min_nbrs\n\n    os.makedirs(output_dir, exist_ok=True)\n    result_filename = os.path.join(output_dir, \"./result.csv\")\n    image_type_setting = args.image_type\n    threshold = args.threshold\n\n    def write_to_csv(row: list):\n        with lock:\n            with open(result_filename, \"a\", newline=\"\", encoding=\"UTF8\") as f:\n                f.write(\",\".join(map(str, row)) + \"\\n\")\n\n    num_workers = cpu_count() if args.n_workers == 0 else args.n_workers\n\n    pool = Pool(processes=num_workers)\n\n    # Backup result.csv if exists\n    if os.path.exists(result_filename):\n        renamed_file = os.path.join(output_dir, now.strftime(\"./result_bak_%y%m%d%H%M.csv\"))\n        shutil.move(result_filename, renamed_file)\n    header = (\n        \"file,image type,face id,\"\n        + \",\".join([f\"dominant {i + 1},percent {i + 1}\" for i in range(n_dominant_colors)])\n        + \",skin tone,tone label,accuracy(0-100)\"\n    )\n    write_to_csv(header.split(\",\"))\n\n    # Start\n    process_wrapper = functools.partial(\n        process if is_debugging() else process_in_main,\n        image_type=image_type_setting,\n        tone_palette=specified_palette,\n        tone_labels=specified_tone_labels,\n        convert_to_black_white=to_bw,\n        n_dominant_colors=n_dominant_colors,\n        new_width=new_width,\n        scale=scale,\n        min_nbrs=min_nbrs,\n        min_size=min_size,\n        threshold=threshold,\n        return_report_image=debug,\n    )\n    print(\"The program is processing your images...\")\n    print(\"Please wait for the program to finish.\")\n    with logging_redirect_tqdm():\n        with tqdm(image_paths, desc=\"Processing images\", unit=\"images\") as pbar:\n            for result in pool.imap(process_wrapper, image_paths):\n                if \"message\" in result:\n                    write_to_csv([result[\"filename\"], result[\"message\"]])\n                    pbar.update()\n                    continue\n\n                basename = result[\"basename\"]\n                extension = result[\"extension\"]\n                image_type = result[\"image_type\"]\n                faces = result[\"faces\"]\n                report_images = result[\"report_images\"]\n\n                pbar.set_description(f\"Processing {basename}\")\n                n_faces = len(faces)\n\n                for face_record in faces:\n                    face_id = face_record[\"face_id\"]\n                    if face_id == \"NA\":\n                        n_faces = 0  # Did not detect any faces\n                    dominant_colors = [[item[\"color\"], item[\"percent\"]] for item in face_record[\"dominant_colors\"]]\n                    record = (\n                        [f\"{basename}{extension}\", image_type, face_id]\n                        + np.hstack(dominant_colors).tolist()\n                        + [face_record[\"skin_tone\"], face_record[\"tone_label\"], face_record[\"accuracy\"]]\n                    )\n\n                    write_to_csv(record)\n                    pbar.set_postfix(\n                        {\n                            \"Image Type\": image_type,\n                            \"#Faces\": n_faces,\n                            \"Face ID\": face_id,\n                            \"Skin Tone\": face_record[\"skin_tone\"],\n                            \"Label\": face_record[\"tone_label\"],\n                            \"Accuracy\": face_record[\"accuracy\"],\n                        }\n                    )\n                if debug:\n                    debug_dir = os.path.join(output_dir, f\"./debug/{image_type}/faces_{n_faces}\")\n                    os.makedirs(debug_dir, exist_ok=True)\n                    for face_id, report_image in report_images.items():\n                        image_name = f\"{basename}-{face_id}\"\n                        report_filename = os.path.join(debug_dir, f\"{image_name}{extension}\")\n                        with lock:\n                            cv2.imwrite(report_filename, report_image)\n                pbar.update()\n    pool.close()\n    pool.join()\n\n\nsys.argv.remove(\"--gui\") if \"--gui\" in sys.argv else None\nif not use_cli and \"--ignore-gooey\" not in sys.argv:\n    try:\n        from gooey import Gooey\n    except ImportError:\n        # If gooey is not installed, use a dummy decorator\n        from stone.utils import Gooey\n        from colorama import just_fix_windows_console, Fore\n\n        just_fix_windows_console()\n        print(\n            Fore.YELLOW + f\"You are using a CLI version of {__package_name__}.\\n\"\n                          f\"Please install the GUI version with the following command:\\n\",\n            Fore.GREEN + f\"pip install {__package_name__}[all] --upgrade\\n\" + Fore.RESET,\n        )\n        sys.exit(0)\n\n    from importlib.resources import files\n\n    main = Gooey(\n        show_preview_warning=False,\n        advanced=True,  # fixme: `False` is not working\n        dump_build_config=False,  # fixme: `True` is not working, as the path cannot be resolved correctly\n        target=\"stone\",\n        suppress_gooey_flag=True,\n        program_name=f\"{__app_name__} v{__version__}\",\n        required_cols=1,\n        optional_cols=1,\n        image_dir=str(files(\"stone.ui\")),\n        tabbed_groups=True,\n        navigation=\"Tabbed\",\n        richtext_controls=True,\n        use_cmd_args=True,\n        menu=[\n            {\n                \"name\": \"Help\",\n                \"items\": [\n                    {\n                        \"type\": \"AboutDialog\",\n                        \"menuTitle\": \"About\",\n                        \"name\": __app_name__,\n                        \"description\": __description__,\n                        \"version\": __version__,\n                        \"copyright\": __copyright__,\n                        \"website\": __url__,\n                        \"developer\": __author__,\n                        \"license\": __license__,\n                    },\n                    {\"type\": \"Link\", \"menuTitle\": \"Documentation\", \"url\": __code__},\n                    {\"type\": \"Link\", \"menuTitle\": \"Report Bugs\", \"url\": __issues__},\n                ],\n            },\n        ],\n    )(main)\n\nif __name__ == \"__main__\":\n    if is_windows():\n        freeze_support()\n    main()\n"
  },
  {
    "path": "src/stone/api.py",
    "content": "import logging\nfrom pathlib import Path\nfrom typing import Union, Literal, List\n\nimport cv2\n\nfrom stone.image import (\n    load_image,\n    is_black_white,\n    build_full_palette,\n    process_image,\n    normalize_palette,\n    default_tone_labels,\n)\nfrom stone.utils import ArgumentError\n\nLOG = logging.getLogger(__name__)\n\n\ndef process(\n    filename_or_url: Union[str, Path],\n    image_type: Literal[\"auto\", \"color\", \"bw\"] = \"auto\",\n    tone_palette: Union[List[str], Literal[\"perla\", \"yadon-ostfeld\", \"proder\", \"bw\"]] = \"perla\",\n    tone_labels: List[str] = None,\n    convert_to_black_white: bool = False,\n    n_dominant_colors=2,\n    new_width=250,\n    scale=1.1,\n    min_nbrs=5,\n    min_size=(90, 90),\n    threshold=0.15,\n    return_report_image=False,\n):\n    \"\"\"\n    Process the image and return the result.\n    :param filename_or_url: The filename (in local devices) or URL (in Internet) of the image.\n    :param image_type: Specify whether the input image(s) is/are colored or black/white.\n           Valid choices are: \"auto\", \"color\" or \"bw\", Defaults to \"auto\", which will be detected automatically.\n    :param tone_palette: Skin tone palette; Valid choices can be `perla`, `yadon-ostfeld`, `proder`;\n           You can also input RGB hex value leading by \"#\" or RGB values separated by comma(,).\n           E.g., ['#373028', '#422811'] or ['255,255,255', '100,100,100']\n    :param tone_labels: Skin tone labels; default values are the uppercase alphabet list leading by the image type\n           ('C' for 'color'; 'B' for 'Black&White'), e.g., ['CA', 'CB', ..., 'CZ'] or ['BA', 'BB', ..., 'BZ'].\n    :param convert_to_black_white: Whether to convert the image to black/white before processing. Defaults to False.\n    :param n_dominant_colors: Number of dominant colors to be extracted from the image. Defaults to 2.\n    :param new_width: Resize the images with the specified width. Negative value will be ignored, defaults to 250.\n    :param scale: How much the image size is reduced at each image scale. Defaults to 1.1.\n    :param min_nbrs: How many neighbors each candidate rectangle should have to retain it.\n           Higher value results in less detection but with higher quality, defaults to 5.\n    :param min_size: Minimum possible face size. Faces smaller than that are ignored, defaults to (90, 90).\n    :param threshold: What percentage of the skin area is required to identify the face, defaults to 0.15.\n    :param return_report_image: Whether to return the report image(s) in the result. Defaults to False.\n    :return:\n    \"\"\"\n    image, basename, extension = load_image(filename_or_url, flags=cv2.IMREAD_COLOR)\n    if image is None:\n        msg = f\"{basename}{extension} is not found or is not a valid image.\"\n        LOG.error(msg)\n        return {\n            \"filename\": basename,\n            \"message\": msg,\n        }\n\n    is_bw = is_black_white(image)\n    decoded_image_type = image_type\n    if image_type == \"auto\":\n        decoded_image_type = \"bw\" if convert_to_black_white or is_bw else \"color\"\n    else:\n        is_bw = image_type == \"bw\"\n\n    if not tone_palette:\n        tone_palette = \"bw\" if decoded_image_type == \"bw\" else \"perla\"\n    if len(tone_palette) == 1:\n        tone_palette = tone_palette[0]\n\n    default_tone_palette = build_full_palette()\n    if isinstance(tone_palette, str):\n        tone_palette = tone_palette.lower()\n        if tone_palette not in default_tone_palette:\n            raise ArgumentError(f\"Invalid `tone_palette`: {tone_palette}, valid choices are: {default_tone_palette.keys()}\")\n        skin_tone_palette = default_tone_palette[tone_palette]\n    else:\n        skin_tone_palette = normalize_palette(tone_palette)\n\n    skin_tone_labels = tone_labels or default_tone_labels(skin_tone_palette, \"C\" if decoded_image_type == \"color\" else \"B\")\n    if len(skin_tone_palette) != len(skin_tone_labels):\n        raise ArgumentError(\"Argument -p/--palette and -l/--labels must have the same length.\")\n\n    records, report_images = process_image(\n        image,\n        is_bw,\n        convert_to_black_white,\n        skin_tone_palette,\n        skin_tone_labels,\n        new_width=new_width,\n        n_dominant_colors=n_dominant_colors,\n        scaleFactor=scale,\n        minNeighbors=min_nbrs,\n        minSize=min_size,\n        threshold=threshold,\n        verbose=return_report_image,\n    )\n    return {\n        \"basename\": basename,\n        \"extension\": extension,\n        \"image_type\": decoded_image_type,\n        \"faces\": records,\n        \"report_images\": report_images,\n    }\n"
  },
  {
    "path": "src/stone/image.py",
    "content": "import functools\nimport logging\nimport math\nimport re\nimport urllib.error\nfrom pathlib import Path\nfrom urllib.request import urlopen\n\nimport cv2\nimport numpy as np\nfrom colormath.color_conversions import convert_color\nfrom colormath.color_diff import delta_e_cie2000\nfrom colormath.color_objects import sRGBColor, LabColor\n\nfrom stone.utils import is_url, extract_filename_and_extension, alphabet_id, ArgumentError\n\nLOG = logging.getLogger(__name__)\n\nDEFAULT_TONE_PALETTE = {\n    # Default skin tone palette\n    \"perla\": [\n        \"#373028\",\n        \"#422811\",\n        \"#513b2e\",\n        \"#6f503c\",\n        \"#81654f\",\n        \"#9d7a54\",\n        \"#bea07e\",\n        \"#e5c8a6\",\n        \"#e7c1b8\",\n        \"#f3dad6\",\n        \"#fbf2f3\",\n    ],\n    # Refer to this paper:\n    # Monk, Ellis. \"Monk Skin Tone Scale,\" 2019. https://skintone.google.\n    \"monk\": [\n        \"#f6ede4\",\n        \"#f3e7db\",\n        \"#f7ead0\",\n        \"#eadaba\",\n        \"#d7bd96\",\n        \"#a07e56\",\n        \"#825c43\",\n        \"#604134\",\n        \"#3a312a\",\n        \"#292420\"\n    ],\n    # Refer to this paper:\n    # Ostfeld, M. C., & Yadon, N. (2022). Skin color, power, and politics in America. Russell Sage Foundation.\n    \"yadon-ostfeld\": [\n        \"#36251d\",\n        \"#48352c\",\n        \"#614539\",\n        \"#755848\",\n        \"#886958\",\n        \"#9b7966\",\n        \"#b18972\",\n        \"#c29c88\",\n        \"#d4afa3\",\n        \"#e6c6bf\",\n    ],\n    # Refer to this paper:\n    # Proyecto sobre discriminación étnico-racial en México (PRODER). El Colegio de México. https://discriminacion.colmex.mx/encuesta-proder/\n    \"proder\": [\n        \"#654d3e\",\n        \"#775741\",\n        \"#876249\",\n        \"#946c51\",\n        \"#a0765a\",\n        \"#a87f64\",\n        \"#b1886c\",\n        \"#b69279\",\n        \"#be9d86\",\n        \"#c5a691\",\n        \"#c8ac99\",\n    ],\n    # Refer to this paper:\n    # Leigh, A., & Susilo, T. (2009). Is voting skin-deep? Estimating the effect of candidate ballot photographs on election outcomes.\n    # Journal of Economic Psychology, 30(1), 61-70.\n    \"bw\": [\n        \"#FFFFFF\",\n        \"#F0F0F0\",\n        \"#E0E0E0\",\n        \"#D0D0D0\",\n        \"#C0C0C0\",\n        \"#B0B0B0\",\n        \"#A0A0A0\",\n        \"#909090\",\n        \"#808080\",\n        \"#707070\",\n        \"#606060\",\n        \"#505050\",\n        \"#404040\",\n        \"#303030\",\n        \"#202020\",\n        \"#101010\",\n        \"#000000\",\n    ],\n}\n\nTONE_ALIAS = {\n    \"monk\": [\"mst\", \"google\"],\n    \"yadon-ostfeld\": [\"yo\", \"ostfeld\", \"yadon\"],\n    \"bw\": [\"black-white\"],\n}\n\ndef build_full_palette():\n    return {alias: palette for name, palette in DEFAULT_TONE_PALETTE.items() for alias in [name] + TONE_ALIAS.get(name, [])}\n\ndef default_tone_labels(tone_palette, prefix:str=\"\"):\n    prefix = prefix or \"\"\n    return [f\"{prefix}{alphabet_id(i)}\" for i in range(len(tone_palette))]\n\n@functools.lru_cache(maxsize=128)  # Python 3.2+\ndef normalize_color(color):\n    hex_color_pattern = re.compile(r\"^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$\")\n    decimal_color_pattern = re.compile(\n        r\"^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\"\n        r\",\\s*(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\"\n        r\",\\s*(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$\"\n    )\n    if decimal_color_pattern.match(color):\n        r, g, b = map(int, color.split(\",\"))\n        color = \"#{:02X}{:02X}{:02X}\".format(r, g, b)\n        return color\n    if hex_color_pattern.match(color):\n        return color.upper()\n    raise ArgumentError(f\"Invalid color code: {color}\")\n\n\n# @functools.lru_cache(maxsize=128)  # Python 3.2+\ndef normalize_palette(palette):\n    return [normalize_color(color) for color in palette]\n\n\ndef load_image(filename_or_url, flags=cv2.IMREAD_COLOR):\n    if isinstance(filename_or_url, str):\n        if is_url(filename_or_url):\n            base_filename, extension = extract_filename_and_extension(filename_or_url)\n            image = image_from_url(filename_or_url, flags)\n            return image, base_filename, extension\n        filename_or_url = Path(filename_or_url)\n    if not Path(filename_or_url).exists():\n        raise FileNotFoundError(f\"{filename_or_url} is not found.\")\n    base_filename, extension = filename_or_url.stem, filename_or_url.suffix\n    filename = str(filename_or_url.resolve())\n    image = cv2.imread(filename, flags)\n    return image, base_filename, extension\n\n\ndef image_from_url(url, flags=cv2.IMREAD_COLOR):\n    \"\"\"\n    Read image from url.\n    Refer to https://stackoverflow.com/a/55026951/8860079\n    :param url:\n    :param flags:\n    :return:\n    \"\"\"\n    try:\n        resp = urlopen(url)\n        image = np.asarray(bytearray(resp.read()), dtype=\"uint8\")\n        image = cv2.imdecode(image, flags)\n    except urllib.error.HTTPError as e:\n        raise FileNotFoundError(f\"{url} is not found.\") from e\n    except Exception as e:\n        raise ArgumentError(f\"{url} is not a valid image.\") from e\n    return image\n\n\ndef create_color_bar(height, width, color):\n    bar = np.zeros((height, width, 3), np.uint8)\n    bar[:] = color\n    return bar\n\n\ndef is_black_white(image, threshold=192) -> bool:\n    \"\"\"\n    Check if the image is black and white\n    :param image:\n    :param threshold:\n    :return:\n    \"\"\"\n    # Reading Images\n    if len(image.shape) == 2:\n        return True\n    h, w, *_ = image.shape\n\n    # Extracting Standard Deviation\n    std = np.std(image, axis=2)\n    below_t = np.sum(np.where(std <= 25))\n    prob_bt = below_t / (h * w)\n\n    return prob_bt >= threshold\n\n\ndef resize(image, width: int = -1, height: int = -1):\n    \"\"\"\n    Resize the image, -1 means auto, but the image won't be resized if both width and height are -1\n    :param image:\n    :param width: -1 means auto\n    :param height: -1 means auto\n    :return:\n    \"\"\"\n    if width < 0 and height < 0:\n        return image\n    elif width < 0:\n        ratio = height / image.shape[0]\n        width = int(image.shape[1] * ratio)\n    elif height < 0:\n        ratio = width / image.shape[1]\n        height = int(image.shape[0] * ratio)\n\n    return cv2.resize(image, (width, height))\n\n\ndef detect_faces(\n    image,\n    scaleFactor=1.1,\n    minNeighbors=5,\n    minSize=(30, 30),\n    biggest_only=True,\n    is_bw=False,\n    threshold=0.3,\n):\n    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n    gray = cv2.equalizeHist(gray)\n\n    cascade = cv2.CascadeClassifier(cv2.data.haarcascades + \"haarcascade_frontalface_default.xml\")\n\n    flags = (cv2.CASCADE_SCALE_IMAGE | cv2.CASCADE_FIND_BIGGEST_OBJECT) if biggest_only else cv2.CASCADE_SCALE_IMAGE\n    faces = cascade.detectMultiScale(\n        gray,\n        scaleFactor=scaleFactor,\n        minNeighbors=minNeighbors,\n        minSize=minSize,\n        flags=flags,\n    )\n    if len(faces) == 0:\n        return []\n    # Change the format of faces from (x, y, w, h) to (x, y, x+w, y+h)\n    faces[:, 2:] += faces[:, :2]\n    return [face for face in faces if is_face(face, image, is_bw, threshold)]\n\n\ndef is_face(face_coord, image, is_bw, threshold=0.3):\n    \"\"\"\n    Check if the face is a real face.\n    Method: detect the skin area in the \"face\" and check if the skin area is larger than the threshold\n    :param face_coord:\n    :param image:\n    :param is_bw:\n    :param threshold:\n    :return:\n    \"\"\"\n    x1, y1, x2, y2 = face_coord\n    face_image = image[y1:y2, x1:x2]\n    detect_skin_fn = detect_skin_in_bw if is_bw else detect_skin_in_color\n    _, skin_mask = detect_skin_fn(face_image)\n    skin_pixels = cv2.countNonZero(skin_mask)\n    total_pixels = face_image.shape[0] * face_image.shape[1]\n    skin_ratio = skin_pixels / total_pixels\n    return skin_ratio >= threshold\n\n\ndef mask_face(image, face):\n    x1, y1, x2, y2 = face\n    mask = np.zeros(image.shape[:2], dtype=np.uint8)\n    mask[y1:y2, x1:x2] = 255  # Fill with white color\n    image = cv2.bitwise_and(image, image, mask=mask)\n    return image\n\n\ndef detect_skin_in_bw(image):\n    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n    _, threshold = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))\n    skin_mask = cv2.morphologyEx(threshold, cv2.MORPH_CLOSE, kernel)\n\n    skin = cv2.bitwise_and(image, image, mask=skin_mask)\n    all_0 = np.isclose(skin, 0).all()\n    return image if all_0 else skin, skin_mask\n\n\ndef detect_skin_in_color(image):\n    # Converting from BGR Colors Space to HSV\n    img = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n\n    # Defining skin Thresholds\n    low_hsv = np.array([0, 48, 80], dtype=np.uint8)\n    high_hsv = np.array([20, 255, 255], dtype=np.uint8)\n\n    skin_mask = cv2.inRange(img, low_hsv, high_hsv)\n    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))\n    skin_mask = cv2.morphologyEx(skin_mask, cv2.MORPH_OPEN, kernel)\n    skin_mask = cv2.morphologyEx(skin_mask, cv2.MORPH_CLOSE, kernel)\n    skin_mask = cv2.GaussianBlur(skin_mask, ksize=(3, 3), sigmaX=0)\n\n    skin = cv2.bitwise_and(image, image, mask=skin_mask)\n\n    all_0 = np.isclose(skin, 0).all()\n    return image if all_0 else skin, skin_mask\n\n\ndef draw_rects(image, *rects, color=(255, 0, 0), thickness=2):\n    for x1, y1, x2, y2 in rects:\n        cv2.rectangle(image, (x1 - 1, y1 - 1), (x2 + 1, y2 + 1), color, thickness)\n    return image\n\n\ndef dominant_colors(image, to_bw, n_clusters=2):\n    if to_bw:\n        data = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n        data = cv2.cvtColor(data, cv2.COLOR_GRAY2BGR)\n    else:\n        data = image\n    data = np.reshape(data, (-1, 3))\n    data = data[np.all(data != 0, axis=1)]\n    data = np.float32(data)\n\n    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)\n    flags = cv2.KMEANS_RANDOM_CENTERS\n    compactness, labels, colors = cv2.kmeans(data, n_clusters, None, criteria, 10, flags)\n    labels, counts = np.unique(labels, return_counts=True)\n\n    order = (-counts).argsort()\n    colors = colors[order]\n    counts = counts[order]\n\n    percents = counts / counts.sum()\n\n    return colors, percents\n\n\ndef blur(image, degree=25):\n    \"\"\"\n    Blur the image\n    :param image:\n    :param degree: The degree of blur. The bigger, the more blur\n    :return:\n    \"\"\"\n    ksize = degree, degree\n    return cv2.blur(image, ksize)\n\n\ndef skin_tone(colors, percents, skin_tone_palette, tone_labels):\n    lab_tones = [convert_color(sRGBColor.new_from_rgb_hex(rgb), LabColor) for rgb in skin_tone_palette]\n    lab_colors = [convert_color(sRGBColor(rgb_r=r, rgb_g=g, rgb_b=b, is_upscaled=True), LabColor) for b, g, r in colors]\n    distances = [np.sum([delta_e_cie2000(c, label) * p for c, p in zip(lab_colors, percents)]) for label in lab_tones]\n    tone_id = np.argmin(distances)\n    distance: float = distances[tone_id]\n    tone_hex = skin_tone_palette[tone_id].upper()\n    tone_label = tone_labels[tone_id]\n    return tone_id, tone_hex, tone_label, distance\n\n\ndef classify(\n    image,\n    is_bw,\n    to_bw,\n    skin_tone_palette,\n    tone_labels,\n    n_dominant_colors=2,\n    verbose=False,\n    report_image=None,\n    use_face=True,\n):\n    \"\"\"\n    Classify the skin tone of the image\n    :param image: Entire image or image with non-face areas masked\n    :param is_bw: Whether the image is black and white\n    :param to_bw: Whether to convert the image to black and white\n    :param skin_tone_palette:\n    :param tone_labels:\n    :param n_dominant_colors:\n    :param verbose: Whether to output the report image\n    :param report_image: The image to draw the report on\n    :param use_face: whether to use face area for detection\n    :return:\n    \"\"\"\n    detect_skin_fn = detect_skin_in_bw if is_bw else detect_skin_in_color\n    skin, skin_mask = detect_skin_fn(image)\n    dmnt_colors, dmnt_pcts = dominant_colors(skin, to_bw, n_dominant_colors)\n    # Generate readable strings\n    hex_colors = [\"#%02X%02X%02X\" % tuple(np.around([r, g, b]).astype(int)) for b, g, r in dmnt_colors]\n    pct_strs = [\"%.2f\" % p for p in dmnt_pcts]\n    result = {\"dominant_colors\": [{\"color\": color, \"percent\": pct} for color, pct in zip(hex_colors, pct_strs)]}\n    # Calculate skin tone\n    tone_id, tone_hex, tone_label, distance = skin_tone(dmnt_colors, dmnt_pcts, skin_tone_palette, tone_labels)\n    accuracy = round(100 - distance, 2)\n    result[\"skin_tone\"] = tone_hex\n    result[\"tone_label\"] = tone_label\n    result[\"accuracy\"] = accuracy\n    if not verbose:\n        return result, None\n\n    # 0. Create initial report image\n    report_image = initial_report_image(image, report_image, skin_mask, use_face, to_bw)\n    bar_width = 100\n\n    # 1. Create color bar for dominant colors\n    color_bars = create_dominant_color_bar(report_image, dmnt_colors, dmnt_pcts, bar_width)\n\n    # 2. Create color bar for a skin tone list\n    palette_bars = create_tone_palette_bar(report_image, tone_id, skin_tone_palette, bar_width)\n\n    # 3. Combine all bars and report image\n    report_image = np.hstack([report_image, color_bars, palette_bars])\n    msg_bar = create_message_bar(dmnt_colors, dmnt_pcts, tone_hex, distance, report_image.shape[1])\n    report_image = np.vstack([report_image, msg_bar])\n    return result, report_image\n\n\ndef initial_report_image(face_image, report_image, skin_mask, use_face, to_bw):\n    report_image = face_image if report_image is None else report_image\n    if to_bw:\n        report_image = cv2.cvtColor(report_image, cv2.COLOR_BGR2GRAY)\n        report_image = cv2.cvtColor(report_image, cv2.COLOR_GRAY2BGR)\n    if use_face:\n        gray = cv2.cvtColor(face_image, cv2.COLOR_BGR2GRAY)\n        skin_mask = cv2.threshold(gray, 1, 255, cv2.THRESH_BINARY)[1]\n    blurred_image = blur(report_image)\n    non_skin_mask = cv2.bitwise_not(skin_mask)\n    edges = cv2.Canny(skin_mask, 50, 150)\n    report_image = cv2.bitwise_and(report_image, report_image, mask=skin_mask) + cv2.bitwise_and(\n        blurred_image, blurred_image, mask=non_skin_mask\n    )\n    contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n    cv2.drawContours(report_image, contours, -1, (255, 0, 0), 2)\n    return report_image\n\n\ndef create_dominant_color_bar(report_image, dmnt_colors, dmnt_pcts, bar_width):\n    color_bars = []\n    total_height = 0\n    for color, pct in zip(dmnt_colors, dmnt_pcts):\n        bar_height = int(math.floor(report_image.shape[0] * pct))\n        total_height += bar_height\n        bar = create_color_bar(bar_height, bar_width, color)\n        color_bars.append(bar)\n    padding_height = report_image.shape[0] - total_height\n    if padding_height > 0:\n        padding = create_color_bar(padding_height, bar_width, (255, 255, 255))\n        color_bars.append(padding)\n    return np.vstack(color_bars)\n\n\ndef hex_to_bgr(hex_color):\n    hex_value = hex_color.lstrip(\"#\")\n    r, g, b = [int(hex_value[i : i + 2], 16) for i in (0, 2, 4)]\n    return [b, g, r]\n\n\ndef rgb_to_hex(rgb_color):\n    r, g, b = rgb_color\n    return \"#%02X%02X%02X\" % (r, g, b)\n\n\ndef create_tone_palette_bar(report_image, tone_id, skin_tone_palette, bar_width):\n    palette_bars = []\n    tone_height = report_image.shape[0] // len(skin_tone_palette)\n    tone_bgrs = []\n    for tone in skin_tone_palette:\n        hex_value = tone.lstrip(\"#\")\n        r, g, b = [int(hex_value[i : i + 2], 16) for i in (0, 2, 4)]\n        tone_bgrs.append([b, g, r])\n        bar = create_color_bar(tone_height, bar_width, [b, g, r])\n        palette_bars.append(bar)\n    padding_height = report_image.shape[0] - tone_height * len(skin_tone_palette)\n    if padding_height > 0:\n        padding = create_color_bar(padding_height, bar_width, (255, 255, 255))\n        palette_bars.append(padding)\n    bar = np.vstack(palette_bars)\n\n    padding = 1\n    start_point = (padding, tone_id * tone_height + padding)\n    end_point = (bar_width - padding, (tone_id + 1) * tone_height)\n    bar = cv2.rectangle(bar, start_point, end_point, (255, 0, 0), 2)\n    return bar\n\n\ndef create_message_bar(dmnt_colors, dmnt_pcts, tone_hex, distance, bar_width):\n    msg_bar = create_color_bar(height=50, width=bar_width, color=(243, 239, 214))\n    b, g, r = np.around(dmnt_colors[0]).astype(int)\n    dominant_color_hex = \"#%02X%02X%02X\" % (r, g, b)\n    pct = f\"{dmnt_pcts[0] * 100:.2f}%\"\n\n    font, font_scale, txt_colr, thickness, line_type = (\n        cv2.FONT_HERSHEY_SIMPLEX,\n        0.5,\n        (0, 0, 0),\n        1,\n        cv2.LINE_AA,\n    )\n    x, y = 2, 15\n    msg = f\"- Dominant color: {dominant_color_hex}, percent: {pct}\"\n    cv2.putText(msg_bar, msg, (x, y), font, font_scale, txt_colr, thickness, line_type)\n\n    text_size, _ = cv2.getTextSize(msg, font, font_scale, thickness)\n    line_height = text_size[1] + 10\n    accuracy = round(100 - distance, 2)\n    cv2.putText(\n        msg_bar,\n        f\"- Skin tone: {tone_hex}, accuracy: {accuracy}\",\n        (x, y + line_height),\n        font,\n        font_scale,\n        txt_colr,\n        thickness,\n        cv2.LINE_AA,\n    )\n\n    return msg_bar\n\n\ndef process_image(\n    image: np.ndarray,\n    is_bw: bool,\n    to_bw: bool,\n    skin_tone_palette: list,\n    tone_labels: list = None,\n    new_width=-1,\n    n_dominant_colors=2,\n    scaleFactor=1.1,\n    minNeighbors=5,\n    minSize=(30, 30),\n    biggest_only=True,\n    threshold=0.3,\n    verbose=False,\n):\n    image = resize(image, new_width)\n\n    records, report_images = [], {}\n    face_coords = detect_faces(image, scaleFactor, minNeighbors, minSize, biggest_only, is_bw, threshold)\n    n_faces = len(face_coords)\n\n    if n_faces == 0:\n        # If no face is detected, find skin area in the whole image and classify.\n        record, report_image = classify(\n            image,\n            is_bw,\n            to_bw,\n            skin_tone_palette,\n            tone_labels,\n            n_dominant_colors,\n            verbose=verbose,\n            use_face=False,\n        )\n        record[\"face_id\"] = \"NA\"\n        records.append(record)\n        report_images[\"NA\"] = report_image\n    # Otherwise, detect skin tone for each face\n    for idx, face_coord in enumerate(face_coords):\n        face_image = mask_face(image, face_coord)\n        record, report_image = classify(\n            face_image,\n            is_bw,\n            to_bw,\n            skin_tone_palette,\n            tone_labels,\n            n_dominant_colors,\n            verbose=verbose,\n            report_image=image,\n            use_face=True,\n        )\n        record[\"face_id\"] = idx + 1\n        records.append(record)\n        report_image = face_report_image(face_coord, idx, report_image)\n        report_images[idx + 1] = report_image\n\n    return records, report_images\n\n\ndef show(image, title=None):\n    title = f\" - {title}\" if title else \"\"\n    cv2.imshow(f\"Skin Tone Classifier{title}\", image)\n    cv2.waitKey(0)\n    cv2.destroyAllWindows()\n\n\ndef face_report_image(face, idx, image):\n    if image is None:\n        return None\n    x1, y1, x2, y2 = face\n    width = x2 - x1\n    height = 20\n    bar = np.ones((height, width, 3), dtype=np.uint8) * (255, 0, 0)\n    report_image = image.copy()\n    report_image[y2 : y2 + height, x1:x2] = bar\n    txt = f\"Face {idx + 1}\"\n    text_color = (255, 255, 255)\n    font_scale = 0.5\n    thickness = 1\n    text_size, _ = cv2.getTextSize(txt, cv2.FONT_HERSHEY_SIMPLEX, font_scale, thickness)\n    text_x = x1 + (width - text_size[0]) // 2\n    text_y = y2 + 15\n    cv2.putText(\n        report_image,\n        txt,\n        (text_x, text_y),\n        cv2.FONT_HERSHEY_SIMPLEX,\n        font_scale,\n        text_color,\n        thickness,\n    )\n    return report_image\n"
  },
  {
    "path": "src/stone/package.py",
    "content": "__version__ = \"1.2.6\"\n__package_name__ = \"skin-tone-classifier\"\n__app_name__ = \"Skin Tone Classifier\"\n__description__ = \"An easy-to-use library for skin tone classification\"\n__author__ = \"Chenglong Ma\"\n__author_email__ = \"chenglong.m@outlook.com\"\n__author_website__ = \"https://chenglongma.com/\"\n__url__ = \"https://chenglongma.com/SkinToneClassifier/\"\n__code__ = \"https://github.com/ChenglongMa/SkinToneClassifier/\"\n__issues__ = \"https://github.com/ChenglongMa/SkinToneClassifier/issues\"\n__license__ = \"GPLv3\"\n__copyright__ = \"2022\"\n"
  },
  {
    "path": "src/stone/ui/__init__.py",
    "content": ""
  },
  {
    "path": "src/stone/utils.py",
    "content": "import argparse\nimport functools\nimport logging\nimport os\nimport re\nimport string\nimport sys\nfrom pathlib import Path\nfrom typing import Union\nfrom urllib.parse import urlparse\n\nfrom stone.package import __version__, __package_name__, __description__, __app_name__\n\nLOG = logging.getLogger(__name__)\n\n\nclass ArgumentError(ValueError):\n    \"\"\"\n    Wrapper for argument error. This exception will be raised when the arguments are invalid.\n    \"\"\"\n\n    pass\n\n\ndef Gooey(*args, **kwargs):\n    \"\"\"\n    Dummy decorator for Gooey.\n    Used in CLI mode to avoid the import error when the Gooey package is not installed.\n    :param args:\n    :param kwargs:\n    :return:\n    \"\"\"\n\n    def inner(func):\n        return func\n\n    return inner\n\n\n@functools.cache\ndef alphabet_id(n:int) -> str:\n    letters = string.ascii_uppercase\n    n_letters = len(letters)\n    if n < n_letters:\n        return letters[n]\n\n    prefix = \"\"\n    while n >= n_letters:\n        prefix += letters[(n // n_letters) - 1]\n        n %= n_letters\n\n    return prefix + letters[n]\n\n\ndef is_url(text):\n    return urlparse(text).scheme in [\"http\", \"https\"]\n\n\ndef extract_filename_and_extension(url):\n    \"\"\"\n    Extract base filename and extension from the url.\n    :param url: URL with filename and extension, e.g., https://example.com/images/pic.jpg?param=value\n    :return: Base filename and extension, e.g., pic, jpg\n    \"\"\"\n    parsed_url = urlparse(url)\n    path = parsed_url.path\n    filename = path.split(\"/\")[-1]\n    basename, *extension = filename.split(\".\")\n    return basename, f\".{extension[0]}\" if extension else None\n\n\ndef build_image_paths(images_paths, recursive=False):\n    filenames, urls = [], []\n    valid_images = [\"*.jpg\", \"*.gif\", \"*.png\", \"*.jpeg\", \"*.webp\", \"*.tif\"]\n    excluded_folders = [\"debug\", \"log\"]\n    if isinstance(images_paths, str):\n        images_paths = [images_paths]\n\n    for filename in images_paths:\n        if is_url(filename):\n            urls.append(filename)\n            continue\n        p = Path(filename)\n        if p.is_dir():\n            images = [p.glob(pattern) for pattern in valid_images]\n            if recursive:\n                subfolders = [f for f in p.glob(\"*/\") if f.name not in excluded_folders]\n                images.extend([sp.rglob(pattern) for pattern in valid_images for sp in subfolders])\n\n            filenames.extend(images)\n        elif p.is_file():\n            filenames.append([p])\n    paths = set([f.resolve() for fs in filenames for f in fs] + urls)\n    paths = list(paths)\n    if len(paths) == 0:\n        raise FileNotFoundError(\"No valid images in the specified path.\")\n    # Sort paths by (first) number extracted from the filename string\n    paths.sort(key=sort_file)\n    return paths\n\n\ndef sort_file(path: Union[str, Path]):\n    if isinstance(path, Path):\n        basename = path.stem\n    else:\n        basename, *_ = extract_filename_and_extension(path)\n    nums = re.findall(r\"\\d+\", basename)\n    return (int(nums[0]) if nums else float(\"inf\")), basename\n\n\ndef is_windows():\n    return sys.platform in [\"win32\", \"cygwin\"]\n\n\ndef is_debugging():\n    gettrace = getattr(sys, \"gettrace\", None)\n    return gettrace is not None and gettrace()\n\n\ndef build_arguments():\n    try:\n        from gooey import GooeyParser\n\n        in_gui = True\n    except ImportError:\n        from argparse import ArgumentParser as GooeyParser\n\n        in_gui = False\n\n    kwargs = dict(formatter_class=argparse.RawTextHelpFormatter) if not in_gui else {}\n    parser = GooeyParser(\n        description=__description__,\n        **kwargs,\n    )\n    kwargs = (\n        {\n            \"gooey_options\": {\"show_border\": False, \"columns\": 1},\n        }\n        if in_gui\n        else {}\n    )\n    files = parser.add_argument_group(\n        \"Images to process\",\n        \"The locations of images to process, which can be directories, files, or URLs.\\n\"\n        \"Multiple values are separated by space;\\n\"\n        'You can mix folders, filenames and web links together, e.g., \"/path/to/dir1 /path/to/pic.jpg https://example.com/pic.png\".\\n',\n        **kwargs,\n    )\n    kwargs = {\"gooey_options\": {\"visible\": False}} if in_gui else {}\n\n    files.add_argument(\n        \"-i\",\n        \"--images\",\n        nargs=\"+\",\n        default=[] if in_gui else [os.getcwd()],\n        metavar=\"Image Filenames\",\n        help=\"Image filename(s), Directories or URLs to process. Separated by space.\",\n        **kwargs,\n    )\n    if in_gui:\n        files.add_argument(\n            \"--image_dirs\",\n            nargs=\"+\",\n            metavar=\"Image Directories\",\n            widget=\"DirChooser\",\n            # widget=\"MultiDirChooser\", # fixme: enable this widget when issues are fixed\n            gooey_options={\n                \"message\": \"Select directories to process\",\n                \"initial_value\": os.getcwd(),\n                \"default_path\": os.getcwd(),\n                \"placeholder\": \"e.g., /path/to/dir1 /path/to/dir2\",\n            },\n        )\n    kwargs = dict(metavar=\"Recursive Search\") if in_gui else {}\n    files.add_argument(\n        \"-r\",\n        \"--recursive\",\n        action=\"store_true\",\n        help=\"Search images recursively in the specified directory.\",\n        **kwargs,\n    )\n    if in_gui:\n        files.add_argument(\n            \"--image_files\",\n            nargs=\"+\",\n            metavar=\"Image Filenames\",\n            help=\"Add individual image file(s)\",\n            widget=\"MultiFileChooser\",\n            gooey_options={\n                \"wildcard\": \"All images|*.jpg;*.jpeg;*.png;*.bmp;*.gif;*.tif;*.webp|\"\n                \"JPG (*.jpg)|*.jpg|\"\n                \"JPEG (*.jpeg)|*.jpeg|\"\n                \"PNG (*.png)|*.png|\"\n                \"BMP (*.bmp)|*.bmp|\"\n                \"GIF (*.gif)|*.gif|\"\n                \"TIFF (*.tif)|*.tif|\"\n                \"WEBP (*.webp)|*.webp|\"\n                \"All files (*.*)|*.*\",\n                \"message\": \"Select the image file(s) to process\",\n                \"default_dir\": os.getcwd(),\n                \"full_width\": False,\n                \"placeholder\": \"e.g., a.jpg b.png\",\n            },\n        )\n\n        files.add_argument(\n            \"--image_urls\",\n            nargs=\"+\",\n            metavar=\"Image URLs\",\n            help=\"Add image URLs\",\n            gooey_options={\n                \"full_width\": False,\n                \"placeholder\": \"e.g., https://example.com/a.jpg https://example.com/b.png\",\n            },\n        )\n\n    kwargs = {\"gooey_options\": {\"show_border\": False, \"columns\": 2}} if in_gui else {}\n    images = parser.add_argument_group(\n        \"Image Settings\",\n        **kwargs,\n    )\n    bw_option = \"black/white\" if in_gui else \"bw\"\n    images.add_argument(\n        \"-t\",\n        \"--image_type\",\n        default=\"auto\",\n        metavar=\"Image Type\",\n        help=\"Specify whether the input image(s) is/are colored or black/white.\\n\"\n        f'Defaults to \"auto\", which will be detected automatically. Other options are \"color\" and \"{bw_option}\".\\n',\n        choices=[\"auto\", \"color\", bw_option],\n    )\n    kwargs = {\"gooey_options\": {\"full_width\": True}} if in_gui else {}\n    images.add_argument(\n        \"-p\",\n        \"--palette\",\n        nargs=\"+\",\n        metavar=\"Palette\",\n        help=\"Skin tone palette;\\n\"\n        \"Valid choices are 'perla', 'monk', 'yadon-ostfeld', 'proder'.\\n\"\n        'You can also input RGB hex values leading by \"#\" or RGB values separated by comma(,),\\n'\n        \"E.g., #373028 #422811 or 255,255,255 100,100,100\\n\"\n        \"Leave blank to use the 'perla' palette.\\n\",\n        **kwargs,\n    )\n    images.add_argument(\n        \"-l\",\n        \"--labels\",\n        nargs=\"+\",\n        metavar=\"Labels\",\n        help=\"Skin tone labels;\\n\"\n        \"Leave blank to use the default values: the uppercase alphabet list leading by the image type ('C' for 'color'; 'B' for 'Black&White'), \"\n        \"e.g., ['CA', 'CB', ..., 'CZ'] or ['BA', 'BB', ..., 'BZ'].\\n\"\n        \"Since v1.2.0, supports range of labels, e.g., 'A-Z' or '1-10'.\\n\"\n        \"Refer to https://github.com/ChenglongMa/SkinToneClassifier#3-specify-category-labels for more details.\",\n        **kwargs,\n    )\n\n    kwargs = dict(metavar=\"Convert to Black/White\") if in_gui else {}\n    images.add_argument(\n        \"-bw\",\n        \"--black_white\",\n        action=\"store_true\",\n        help=\"Whether to convert the input to black/white image(s)?\\n\"\n        \"If true, the app will convert the input to black/white image(s) and use the black/white palette for classification.\",\n        **kwargs,\n    )\n\n    kwargs = (\n        {\"gooey_options\": {\"initial_value\": 2, \"min\": 1, \"max\": 99999, \"full_width\": False}, \"widget\": \"IntegerField\"}\n        if in_gui\n        else {}\n    )\n    images.add_argument(\n        \"--n_colors\",\n        metavar=\"Number of Dominant Colors\",\n        type=int,\n        help=\"Specify the number of dominant colors to be extracted.\\n\"\n        \"The colors will be used to compare with the colors in the palette.\\n\",\n        default=2,\n        **kwargs,\n    )\n\n    kwargs = (\n        {\n            \"gooey_options\": {\"initial_value\": 250, \"min\": 10, \"max\": 99999, \"full_width\": False},\n            \"widget\": \"IntegerField\",\n        }\n        if in_gui\n        else {}\n    )\n    images.add_argument(\n        \"--new_width\",\n        type=int,\n        metavar=\"New Width (pixels)\",\n        help=\"Resize the images with the specified width.\\n\"\n        \"Sometimes smaller images will be processed faster and more accurately.\\n\"\n        \"No resizing will be performed if the value is negative.\",\n        default=250,\n        **kwargs,\n    )\n\n    kwargs = {\"gooey_options\": {\"show_border\": True}} if in_gui else {}\n    outputs = parser.add_argument_group(\"Output Settings\", **kwargs)\n\n    kwargs = (\n        {\n            \"gooey_options\": {\"message\": \"Select the output directory\", \"default_path\": os.getcwd()},\n            \"widget\": \"DirChooser\",\n        }\n        if in_gui\n        else {}\n    )\n    outputs.add_argument(\n        \"-o\",\n        \"--output\",\n        metavar=\"Output Directory\",\n        default=os.getcwd(),\n        help=\"Specify the path of output file, defaults to current directory.\",\n        **kwargs,\n    )\n\n    kwargs = dict(metavar=\"Generate Report Images\") if in_gui else {}\n    outputs.add_argument(\n        \"-d\",\n        \"--debug\",\n        action=\"store_true\",\n        default=in_gui,\n        help=\"Whether to generate report images?\\n\"\n        \"If true, the report images will be saved in the '<OUTPUT_DIRECTORY>/debug' directory.\",\n        **kwargs,\n    )\n\n    kwargs = {\"gooey_options\": {\"show_border\": False, \"columns\": 2}} if in_gui else {}\n    advanced = parser.add_argument_group(\n        \"Advanced Settings\",\n        \"For advanced users only, please refer to https://stackoverflow.com/a/20805153/8860079\",\n        **kwargs,\n    )\n\n    kwargs = (\n        {\"gooey_options\": {\"initial_value\": 1.1, \"min\": 0.1, \"max\": 2.0}, \"widget\": \"DecimalField\"} if in_gui else {}\n    )\n    advanced.add_argument(\n        \"--scale\",\n        type=float,\n        metavar=\"Scale\",\n        help=\"Specify how much the image size is reduced at each image scale.\",\n        default=1.1,\n        **kwargs,\n    )\n\n    kwargs = {\"gooey_options\": {\"initial_value\": 5, \"min\": 1, \"max\": 99999}, \"widget\": \"IntegerField\"} if in_gui else {}\n    advanced.add_argument(\n        \"--min_nbrs\",\n        type=int,\n        metavar=\"Minimum Neighbors\",\n        help=\"Specify how many neighbors each candidate rectangle should have to retain it.\\n\"\n        \"Higher value results in less detections but with higher quality.\",\n        default=5,\n        **kwargs,\n    )\n    default_min_width = 90\n    default_min_height = 90\n\n    kwargs = {\"gooey_options\": {\"visible\": False}} if in_gui else {}\n    advanced.add_argument(\n        \"--min_size\",\n        type=int,\n        nargs=\"+\",\n        metavar=\"Minimum Possible Face Size, format: <Width Height>\",\n        help=f'Specify the minimum possible face size. Faces smaller than that are ignored, defaults to \"{default_min_width} {default_min_height}\".',\n        default=(default_min_width, default_min_height),\n        **kwargs,\n    )\n    if in_gui:\n        min_size = advanced.add_argument_group(\n            \"Minimum Possible Face Size (pixels)\",\n            'Specify the minimum possible face size. Faces smaller than that are ignored, defaults to \"90 90\".',\n            gooey_options={\"show_border\": True, \"columns\": 2},\n        )\n\n        min_size.add_argument(\n            \"--min_width\",\n            type=int,\n            metavar=\"Minimum Width\",\n            # help=\"Specify the minimum possible face width. Faces smaller than that are ignored, defaults to 90.\",\n            default=default_min_width,\n            widget=\"IntegerField\",\n            gooey_options={\"initial_value\": default_min_width, \"min\": 10, \"max\": 99999},\n        )\n\n        min_size.add_argument(\n            \"--min_height\",\n            type=int,\n            metavar=\"Minimum Height\",\n            # help=\"Specify the minimum possible face height. Faces smaller than that are ignored, defaults to 90.\",\n            default=default_min_height,\n            widget=\"IntegerField\",\n            gooey_options={\"initial_value\": default_min_height, \"min\": 10, \"max\": 99999},\n        )\n\n    kwargs = (\n        {\"gooey_options\": {\"initial_value\": 0.15, \"min\": 0.01, \"max\": 1.0}, \"widget\": \"DecimalField\"} if in_gui else {}\n    )\n    advanced.add_argument(\n        \"--threshold\",\n        type=float,\n        metavar=\"Minimum Possible Face Proportion\",\n        help=\"Specify the minimum proportion of the skin area required to identify the face, defaults to 0.15.\",\n        default=0.15,\n        **kwargs,\n    )\n\n    kwargs = {\"gooey_options\": {\"initial_value\": 0, \"min\": 0, \"max\": 99999}, \"widget\": \"IntegerField\"} if in_gui else {}\n    advanced.add_argument(\n        \"--n_workers\",\n        type=int,\n        metavar=\"Number of CPU Workers\",\n        help=\"Specify the number of workers to process the images.\\n\"\n        \"0 means the total number of CPU cores in the system.\",\n        default=0,\n        **kwargs,\n    )\n\n    kwargs = dict(gooey_options={\"visible\": False}) if in_gui else {}\n    advanced.add_argument(\n        \"-v\",\n        \"--version\",\n        action=\"version\",\n        version=f\"%(prog)s {__version__}\",\n        help=\"Show the version number and exit.\",\n        **kwargs,\n    )\n    args = parser.parse_args()\n    images = []\n    if getattr(args, \"images\", False):\n        images.extend(args.images)\n    if getattr(args, \"image_dirs\", False):\n        images.extend(args.image_dirs)\n    if getattr(args, \"image_files\", False):\n        images.extend(args.image_files)\n    if getattr(args, \"image_urls\", False):\n        images.extend(args.image_urls)\n    args.images = images\n    if (\n        tuple(args.min_size) == (default_min_width, default_min_height)\n        and getattr(args, \"min_width\", False)\n        and getattr(args, \"min_height\", False)\n    ):\n        args.min_size = (args.min_width, args.min_height)\n    return args\n\n\ndef resolve_labels(labels):\n    if not labels or len(labels) != 1:\n        return labels\n    label = labels[0]\n\n    separator = r\"[-,~:;_]\"\n    pattern = rf\"^([a-zA-Z0-9]+){separator}([a-zA-Z0-9]+)(?:{separator}([-+]?\\d+))?$\"\n    match = re.match(pattern, label)\n    if match is None:\n        return labels\n    start, end, step = match.groups()\n    if not step:\n        step = 1\n    else:\n        step = int(step)\n    if step == 0:\n        LOG.warning(f\"The specified step in the '--label' setting ('{label}') cannot be 0; resetting to 1.\")\n        step = 1\n    if step < 0:\n        start, end = end, start\n\n    if start.isdigit() and end.isalpha() or start.isalpha() and end.isdigit():\n        LOG.warning(\n            f\"Invalid '--label' setting ('{label}'): The start value ({start}) and the end value ({end}) should be both digits or both letters.\"\n        )\n        return labels\n    if start >= end:\n        LOG.warning(\n            f\"Invalid '--label' setting ('{label}'): The start value ({start}) should be less than the end value ({end}).\"\n        )\n        return labels\n    if start.isdigit() and end.isdigit():\n        start, end = int(start), int(end)\n        return [str(i) for i in range(start, end + 1, step)]\n    if start.isalpha() and end.isalpha():\n        start, end = start.upper(), end.upper()\n        return [chr(i) for i in range(ord(start), ord(end) + 1, step)]\n    return labels\n\n\ndef get_latest_version_from_pypi(package_name):\n    try:\n        import requests\n\n        response = requests.get(f\"https://pypi.org/pypi/{package_name}/json\")\n        response.raise_for_status()\n\n        data = response.json()\n        latest_version = data[\"info\"][\"version\"]\n        return latest_version\n    except Exception:\n        pass\n\n\ndef check_version():\n    if \"STONE_UPGRADE_FLAG\" in os.environ:\n        return\n    try:\n        from packaging.version import parse\n        import importlib.metadata\n\n        latest_version = get_latest_version_from_pypi(__package_name__)\n        if not latest_version:\n            return\n        distribution = importlib.metadata.distribution(__package_name__)\n        installed_version = distribution.version\n        if parse(installed_version) < parse(latest_version):\n            from colorama import just_fix_windows_console, Fore\n\n            just_fix_windows_console()\n            print(\n                Fore.YELLOW + f\"You are using an outdated version of {__package_name__} ({installed_version}).\\n\"\n                f\"Please upgrade to the latest version ({latest_version}) with the following command:\\n\",\n                Fore.GREEN + f\"pip install {__package_name__}[all] --upgrade\\n\" + Fore.RESET,\n            )\n            os.environ[\"STONE_UPGRADE_FLAG\"] = \"1\"\n    except Exception:\n        pass\n"
  },
  {
    "path": "tests/__init__.py",
    "content": ""
  },
  {
    "path": "tests/test_utils.py",
    "content": "import unittest\nfrom pathlib import Path\n\nfrom stone.image import default_tone_labels\nfrom stone.utils import build_image_paths, resolve_labels, alphabet_id\n\n\nclass TestUtils(unittest.TestCase):\n    def setUp(self):\n        self.image_path = str(Path(\"./mock_data/images\").resolve())\n        # Sorted image paths\n        self.expected_recursive_image_paths = [\n            f\"{self.image_path}/fake_img_1.gif\",  # In default, sorted by the trailing number\n            f\"{self.image_path}/fake_img_2.jpeg\",\n            f\"{self.image_path}/subfolder/sub_fake_img_3.gif\",\n            f\"{self.image_path}/subfolder/sub_fake_img_4.jpeg\",\n            f\"{self.image_path}/fake_img_10.webp\",  # Sorted by length of the filename if the trailing number is the same\n            f\"{self.image_path}/subfolder/sub_fake_img_10.jpg\",\n            f\"{self.image_path}/subfolder/sub_fake_img_21.png\",\n            f\"{self.image_path}/fake_img_22.png\",\n            f\"{self.image_path}/fake_img_100.jpg\",\n            f\"{self.image_path}/subfolder/sub_fake_img_101.webp\",\n        ]\n\n        self.expected_non_recursive_image_paths = [\n            p for p in self.expected_recursive_image_paths if \"subfolder\" not in p\n        ]\n\n    def should_exclude_folder(self, paths, excluded_folders):\n        \"\"\"\n        Check if the paths do not contain any of the excluded folders.\n        :param paths:\n        :param excluded_folders:\n        :return:\n        \"\"\"\n        self.assertTrue(\n            all(\n                [\n                    excluded_folder != path.relative_to(self.image_path).parts[0]\n                    for path in paths\n                    for excluded_folder in excluded_folders\n                ]\n            )\n        )\n\n    def test_single_directory_recursive(self):\n        image_paths = build_image_paths(self.image_path, recursive=True)\n        self.assertTrue(isinstance(image_paths, list))\n        self.assertEqual(len(image_paths), 10)\n        self.should_exclude_folder(image_paths, [\"debug\", \"log\"])\n        for i in range(len(image_paths)):\n            actual = image_paths[i]\n            expected = Path(self.expected_recursive_image_paths[i])\n            self.assertTrue(actual.samefile(expected), msg=f\"{i}: {actual} != {expected}\")\n\n    def test_single_directory_non_recursive(self):\n        image_paths = build_image_paths(self.image_path, recursive=False)\n        self.assertTrue(isinstance(image_paths, list))\n        self.assertEqual(len(image_paths), 5)\n        self.should_exclude_folder(image_paths, [\"subfolder\", \"debug\", \"log\"])\n        self.assertListEqual(\n            image_paths,\n            [Path(p).resolve() for p in self.expected_non_recursive_image_paths],\n        )\n\n    def test_multiple_directories_recursive(self):\n        paths = build_image_paths([self.image_path, f\"{self.image_path}/subfolder\"], recursive=True)\n        self.assertTrue(isinstance(paths, list))\n        self.assertEqual(len(paths), 10)\n\n    def test_single_file(self):\n        paths = build_image_paths(self.expected_recursive_image_paths[0])\n        self.assertTrue(isinstance(paths, list))\n        self.assertEqual(len(paths), 1)\n\n    def test_multiple_files(self):\n        paths = build_image_paths(self.expected_recursive_image_paths)\n        self.assertTrue(isinstance(paths, list))\n        self.assertEqual(len(paths), len(self.expected_recursive_image_paths))\n\n    def test_single_url(self):\n        paths = build_image_paths(\"http://example.com/image.jpg\")\n        self.assertTrue(isinstance(paths, list))\n        self.assertEqual(len(paths), 1)\n\n    def test_no_valid_images(self):\n        with self.assertRaises(FileNotFoundError):\n            build_image_paths(\"/path/to/nonexistent\")\n\n    def test_resolve_labels_in_digits(self):\n        start, end, step = 1, 12, 1\n        labels = [f\"{start}-{end}\"]\n        expected = \"1 2 3 4 5 6 7 8 9 10 11 12\".split()\n        actual = resolve_labels(labels)\n        self.assertListEqual(actual, expected)\n\n    def test_resolve_labels_in_alphabet(self):\n        start, end, step = \"a\", \"z\", 2\n        labels = [f\"{start}-{end}-{step}\"]\n        expected = list(\"ACEGIKMOQSUWY\")\n        actual = resolve_labels(labels)\n        self.assertListEqual(actual, expected)\n\n    def test_resolve_labels_step_is_zero(self):\n        start, end, step = \"a\", \"z\", 0\n        labels = [f\"{start}-{end}-{step}\"]\n        expected = list(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\")\n        actual = resolve_labels(labels)\n        self.assertListEqual(actual, expected)\n\n    def test_resolve_labels_start_less_than_end(self):\n        start, end, step = 12, 1, 1\n        labels = [f\"{start}-{end}\"]\n        expected = labels\n        actual = resolve_labels(labels)\n        self.assertListEqual(actual, expected)\n\n    def test_default_tone_labels(self):\n        tone_palette = list(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\")\n        actual_labels = default_tone_labels(tone_palette)\n        self.assertListEqual(\n            actual_labels,\n            list(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"),\n        )\n\n    def test_alphabet_id(self):\n        self.assertEqual(alphabet_id(0), \"A\")\n        self.assertEqual(alphabet_id(25), \"Z\")\n        self.assertEqual(alphabet_id(26), \"AA\")\n        self.assertEqual(alphabet_id(27), \"AB\")\n        self.assertEqual(alphabet_id(51), \"AZ\")\n        self.assertEqual(alphabet_id(52), \"BA\")\n        self.assertEqual(alphabet_id(77), \"BZ\")\n        self.assertEqual(alphabet_id(78), \"CA\")\n\n    def test_default_tone_labels_with_more_than_26_tones(self):\n        tone_palette = list(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\") * 2\n        actual_labels = default_tone_labels(tone_palette)\n        self.assertListEqual(\n            actual_labels,\n            list(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\") + [\"AA\", \"AB\", \"AC\", \"AD\", \"AE\", \"AF\", \"AG\", \"AH\", \"AI\", \"AJ\", \"AK\", \"AL\", \"AM\", \"AN\", \"AO\", \"AP\", \"AQ\", \"AR\", \"AS\", \"AT\", \"AU\", \"AV\", \"AW\", \"AX\", \"AY\", \"AZ\"],\n        )\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n"
  },
  {
    "path": "tox.ini",
    "content": "# this file is *not* meant to cover or endorse the use of tox or pytest or\n# testing in general,\n#\n#  It's meant to show the use of:\n#\n#  - check-manifest\n#     confirm items checked into vcs are in your sdist\n#  - readme_renderer (when using a ReStructuredText README)\n#     confirms your long_description will render correctly on PyPI.\n#\n#  and also to help confirm pull requests to this project.\n\n[tox]\nenvlist = py{39,310,311,312}\n\n# Define the minimal tox version required to run;\n# if the host tox is less than this the tool with create an environment and\n# provision it with a tox that satisfies it under provision_tox_env.\n# At least this version is needed for PEP 517/518 support.\nminversion = 3.3.0\n\n# Activate isolated build environment. tox will use a virtual environment\n# to build a source distribution from the source tree. For build tools and\n# arguments use the pyproject.toml file as specified in PEP-517 and PEP-518.\nisolated_build = true\n\n[testenv]\ndeps =\n    check-manifest >= 0.42\n    # If your project uses README.rst, uncomment the following:\n    # readme_renderer\n    # flake8\n    # pytest\n    build\n    twine\n\nallowlist_externals =\n    cp\n    copy\n    xcopy\n    python\n\ncommands =\n    check-manifest --ignore 'tox.ini,tests/**,.idea/**'\n    python -m build\n    python -m twine check dist/*\n    # flake8 .\n    # python -m unittest discover -v\n    python -c \"import os, shutil; shutil.copytree('tests/mock_data', './mock_data', dirs_exist_ok=True)\"\n    python -m unittest discover -v tests\n    # py.test tests {posargs}\n\n# [flake8]\n# exclude = .tox,*.egg,build,data\n# select = E,W,F"
  }
]