diff --git a/.cookiecutter.json b/.cookiecutter.json new file mode 100644 index 0000000..2be3311 --- /dev/null +++ b/.cookiecutter.json @@ -0,0 +1,14 @@ +{ + "_template": "gh:iterative/py-template", + "author": "Iterative", + "copyright_year": "2022", + "development_status": "Development Status :: 1 - Planning", + "email": "support@dvc.org", + "friendly_name": "DVC render", + "github_user": "iterative", + "license": "Apache-2.0", + "package_name": "dvc_render", + "project_name": "dvc-render", + "short_description": "", + "version": "0.0.0" +} diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..393a944 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,16 @@ +version: 2 + +updates: + - directory: "/" + package-ecosystem: "pip" + schedule: + interval: "weekly" + labels: + - "maintenance" + + - directory: "/" + package-ecosystem: "github-actions" + schedule: + interval: "weekly" + labels: + - "maintenance" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..03538ae --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,32 @@ +name: Release + +on: + release: + types: [published] + +jobs: + release: + runs-on: ubuntu-latest + steps: + - name: Check out the repository + uses: actions/checkout@v2 + + - name: Set up Python 3.7 + uses: actions/setup-python@v2 + with: + python-version: '3.7' + + - name: Upgrade pip and nox + run: | + pip install --upgrade pip nox + pip --version + nox --version + + - name: Build package + run: nox -s build + + - name: Upload package + uses: pypa/gh-action-pypi-publish@master + with: + user: __token__ + password: ${{ secrets.PYPI_TOKEN }} diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..8fc7ec0 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,40 @@ +name: Tests + +on: [push, pull_request] + +jobs: + tests: + timeout-minutes: 10 + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-20.04, windows-latest, macos-latest] + pyv: ['3.7', '3.8', '3.9', '3.10'] + + steps: + - name: Check out the repository + uses: actions/checkout@v2 + + - name: Set up Python ${{ matrix.pyv }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.pyv }} + + - name: Upgrade pip and nox + run: | + pip install --upgrade pip nox + pip --version + nox --version + + - name: Lint code and check dependencies + run: nox -s lint safety + + - name: Run tests + run: nox -s tests-${{ matrix.pyv }} -- --cov-report=xml + + - name: Upload coverage report + uses: codecov/codecov-action@v2.1.0 + + - name: Build package + run: nox -s build diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a81c8ee --- /dev/null +++ b/.gitignore @@ -0,0 +1,138 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..e938684 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,45 @@ +default_language_version: + python: python3 +repos: + - repo: https://github.com/psf/black + rev: 21.11b1 + hooks: + - id: black + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.0.1 + hooks: + - id: check-added-large-files + - id: check-case-conflict + - id: check-docstring-first + - id: check-executables-have-shebangs + - id: check-toml + - id: check-merge-conflict + - id: check-yaml + - id: debug-statements + - id: end-of-file-fixer + - id: mixed-line-ending + - id: sort-simple-yaml + - id: trailing-whitespace + - repo: https://github.com/codespell-project/codespell + rev: v2.1.0 + hooks: + - id: codespell + - repo: https://github.com/asottile/pyupgrade + rev: v2.31.0 + hooks: + - id: pyupgrade + - repo: https://github.com/PyCQA/isort + rev: 5.10.1 + hooks: + - id: isort + - repo: https://gitlab.com/pycqa/flake8 + rev: 3.9.2 + hooks: + - id: flake8 + additional_dependencies: + - flake8-bandit + - flake8-broken-line + - flake8-bugbear + - flake8-comprehensions + - flake8-debugger + - flake8-string-format diff --git a/CODE_OF_CONDUCT.rst b/CODE_OF_CONDUCT.rst new file mode 100644 index 0000000..bc50a04 --- /dev/null +++ b/CODE_OF_CONDUCT.rst @@ -0,0 +1,105 @@ +Contributor Covenant Code of Conduct +==================================== + +Our Pledge +---------- + +We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. + + +Our Standards +------------- + +Examples of behavior that contributes to a positive environment for our community include: + +- Demonstrating empathy and kindness toward other people +- Being respectful of differing opinions, viewpoints, and experiences +- Giving and gracefully accepting constructive feedback +- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience +- Focusing on what is best not just for us as individuals, but for the overall community + +Examples of unacceptable behavior include: + +- The use of sexualized language or imagery, and sexual attention or + advances of any kind +- Trolling, insulting or derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or email + address, without their explicit permission +- Other conduct which could reasonably be considered inappropriate in a + professional setting + +Enforcement Responsibilities +---------------------------- + +Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. + + +Scope +----- + +This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. + + +Enforcement +----------- + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at support@dvc.org. All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the reporter of any incident. + + +Enforcement Guidelines +---------------------- + +Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: + + +1. Correction +~~~~~~~~~~~~~ + +**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. + + +2. Warning +~~~~~~~~~~ + +**Community Impact**: A violation through a single incident or series of actions. + +**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. + + +3. Temporary Ban +~~~~~~~~~~~~~~~~ + +**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. + + +4. Permanent Ban +~~~~~~~~~~~~~~~~ + +**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the community. + + +Attribution +----------- + +This Code of Conduct is adapted from the `Contributor Covenant `__, version 2.0, +available at https://www.contributor-covenant.org/version/2/0/code_of_conduct/. + +Community Impact Guidelines were inspired by `Mozilla’s code of conduct enforcement ladder `__. + +.. _homepage: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst new file mode 100644 index 0000000..3a8c91d --- /dev/null +++ b/CONTRIBUTING.rst @@ -0,0 +1,111 @@ +Contributor Guide +================= + +Thank you for your interest in improving this project. +This project is open-source under the `Apache 2.0 license`_ and +welcomes contributions in the form of bug reports, feature requests, and pull requests. + +Here is a list of important resources for contributors: + +- `Source Code`_ +- `Documentation`_ +- `Issue Tracker`_ +- `Code of Conduct`_ + +.. _Apache 2.0 license: https://opensource.org/licenses/Apache-2.0 +.. _Source Code: https://github.com/iterative/dvc-render +.. _Documentation: https://dvc-render.readthedocs.io/ +.. _Issue Tracker: https://github.com/iterative/dvc-render/issues + +How to report a bug +------------------- + +Report bugs on the `Issue Tracker`_. + +When filing an issue, make sure to answer these questions: + +- Which operating system and Python version are you using? +- Which version of this project are you using? +- What did you do? +- What did you expect to see? +- What did you see instead? + +The best way to get your bug fixed is to provide a test case, +and/or steps to reproduce the issue. + + +How to request a feature +------------------------ + +Request features on the `Issue Tracker`_. + + +How to set up your development environment +------------------------------------------ + +You need Python 3.7+ and the following tools: + +- Nox_ + +Install the package with development requirements: + +.. code:: console + + $ pip install nox + +.. _Nox: https://nox.thea.codes/ + + +How to test the project +----------------------- + +Run the full test suite: + +.. code:: console + + $ nox + +List the available Nox sessions: + +.. code:: console + + $ nox --list-sessions + +You can also run a specific Nox session. +For example, invoke the unit test suite like this: + +.. code:: console + + $ nox --session=tests + +Unit tests are located in the ``tests`` directory, +and are written using the pytest_ testing framework. + +.. _pytest: https://pytest.readthedocs.io/ + + +How to submit changes +--------------------- + +Open a `pull request`_ to submit changes to this project. + +Your pull request needs to meet the following guidelines for acceptance: + +- The Nox test suite must pass without errors and warnings. +- Include unit tests. This project maintains 100% code coverage. +- If your changes add functionality, update the documentation accordingly. + +Feel free to submit early, though—we can always iterate on this. + +To run linting and code formatting checks, you can invoke a `lint` session in nox: + +.. code:: console + + $ nox -s lint + +It is recommended to open an issue before starting work on anything. +This will allow a chance to talk it over with the owners and validate your approach. + +.. _pull request: https://github.com/iterative/dvc-render/pulls +.. github-only +.. _Code of Conduct: CODE_OF_CONDUCT.rst diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..6bc4e6e --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2022 Iterative. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..5e3ccc2 --- /dev/null +++ b/README.rst @@ -0,0 +1,86 @@ +DVC render +========== + +|PyPI| |Status| |Python Version| |License| + +|Tests| |Codecov| |pre-commit| |Black| + +.. |PyPI| image:: https://img.shields.io/pypi/v/dvc-render.svg + :target: https://pypi.org/project/dvc-render/ + :alt: PyPI +.. |Status| image:: https://img.shields.io/pypi/status/dvc-render.svg + :target: https://pypi.org/project/dvc-render/ + :alt: Status +.. |Python Version| image:: https://img.shields.io/pypi/pyversions/dvc-render + :target: https://pypi.org/project/dvc-render + :alt: Python Version +.. |License| image:: https://img.shields.io/pypi/l/dvc-render + :target: https://opensource.org/licenses/Apache-2.0 + :alt: License +.. |Tests| image:: https://github.com/iterative/dvc-render/workflows/Tests/badge.svg + :target: https://github.com/iterative/dvc-render/actions?workflow=Tests + :alt: Tests +.. |Codecov| image:: https://codecov.io/gh/iterative/dvc-render/branch/main/graph/badge.svg + :target: https://app.codecov.io/gh/iterative/dvc-render + :alt: Codecov +.. |pre-commit| image:: https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white + :target: https://github.com/pre-commit/pre-commit + :alt: pre-commit +.. |Black| image:: https://img.shields.io/badge/code%20style-black-000000.svg + :target: https://github.com/psf/black + :alt: Black + + +Features +-------- + +* TODO + + +Requirements +------------ + +* TODO + + +Installation +------------ + +You can install *DVC render* via pip_ from PyPI_: + +.. code:: console + + $ pip install dvc-render + + +Usage +----- + + +Contributing +------------ + +Contributions are very welcome. +To learn more, see the `Contributor Guide`_. + + +License +------- + +Distributed under the terms of the `Apache 2.0 license`_, +*DVC render* is free and open source software. + + +Issues +------ + +If you encounter any problems, +please `file an issue`_ along with a detailed description. + + +.. _Apache 2.0 license: https://opensource.org/licenses/Apache-2.0 +.. _PyPI: https://pypi.org/ +.. _file an issue: https://github.com/iterative/dvc-render/issues +.. _pip: https://pip.pypa.io/ +.. github-only +.. _Contributor Guide: CONTRIBUTING.rst diff --git a/dvc/render/__init__.py b/dvc/render/__init__.py deleted file mode 100644 index 0db4852..0000000 --- a/dvc/render/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -from .image import ImageRenderer -from .vega import VegaRenderer - -RENDERERS = [ImageRenderer, VegaRenderer] diff --git a/dvc/render/base.py b/dvc/render/base.py deleted file mode 100644 index d321384..0000000 --- a/dvc/render/base.py +++ /dev/null @@ -1,77 +0,0 @@ -import abc -from typing import TYPE_CHECKING, Dict - -from dvc.exceptions import DvcException - -if TYPE_CHECKING: - from dvc.types import StrPath - - -REVISION_FIELD = "rev" -INDEX_FIELD = "step" - - -class BadTemplateError(DvcException): - pass - - -class Renderer(abc.ABC): - REVISIONS_KEY = "revisions" - TYPE_KEY = "type" - - def __init__(self, data: Dict, **kwargs): - self.data = data - - from dvc.render.utils import get_files - - files = get_files(self.data) - - # we assume comparison of same file between revisions for now - assert len(files) == 1 - self.filename = files.pop() - - def partial_html(self, **kwargs): - """ - Us this method to generate partial HTML content, - that will fill self.DIV - """ - - raise NotImplementedError - - @property - @abc.abstractmethod - def TYPE(self): - raise NotImplementedError - - @property - @abc.abstractmethod - def DIV(self): - raise NotImplementedError - - @property - @abc.abstractmethod - def SCRIPTS(self): - raise NotImplementedError - - @abc.abstractmethod - def as_json(self, **kwargs): - raise NotImplementedError - - @staticmethod - def _remove_special_chars(string: str): - return string.translate( - {ord(c): "_" for c in r"!@#$%^&*()[]{};,<>?\/:.|`~=_+"} - ) - - @property - def needs_output_path(self): - return False - - def generate_html(self, path: "StrPath"): - """this method might edit content of path""" - partial = self.partial_html(path=path) - - div_id = self._remove_special_chars(self.filename) - div_id = f"plot_{div_id}" - - return self.DIV.format(id=div_id, partial=partial) diff --git a/dvc/render/data.py b/dvc/render/data.py deleted file mode 100644 index 5f45720..0000000 --- a/dvc/render/data.py +++ /dev/null @@ -1,194 +0,0 @@ -from copy import deepcopy -from functools import partial -from typing import Dict, List, Optional, Set, Union - -from funcy import first, project - -from dvc.exceptions import DvcException -from dvc.render.base import INDEX_FIELD, REVISION_FIELD - - -class FieldsNotFoundError(DvcException): - def __init__(self, expected_fields, found_fields): - expected_str = ", ".join(expected_fields) - found_str = ", ".join(found_fields) - super().__init__( - f"Could not find all provided fields ('{expected_str}') " - f"in data fields ('{found_str}')." - ) - - -class PlotDataStructureError(DvcException): - def __init__(self): - super().__init__( - "Plot data extraction failed. Please see " - "https://man.dvc.org/plots for supported data formats." - ) - - -def _filter_fields(datapoints: List[Dict], fields: Set) -> List[Dict]: - if not fields: - return datapoints - assert isinstance(fields, set) - - new_data = [] - for data_point in datapoints: - keys = set(data_point.keys()) - if not fields <= keys: - raise FieldsNotFoundError(fields, keys) - - new_data.append(project(data_point, fields)) - - return new_data - - -def _lists(dictionary: Dict): - for _, value in dictionary.items(): - if isinstance(value, dict): - yield from _lists(value) - elif isinstance(value, list): - yield value - - -def _find_first_list(data: Union[Dict, List], fields: Set) -> List[Dict]: - fields = fields or set() - - if not isinstance(data, dict): - return data - - for lst in _lists(data): - if ( - all(isinstance(dp, dict) for dp in lst) - # if fields is empty, it will match any set - and set(first(lst).keys()) & fields == fields - ): - return lst - - raise PlotDataStructureError() - - -def _append_index(datapoints: List[Dict]) -> List[Dict]: - if INDEX_FIELD in first(datapoints).keys(): - return datapoints - - for index, data_point in enumerate(datapoints): - data_point[INDEX_FIELD] = index - return datapoints - - -class Converter: - """ - Class that takes care of converting unspecified data blob - (Dict or List[Dict]) into datapoints (List[Dict]). - If some properties that are required by Template class are missing - ('x', 'y') it will attempt to fill in the blanks. - """ - - @staticmethod - def update(datapoints: List[Dict], update_dict: Dict): - for data_point in datapoints: - data_point.update(update_dict) - return datapoints - - def __init__(self, plot_properties: Optional[Dict] = None): - plot_properties = plot_properties or {} - self.props = deepcopy(plot_properties) - self.inferred_props: Dict = {} - - self.steps = [] - - self._infer_x() - self._infer_fields() - - self.steps.append( - ( - "find_data", - partial( - _find_first_list, - fields=self.inferred_props.get("fields", set()) - - {INDEX_FIELD}, - ), - ) - ) - - if not self.props.get("x", None): - self.steps.append(("append_index", partial(_append_index))) - - self.steps.append( - ( - "filter_fields", - partial( - _filter_fields, - fields=self.inferred_props.get("fields", set()), - ), - ) - ) - - def _infer_x(self): - if not self.props.get("x", None): - self.inferred_props["x"] = INDEX_FIELD - - def skip_step(self, name: str): - self.steps = [(_name, fn) for _name, fn in self.steps if _name != name] - - def _infer_fields(self): - fields = self.props.get("fields", set()) - if fields: - fields = { - *fields, - self.props.get("x", None), - self.props.get("y", None), - self.inferred_props.get("x", None), - } - {None} - self.inferred_props["fields"] = fields - - def _infer_y(self, datapoints: List[Dict]): - if "y" not in self.props: - data_fields = list(first(datapoints)) - skip = ( - REVISION_FIELD, - self.props.get("x", None) or self.inferred_props.get("x"), - ) - inferred_y = first( - f for f in reversed(data_fields) if f not in skip - ) - if "y" in self.inferred_props: - previous_y = self.inferred_props["y"] - if previous_y != inferred_y: - raise DvcException( - f"Inferred y ('{inferred_y}' value does not match" - f"previously matched one ('f{previous_y}')." - ) - else: - self.inferred_props["y"] = inferred_y - - def convert(self, data): - """ - Convert the data. Fill necessary fields ('x', 'y') and return both - generated datapoints and updated properties. - """ - processed = deepcopy(data) - - for _, step in self.steps: - processed = step(processed) - - self._infer_y(processed) - - return processed, {**self.props, **self.inferred_props} - - -def to_datapoints(data: Dict, props: Dict): - converter = Converter(props) - - datapoints = [] - for revision, rev_data in data.items(): - for _, file_data in rev_data.get("data", {}).items(): - if "data" in file_data: - processed, final_props = converter.convert( - file_data.get("data") - ) - - Converter.update(processed, {REVISION_FIELD: revision}) - - datapoints.extend(processed) - return datapoints, final_props diff --git a/dvc/render/image.py b/dvc/render/image.py deleted file mode 100644 index f7db589..0000000 --- a/dvc/render/image.py +++ /dev/null @@ -1,110 +0,0 @@ -import json -import os -from typing import TYPE_CHECKING - -from funcy import reraise - -from dvc.exceptions import DvcException -from dvc.render.base import Renderer -from dvc.render.utils import get_files -from dvc.utils import relpath - -if TYPE_CHECKING: - from dvc.types import StrPath - - -class ImageRenderer(Renderer): - TYPE = "image" - DIV = """ -
- {partial} -
""" - - SCRIPTS = "" - - @property - def needs_output_path(self): - return True - - def _write_image( - self, - path: "StrPath", - revision: str, - filename: str, - image_data: bytes, - ): - img_path = os.path.join( - path, f"{revision}_{filename.replace(os.sep, '_')}" - ) - with open(img_path, "wb") as fd: - fd.write(image_data) - - return img_path - - def _save_images(self, path: "StrPath"): - - for rev, rev_data in self.data.items(): - if "data" in rev_data: - for file, file_data in rev_data.get("data", {}).items(): - if "data" in file_data: - if not os.path.isdir(path): - os.makedirs(path, exist_ok=True) - yield rev, file, self._write_image( - os.path.abspath(path), rev, file, file_data["data"] - ) - - def partial_html(self, **kwargs): - path = kwargs.get("path", None) - if not path: - raise DvcException("Can't save here") - static = os.path.join(path, "static") - - div_content = [] - for rev, _, img_path in self._save_images(static): - div_content.append( - """ -
-

{title}

- -
""".format( - title=rev, src=(relpath(img_path, path)) - ) - ) - if div_content: - div_content.insert(0, f"

{self.filename}

") - return "\n".join(div_content) - return "" - - def as_json(self, **kwargs): - - with reraise( - KeyError, - DvcException( - f"{type(self).__name__} needs 'path' to store images." - ), - ): - path = kwargs["path"] - - results = [] - - for revision, _, img_path in self._save_images(path): - results.append( - { - self.TYPE_KEY: self.TYPE, - self.REVISIONS_KEY: [revision], - "url": img_path, - } - ) - - return json.dumps(results) - - @staticmethod - def matches(data): - files = get_files(data) - extensions = set(map(lambda f: os.path.splitext(f)[1], files)) - return extensions.issubset({".jpg", ".jpeg", ".gif", ".png"}) diff --git a/dvc/render/utils.py b/dvc/render/utils.py deleted file mode 100644 index a5bdc0a..0000000 --- a/dvc/render/utils.py +++ /dev/null @@ -1,75 +0,0 @@ -import os.path -from typing import Dict, List - -import dpath.util - - -def get_files(data: Dict) -> List: - files = set() - for rev in data.keys(): - for file in data[rev].get("data", {}).keys(): - files.add(file) - sorted_files = sorted(files) - return sorted_files - - -def group_by_filename(plots_data: Dict) -> List[Dict]: - files = get_files(plots_data) - grouped = [] - for file in files: - grouped.append(dpath.util.search(plots_data, ["*", "*", file])) - return grouped - - -def squash_plots_properties(data: Dict) -> Dict: - resolved: Dict[str, str] = {} - for rev_data in data.values(): - for file_data in rev_data.get("data", {}).values(): - props = file_data.get("props", {}) - resolved = {**resolved, **props} - return resolved - - -def match_renderers(plots_data, templates): - from dvc.render import RENDERERS - - renderers = [] - for group in group_by_filename(plots_data): - - plot_properties = squash_plots_properties(group) - template = templates.load(plot_properties.get("template", None)) - - for renderer_class in RENDERERS: - if renderer_class.matches(group): - renderers.append( - renderer_class( - group, template=template, properties=plot_properties - ) - ) - return renderers - - -def render( - repo, - renderers, - metrics=None, - path=None, - html_template_path=None, - refresh_seconds=None, -): - if not html_template_path: - html_template_path = repo.config.get("plots", {}).get( - "html_template", None - ) - if html_template_path and not os.path.isabs(html_template_path): - html_template_path = os.path.join(repo.dvc_dir, html_template_path) - - from dvc.render.html import write - - return write( - path, - renderers, - metrics=metrics, - template_path=html_template_path, - refresh_seconds=refresh_seconds, - ) diff --git a/dvc/render/vega.py b/dvc/render/vega.py deleted file mode 100644 index 75e7be8..0000000 --- a/dvc/render/vega.py +++ /dev/null @@ -1,108 +0,0 @@ -import json -import os -from copy import deepcopy -from typing import Dict, Optional - -from dvc.render.base import BadTemplateError, Renderer -from dvc.render.data import to_datapoints -from dvc.render.template import Template -from dvc.render.utils import get_files - - -class VegaRenderer(Renderer): - TYPE = "vega" - - DIV = """ -
- -
- """ - - SCRIPTS = """ - - - - """ - - def __init__( - self, data: Dict, template: Template, properties: Dict = None - ): - super().__init__(data) - self.properties = properties or {} - self.template = template - - def _revisions(self): - return list(self.data.keys()) - - def _fill_template(self, template, datapoints, props=None): - props = props or {} - - content = deepcopy(template.content) - if template.anchor_str("data") not in template.content: - anchor = template.anchor("data") - raise BadTemplateError( - f"Template '{template.name}' is not using '{anchor}' anchor" - ) - - if props.get("x"): - template.check_field_exists(datapoints, props.get("x")) - if props.get("y"): - template.check_field_exists(datapoints, props.get("y")) - - content = template.fill_anchor(content, "data", datapoints) - - props.setdefault("title", "") - props.setdefault("x_label", props.get("x")) - props.setdefault("y_label", props.get("y")) - - names = ["title", "x", "y", "x_label", "y_label"] - for name in names: - value = props.get(name) - if value is not None: - content = template.fill_anchor(content, name, value) - - return content - - def get_filled_template(self): - props = self.properties - datapoints, final_props = to_datapoints(self.data, props) - - if datapoints: - filled_template = self._fill_template( - self.template, datapoints, final_props - ) - - return filled_template - return None - - def asdict(self): - filled_template = self.get_filled_template() - if filled_template: - return json.loads(filled_template) - return {} - - def as_json(self, **kwargs) -> Optional[str]: - - content = self.asdict() - - return json.dumps( - [ - { - self.TYPE_KEY: self.TYPE, - self.REVISIONS_KEY: self._revisions(), - "content": content, - } - ], - ) - - def partial_html(self, **kwargs): - return self.get_filled_template() or "" - - @staticmethod - def matches(data): - files = get_files(data) - extensions = set(map(lambda f: os.path.splitext(f)[1], files)) - return extensions.issubset({".yml", ".yaml", ".json", ".csv", ".tsv"}) diff --git a/noxfile.py b/noxfile.py new file mode 100644 index 0000000..7c21af1 --- /dev/null +++ b/noxfile.py @@ -0,0 +1,62 @@ +"""Automation using nox.""" +import glob +import os + +import nox + +nox.options.reuse_existing_virtualenvs = True +nox.options.sessions = "lint", "tests" +locations = "src", "tests" + + +@nox.session(python=["3.7", "3.8", "3.9", "3.10"]) +def tests(session: nox.Session) -> None: + session.install(".[tests]") + session.run( + "pytest", + "--cov", + "--cov-config=pyproject.toml", + *session.posargs, + env={"COVERAGE_FILE": f".coverage.{session.python}"}, + ) + + +@nox.session +def lint(session: nox.Session) -> None: + session.install("pre-commit") + session.install("-e", ".[dev]") + + args = *(session.posargs or ("--show-diff-on-failure",)), "--all-files" + session.run("pre-commit", "run", *args) + session.run("python", "-m", "mypy") + session.run("python", "-m", "pylint", *locations) + + +@nox.session +def safety(session: nox.Session) -> None: + """Scan dependencies for insecure packages.""" + session.install(".[dev]") + session.install("safety") + session.run("safety", "check", "--full-report") + + +@nox.session +def build(session: nox.Session) -> None: + session.install("build", "setuptools", "twine") + session.run("python", "-m", "build") + dists = glob.glob("dist/*") + session.run("twine", "check", *dists, silent=True) + + +@nox.session +def dev(session: nox.Session) -> None: + """Sets up a python development environment for the project.""" + args = session.posargs or ("venv",) + venv_dir = os.fsdecode(os.path.abspath(args[0])) + + session.log(f"Setting up virtual environment in {venv_dir}") + session.install("virtualenv") + session.run("virtualenv", venv_dir, silent=True) + + python = os.path.join(venv_dir, "bin/python") + session.run(python, "-m", "pip", "install", "-e", ".[dev]", external=True) diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..f07b12f --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,70 @@ +[build-system] +requires = ["setuptools>=48", "wheel"] +build-backend = "setuptools.build_meta" + +[tool.black] +line-length = 79 +include = '\.pyi?$' +exclude = ''' +/( + \.eggs + | \.git + | \.hg + | \.mypy_cache + | \.tox + | \.venv + | _build + | buck-out + | build + | dist +)/ +''' + +[tool.isort] +profile = "black" +known_first_party = ["dvc_render"] +line_length = 79 + +[tool.pytest.ini_options] +addopts = "-ra" + +[tool.coverage.run] +branch = true +source = ["dvc_render", "tests"] + +[tool.coverage.paths] +source = ["src", "*/site-packages"] + +[tool.coverage.report] +show_missing = true +exclude_lines = [ + "pragma: no cover", + "if __name__ == .__main__.:", + "if typing.TYPE_CHECKING:", + "if TYPE_CHECKING:", + "raise NotImplementedError", + "raise AssertionError", + "@overload", +] + +[tool.mypy] +# Error output +show_column_numbers = true +show_error_codes = true +show_error_context = true +show_traceback = true +pretty = true +check_untyped_defs = false +# Warnings +warn_no_return = true +warn_redundant_casts = true +warn_unreachable = true +files = ["src", "tests"] + +[tool.pylint.message_control] +enable = ["c-extension-no-member", "no-else-return"] +disable = ["missing-module-docstring", "missing-class-docstring", "invalid-name", "R0801"] + +[tool.pylint.variables] +dummy-variables-rgx = "_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_" +ignored-argument-names = "_.*|^ignored_|^unused_|args|kwargs" diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..1220481 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,60 @@ +[metadata] +description = DVC render +name = dvc-render +version = 0.0.0 +long_description = file: README.rst +long_description_content_type = text/x-rst +license = Apache-2.0 +license_file = LICENSE +url = https://github.com/iterative/dvc-render +platforms=any +authors = Iterative +maintainer_email = support@dvc.org +classifiers = + Programming Language :: Python :: 3 + Programming Language :: Python :: 3.7 + Programming Language :: Python :: 3.8 + Programming Language :: Python :: 3.9 + Programming Language :: Python :: 3.10 + Development Status :: 1 - Planning + +[options] +python_requires = >=3.7 +zip_safe = False +package_dir= + =src +packages = find: +install_requires= + funcy>=1.17 + tabulate>=0.8.7 + +[options.extras_require] +tests = + pytest==6.2.5 + pytest-sugar==0.9.4 + pytest-cov==3.0.0 + pytest-mock==3.6.1 + pylint==2.12.2 + mypy==0.930 + pytest-test-utils>=0.0.6 +dev = + %(tests)s + +[options.packages.find] +exclude = + tests + tests.* +where=src + +[flake8] +ignore= + E203, # Whitespace before ':' + E266, # Too many leading '#' for block comment + W503, # Line break occurred before a binary operator + P1, # unindexed parameters in the str.format, see: + # https://pypi.org/project/flake8-string-format/ +max_line_length = 79 +max-complexity = 15 +select = B,C,E,F,W,T4,B902,T,P +show_source = true +count = true diff --git a/src/dvc_render/__init__.py b/src/dvc_render/__init__.py new file mode 100644 index 0000000..25ccd49 --- /dev/null +++ b/src/dvc_render/__init__.py @@ -0,0 +1,7 @@ +from .html import render_html # noqa: F401 +from .image import ImageRenderer +from .plotly import ParallelCoordinatesRenderer # noqa: F401 +from .vega import VegaRenderer +from .vega_templates import TEMPLATES # noqa: F401 + +RENDERERS = [ImageRenderer, VegaRenderer] diff --git a/src/dvc_render/base.py b/src/dvc_render/base.py new file mode 100644 index 0000000..55dd6ba --- /dev/null +++ b/src/dvc_render/base.py @@ -0,0 +1,65 @@ +import abc +from pathlib import Path +from typing import TYPE_CHECKING, Dict, Iterable, Union + +if TYPE_CHECKING: + from os import PathLike + +StrPath = Union[str, "PathLike[str]"] + + +class Renderer(abc.ABC): + + DIV = """ +
+ {partial} +
+ """ + + EXTENSIONS: Iterable[str] = {} + + def __init__(self, datapoints: Dict, name: str, **properties): + self.datapoints = datapoints + self.name = name + self.properties = properties + + @abc.abstractmethod + def partial_html(self) -> str: + """ + Us this method to generate HTML content, + to fill `{partial}` inside self.DIV. + """ + raise NotImplementedError + + @property + @abc.abstractmethod + def TYPE(self): # pylint: disable=missing-function-docstring + raise NotImplementedError + + @property + @abc.abstractmethod + def SCRIPTS(self): # pylint: disable=missing-function-docstring + raise NotImplementedError + + @staticmethod + def remove_special_chars(string: str) -> str: + "Ensure string is valid HTML id." + return string.translate( + {ord(c): "_" for c in r"!@#$%^&*()[]{};,<>?\/:.|`~=_+"} + ) + + def generate_html(self) -> str: + "Return `DIV` formatted with `partial_html`." + partial = self.partial_html() + + div_id = self.remove_special_chars(self.name) + div_id = f"plot_{div_id}" + + return self.DIV.format(id=div_id, partial=partial) + + @classmethod + def matches( + cls, filename, properties # pylint: disable=unused-argument + ) -> bool: + "Check if the Renderer is suitable." + return Path(filename).suffix in cls.EXTENSIONS diff --git a/src/dvc_render/exceptions.py b/src/dvc_render/exceptions.py new file mode 100644 index 0000000..ea65729 --- /dev/null +++ b/src/dvc_render/exceptions.py @@ -0,0 +1,2 @@ +class DvcRenderException(Exception): + pass diff --git a/dvc/render/html.py b/src/dvc_render/html.py similarity index 83% rename from dvc/render/html.py rename to src/dvc_render/html.py index 89da967..578c104 100644 --- a/dvc/render/html.py +++ b/src/dvc_render/html.py @@ -2,11 +2,13 @@ from pathlib import Path from typing import TYPE_CHECKING, Dict, List, Optional -from dvc.exceptions import DvcException +import tabulate # type: ignore + +from .exceptions import DvcRenderException if TYPE_CHECKING: - from dvc.render.base import Renderer - from dvc.types import StrPath + from .base import Renderer, StrPath + PAGE_HTML = """ @@ -21,7 +23,7 @@ """ -class MissingPlaceholderError(DvcException): +class MissingPlaceholderError(DvcRenderException): def __init__(self, placeholder): super().__init__(f"HTML template has to contain '{placeholder}'.") @@ -50,8 +52,7 @@ def __init__( self.refresh_tag = self.REFRESH_TAG.format(refresh_seconds) def with_metrics(self, metrics: Dict[str, Dict]) -> "HTML": - import tabulate - + "Adds metrics element." header: List[str] = [] rows: List[List[str]] = [] @@ -66,15 +67,18 @@ def with_metrics(self, metrics: Dict[str, Dict]) -> "HTML": return self def with_scripts(self, scripts: str) -> "HTML": + "Extend scripts element." if scripts not in self.scripts: self.scripts += f"\n{scripts}" return self def with_element(self, html: str) -> "HTML": + "Adds custom html element." self.elements.append(html) return self def embed(self) -> str: + "Format HTML template with all elements." kwargs = { self.SCRIPTS_PLACEHOLDER: self.scripts, self.PLOTS_PLACEHOLDER: "\n".join(self.elements), @@ -83,14 +87,14 @@ def embed(self) -> str: return self.template.format(**kwargs) -def write( - path: "StrPath", +def render_html( renderers: List["Renderer"], + path: "StrPath", metrics: Optional[Dict[str, Dict]] = None, template_path: Optional["StrPath"] = None, refresh_seconds: Optional[int] = None, -): - +) -> "StrPath": + "User renderers to fill an HTML template and write to path." os.makedirs(path, exist_ok=True) page_html = None @@ -105,10 +109,10 @@ def write( for renderer in renderers: document.with_scripts(renderer.SCRIPTS) - document.with_element(renderer.generate_html(path)) + document.with_element(renderer.generate_html()) index = Path(os.path.join(path, "index.html")) - with open(index, "w", encoding="utf-8") as fd: - fd.write(document.embed()) + with open(index, "w", encoding="utf-8") as f: + f.write(document.embed()) return index diff --git a/src/dvc_render/image.py b/src/dvc_render/image.py new file mode 100644 index 0000000..fe84db5 --- /dev/null +++ b/src/dvc_render/image.py @@ -0,0 +1,38 @@ +from .base import Renderer + + +class ImageRenderer(Renderer): + TYPE = "image" + DIV = """ +
+ {partial} +
""" + + TITLE_FIELD = "rev" + SRC_FIELD = "src" + + SCRIPTS = "" + + EXTENSIONS = {".jpg", ".jpeg", ".gif", ".png"} + + def partial_html(self) -> str: + div_content = [] + for datapoint in self.datapoints: + div_content.append( + f""" +
+

{datapoint[self.TITLE_FIELD]}

+ +
+ """ + ) + if div_content: + div_content.insert(0, f"

{self.name}

") + return "\n".join(div_content) + return "" diff --git a/dvc/render/plotly.py b/src/dvc_render/plotly.py similarity index 84% rename from dvc/render/plotly.py rename to src/dvc_render/plotly.py index 8092e18..93a6b2f 100644 --- a/dvc/render/plotly.py +++ b/src/dvc_render/plotly.py @@ -1,11 +1,8 @@ import json from collections import defaultdict -from typing import TYPE_CHECKING, Any, Dict, Optional +from typing import Any, Dict, Optional -from dvc.render.base import Renderer - -if TYPE_CHECKING: - from dvc.compare import TabularData +from .base import Renderer class ParallelCoordinatesRenderer(Renderer): @@ -20,6 +17,8 @@ class ParallelCoordinatesRenderer(Renderer): """ + EXTENSIONS = {".json"} + SCRIPTS = """ """ @@ -27,21 +26,22 @@ class ParallelCoordinatesRenderer(Renderer): # pylint: disable=W0231 def __init__( self, - tabular_data: "TabularData", + datapoints, + name="pcp", color_by: Optional[str] = None, fill_value: str = "", ): - self.tabular_data = tabular_data + self.datapoints = datapoints self.color_by = color_by - self.filename = "experiments" + self.name = name self.fill_value = fill_value - def partial_html(self, **kwargs): - return self.as_json() + def partial_html(self) -> str: + return json.dumps(self._get_plotly_data()) - def as_json(self, **kwargs) -> str: + def _get_plotly_data(self): tabular_dict = defaultdict(list) - for row in self.tabular_data.as_dict(): + for row in self.datapoints: for col_name, value in row.items(): tabular_dict[col_name].append(str(value)) @@ -89,4 +89,4 @@ def as_json(self, **kwargs) -> str: trace["line"]["colorbar"]["tickvals"] = dummy_values trace["line"]["colorbar"]["ticktext"] = values - return json.dumps({"data": [trace], "layout": {}}) + return {"data": [trace], "layout": {}} diff --git a/src/dvc_render/vega.py b/src/dvc_render/vega.py new file mode 100644 index 0000000..46a6b08 --- /dev/null +++ b/src/dvc_render/vega.py @@ -0,0 +1,69 @@ +from copy import deepcopy +from typing import Dict + +from .base import Renderer +from .exceptions import DvcRenderException +from .vega_templates import get_template + + +class BadTemplateError(DvcRenderException): + pass + + +class VegaRenderer(Renderer): + TYPE = "vega" + + DIV = """ +
+ +
+ """ + + SCRIPTS = """ + + + + """ + + EXTENSIONS = {".yml", ".yaml", ".json", ".csv", ".tsv"} + + def __init__(self, datapoints: Dict, name: str, **properties): + super().__init__(datapoints, name, **properties) + self.template = get_template( + self.properties.get("template", None), + self.properties.get("template_dir", None), + ) + + def partial_html(self) -> str: + content = deepcopy(self.template.content) + if self.template.anchor_str("data") not in self.template.content: + anchor = self.template.anchor("data") + raise BadTemplateError( + f"Template '{self.template.name}' " + f"is not using '{anchor}' anchor" + ) + + if self.properties.get("x"): + self.template.check_field_exists( + self.datapoints, self.properties.get("x") + ) + if self.properties.get("y"): + self.template.check_field_exists( + self.datapoints, self.properties.get("y") + ) + + content = self.template.fill_anchor(content, "data", self.datapoints) + + self.properties.setdefault("title", "") + self.properties.setdefault("x_label", self.properties.get("x")) + self.properties.setdefault("y_label", self.properties.get("y")) + + names = ["title", "x", "y", "x_label", "y_label"] + for name in names: + value = self.properties.get(name) + if value is not None: + content = self.template.fill_anchor(content, name, value) + return content diff --git a/dvc/render/template.py b/src/dvc_render/vega_templates.py similarity index 84% rename from dvc/render/template.py rename to src/dvc_render/vega_templates.py index e8b8509..0e462d3 100644 --- a/dvc/render/template.py +++ b/src/dvc_render/vega_templates.py @@ -1,25 +1,26 @@ import json -import os -from typing import Any, Dict, List, Optional +from pathlib import Path +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union -from funcy import cached_property +from .exceptions import DvcRenderException -from dvc.exceptions import DvcException +if TYPE_CHECKING: + from .base import StrPath -class TemplateNotFoundError(DvcException): +class TemplateNotFoundError(DvcRenderException): def __init__(self, path): super().__init__(f"Template '{path}' not found.") -class NoFieldInDataError(DvcException): +class NoFieldInDataError(DvcRenderException): def __init__(self, field_name): super().__init__( f"Field '{field_name}' does not exist in provided data." ) -class TemplateContentDoesNotMatch(DvcException): +class TemplateContentDoesNotMatch(DvcRenderException): def __init__(self, template_name: str, path: str): super().__init__( f"Template '{path}' already exists " @@ -56,24 +57,29 @@ def __init__(self, content=None, name=None): @classmethod def anchor(cls, name): + "Get ANCHOR formatted with name." return cls.ANCHOR.format(name.upper()) - def has_anchor(self, name): + def has_anchor(self, name) -> bool: + "Check if ANCHOR formatted with name is in content." return self.anchor_str(name) in self.content @classmethod - def fill_anchor(cls, content, name, value): + def fill_anchor(cls, content, name, value) -> str: + "Replace anchor `name` with `value` in content." value_str = json.dumps( value, indent=cls.INDENT, separators=cls.SEPARATORS, sort_keys=True ) return content.replace(cls.anchor_str(name), value_str) @classmethod - def anchor_str(cls, name): + def anchor_str(cls, name) -> str: + "Get string wrapping ANCHOR formatted with name." return f'"{cls.anchor(name)}"' @staticmethod def check_field_exists(data, field): + "Raise NoFieldInDataError if `field` not in `data`." if not any(field in row for row in data): raise NoFieldInDataError(field) @@ -499,97 +505,87 @@ class LinearTemplate(Template): } -class PlotTemplates: - TEMPLATES_DIR = "plots" - TEMPLATES = [ - SimpleLinearTemplate, - LinearTemplate, - ConfusionTemplate, - NormalizedConfusionTemplate, - ScatterTemplate, - SmoothLinearTemplate, - ] - - @cached_property - def templates_dir(self): - return os.path.join(self.dvc_dir, self.TEMPLATES_DIR) - - def get_template(self, template_name: str): - template_path = os.path.abspath(template_name) - if os.path.exists(template_path): - return os.path.abspath(template_path) - - if self.dvc_dir and os.path.exists(self.dvc_dir): - template_path = os.path.join(self.templates_dir, template_name) - if os.path.exists(template_path): - return template_path - - all_templates = [ - os.path.join(root, file) - for root, _, files in os.walk(self.templates_dir) - for file in files - ] - matches = [ - template - for template in all_templates - if os.path.splitext(template)[0] == template_path - ] - if matches: - assert len(matches) == 1 - return matches[0] - raise TemplateNotFoundError(template_name) - - def __init__(self, dvc_dir): - self.dvc_dir = dvc_dir - - def init( - self, output: Optional[str] = None, targets: Optional[List] = None - ): - from dvc.utils.fs import makedirs - - output = output or self.templates_dir - - makedirs(output, exist_ok=True) - - if targets: - templates = [ - template - for template in self.TEMPLATES - if template.DEFAULT_NAME in targets - ] - else: - templates = self.TEMPLATES - - for template in templates: - self._dump(template(), output) - - def _dump(self, template: Template, output: str): - path = os.path.join(output, template.filename) - - if os.path.exists(path): - with open(path, "r", encoding="utf-8") as fd: - content = fd.read() +TEMPLATES = [ + SimpleLinearTemplate, + LinearTemplate, + ConfusionTemplate, + NormalizedConfusionTemplate, + ScatterTemplate, + SmoothLinearTemplate, +] + + +def _find_template( + template_name: str, template_dir: Optional[str] = None +) -> Optional["StrPath"]: + if template_dir: + for template_path in Path(template_dir).rglob(f"{template_name}*"): + return template_path + + template_path = Path(template_name).with_suffix(".json") + template_path = template_path.resolve() + if template_path.exists(): + return template_path.resolve() + + return None + + +def get_template( + template: Union[Optional[str], Template] = None, + template_dir: Optional[str] = None, +) -> Template: + """Return template instance based on given template arg. + + If template is already an instance, return it. + If template is None, return default `linear` template. + If template is a path, will try to find it as absolute + path or inside template_dir. + If template matches one of the DEFAULT_NAMEs in TEMPLATES, + return an instance of the one matching. + """ + if isinstance(template, Template): + return template + + if template is None: + template = "linear" + + template_path = _find_template(template, template_dir) + + if template_path: + with open(template_path, "r", encoding="utf-8") as f: + content = f.read() + return Template(content, name=template) + + for template_cls in TEMPLATES: + if template_cls.DEFAULT_NAME == template: + return template_cls() + + raise TemplateNotFoundError(template) + + +def dump_templates(output: "StrPath", targets: Optional[List] = None) -> None: + "Write TEMPLATES in `.json` format to `output`." + output = Path(output) + output.mkdir(exist_ok=True) + + if targets: + templates = [ + template + for template in TEMPLATES + if template.DEFAULT_NAME in targets + ] + else: + templates = TEMPLATES + + for template_cls in templates: + template = template_cls() + path = output / template.filename + + if path.exists(): + content = path.read_text(encoding="utf-8") if content != template.content: raise TemplateContentDoesNotMatch( template.DEFAULT_NAME or "", path ) else: - with open(path, "w", encoding="utf-8") as fd: - fd.write(template.content) - - def load(self, template_name=None): - if not template_name: - template_name = "linear" - - try: - path = self.get_template(template_name) - - with open(path, "r", encoding="utf-8") as fd: - content = fd.read() - - return Template(content, name=template_name) - except TemplateNotFoundError: - for template in self.TEMPLATES: - if template.DEFAULT_NAME == template_name: - return template() - raise + path.write_text(template.content, encoding="utf-8") diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_html.py b/tests/test_html.py new file mode 100644 index 0000000..591f576 --- /dev/null +++ b/tests/test_html.py @@ -0,0 +1,50 @@ +import pytest + +from dvc_render.html import HTML, PAGE_HTML, MissingPlaceholderError + +# pylint: disable=missing-function-docstring, R0801 + + +CUSTOM_PAGE_HTML = """ + + + TITLE + + + + + + {plot_divs} + +""" + + +@pytest.mark.parametrize( + "template,page_elements,expected_page", + [ + ( + None, + ["content"], + PAGE_HTML.format(plot_divs="content", refresh_tag="", scripts=""), + ), + ( + CUSTOM_PAGE_HTML, + ["content"], + CUSTOM_PAGE_HTML.format(plot_divs="content"), + ), + ], +) +def test_html(template, page_elements, expected_page): + page = HTML(template) + page.elements = page_elements + + result = page.embed() + + assert result == expected_page + + +def test_no_placeholder(): + template = "" + + with pytest.raises(MissingPlaceholderError): + HTML(template) diff --git a/tests/test_image.py b/tests/test_image.py new file mode 100644 index 0000000..444db60 --- /dev/null +++ b/tests/test_image.py @@ -0,0 +1,40 @@ +import pytest + +from dvc_render.image import ImageRenderer + +# pylint: disable=missing-function-docstring + + +@pytest.mark.parametrize( + "extension, matches", + ( + (".csv", False), + (".json", False), + (".tsv", False), + (".yaml", False), + (".jpg", True), + (".gif", True), + (".jpeg", True), + (".png", True), + ), +) +def test_matches(extension, matches): + filename = "file" + extension + assert ImageRenderer.matches(filename, {}) == matches + + +def test_render(tmp_dir): + tmp_dir.gen("workspace_file.jpg", b"content") + + datapoints = [ + { + "filename": "file.jpg", + "rev": "workspace", + "src": "workspace_file.jpg", + } + ] + + html = ImageRenderer(datapoints, "file.jpg").generate_html() + + assert "

file.jpg

" in html + assert '' in html diff --git a/tests/test_parallel_coordinates.py b/tests/test_parallel_coordinates.py new file mode 100644 index 0000000..6bea8b2 --- /dev/null +++ b/tests/test_parallel_coordinates.py @@ -0,0 +1,170 @@ +import json + +from dvc_render.html import render_html +from dvc_render.plotly import ParallelCoordinatesRenderer + +# pylint: disable=missing-function-docstring, unspecified-encoding + + +def expected_format(result): + assert "data" in result + assert "layout" in result + assert isinstance(result["data"], list) + assert result["data"][0]["type"] == "parcoords" + assert isinstance(result["data"][0]["dimensions"], list) + return True + + +def test_scalar_columns(): + datapoints = [ + {"col-1": "0.1", "col-2": "1", "col-3": ""}, + {"col-1": "2", "col-2": "0.2", "col-3": "0"}, + ] + renderer = ParallelCoordinatesRenderer(datapoints) + + result = json.loads(renderer.partial_html()) + + assert expected_format(result) + + assert result["data"][0]["dimensions"][0] == { + "label": "col-1", + "values": [0.1, 2.0], + } + assert result["data"][0]["dimensions"][1] == { + "label": "col-2", + "values": [1.0, 0.2], + } + assert result["data"][0]["dimensions"][2] == { + "label": "col-3", + "values": [None, 0], + } + + +def test_categorical_columns(): + datapoints = [ + {"col-1": "foo", "col-2": ""}, + {"col-1": "bar", "col-2": "foobar"}, + {"col-1": "foo", "col-2": ""}, + ] + renderer = ParallelCoordinatesRenderer(datapoints) + + result = json.loads(renderer.partial_html()) + + assert expected_format(result) + + assert result["data"][0]["dimensions"][0] == { + "label": "col-1", + "values": [1, 0, 1], + "tickvals": [1, 0, 1], + "ticktext": ["foo", "bar", "foo"], + } + assert result["data"][0]["dimensions"][1] == { + "label": "col-2", + "values": [1, 0, 1], + "tickvals": [1, 0, 1], + "ticktext": ["Missing", "foobar", "Missing"], + } + + +def test_mixed_columns(): + datapoints = [ + {"categorical": "foo", "scalar": "0.1"}, + {"categorical": "bar", "scalar": "2"}, + ] + renderer = ParallelCoordinatesRenderer(datapoints) + + result = json.loads(renderer.partial_html()) + + assert expected_format(result) + + assert result["data"][0]["dimensions"][0] == { + "label": "categorical", + "values": [1, 0], + "tickvals": [1, 0], + "ticktext": ["foo", "bar"], + } + assert result["data"][0]["dimensions"][1] == { + "label": "scalar", + "values": [0.1, 2.0], + } + + +def test_color_by_scalar(): + datapoints = [ + {"categorical": "foo", "scalar": "0.1"}, + {"categorical": "bar", "scalar": "2"}, + ] + renderer = ParallelCoordinatesRenderer(datapoints, color_by="scalar") + + result = json.loads(renderer.partial_html()) + + assert expected_format(result) + assert result["data"][0]["line"] == { + "color": [0.1, 2.0], + "showscale": True, + "colorbar": {"title": "scalar"}, + } + + +def test_color_by_categorical(): + datapoints = [ + {"categorical": "foo", "scalar": "0.1"}, + {"categorical": "bar", "scalar": "2"}, + ] + renderer = ParallelCoordinatesRenderer(datapoints, color_by="categorical") + + result = json.loads(renderer.partial_html()) + + assert expected_format(result) + assert result["data"][0]["line"] == { + "color": [1, 0], + "showscale": True, + "colorbar": { + "title": "categorical", + "tickmode": "array", + "tickvals": [1, 0], + "ticktext": ["foo", "bar"], + }, + } + + +def test_write_parallel_coordinates(tmp_dir): + datapoints = [ + {"categorical": "foo", "scalar": "0.1"}, + {"categorical": "bar", "scalar": "2"}, + ] + + renderer = ParallelCoordinatesRenderer(datapoints) + html_path = render_html(renderers=[renderer], path=tmp_dir) + + html_text = html_path.read_text() + + assert ParallelCoordinatesRenderer.SCRIPTS in html_text + + div = ParallelCoordinatesRenderer.DIV.format( + id="plot_pcp", partial=renderer.partial_html() + ) + assert div in html_text + + +def test_fill_value(): + datapoints = [ + {"categorical": "foo", "scalar": "-"}, + {"categorical": "-", "scalar": "2"}, + ] + renderer = ParallelCoordinatesRenderer(datapoints, fill_value="-") + + result = json.loads(renderer.partial_html()) + + assert expected_format(result) + + assert result["data"][0]["dimensions"][0] == { + "label": "categorical", + "values": [0, 1], + "tickvals": [0, 1], + "ticktext": ["foo", "Missing"], + } + assert result["data"][0]["dimensions"][1] == { + "label": "scalar", + "values": [None, 2.0], + } diff --git a/tests/test_renderer.py b/tests/test_renderer.py new file mode 100644 index 0000000..60ba513 --- /dev/null +++ b/tests/test_renderer.py @@ -0,0 +1,11 @@ +from dvc_render.base import Renderer + +# pylint: disable=missing-function-docstring + + +def test_remove_special_characters(): + special_chars = r"!@#$%^&*()[]{};,<>?\/:.|`~=_+" + dirty = f"plot_name{special_chars}" + assert Renderer.remove_special_chars(dirty) == "plot_name" + "_" * len( + special_chars + ) diff --git a/tests/test_templates.py b/tests/test_templates.py new file mode 100644 index 0000000..77f9e07 --- /dev/null +++ b/tests/test_templates.py @@ -0,0 +1,73 @@ +import os + +import pytest + +from dvc_render.vega_templates import ( + TEMPLATES, + LinearTemplate, + ScatterTemplate, + TemplateContentDoesNotMatch, + TemplateNotFoundError, + dump_templates, + get_template, +) + +# pylint: disable=missing-function-docstring, unused-argument + + +def test_raise_on_no_template(): + with pytest.raises(TemplateNotFoundError): + get_template("non_existing_template.json") + + +@pytest.mark.parametrize( + "template_path, target_name", + [ + (os.path.join(".dvc", "plots", "template.json"), "template"), + (os.path.join(".dvc", "plots", "template.json"), "template.json"), + ( + os.path.join(".dvc", "plots", "subdir", "template.json"), + os.path.join("subdir", "template.json"), + ), + ( + os.path.join(".dvc", "plots", "subdir", "template.json"), + os.path.join("subdir", "template"), + ), + ("template.json", "template.json"), + ], +) +def test_get_template(tmp_dir, template_path, target_name): + tmp_dir.gen(template_path, "template_content") + assert ( + get_template(target_name, ".dvc/plots").content == "template_content" + ) + + +def test_get_default_template(): + assert get_template(None).content == LinearTemplate().content + + +@pytest.mark.parametrize( + "targets,expected_templates", + ( + ([None, TEMPLATES]), + (["linear", "scatter"], [ScatterTemplate, LinearTemplate]), + ), +) +def test_init(tmp_dir, targets, expected_templates): + output = "plots" + dump_templates(output, targets) + + assert set(os.listdir(output)) == { + cls.DEFAULT_NAME + ".json" for cls in expected_templates + } + + +def test_raise_on_init_modified(tmp_dir): + dump_templates(output=".", targets=["linear"]) + + with open(tmp_dir / "linear.json", "a", encoding="utf-8") as fd: + fd.write("modification") + + with pytest.raises(TemplateContentDoesNotMatch): + dump_templates(output=".", targets=["linear"]) diff --git a/tests/test_vega.py b/tests/test_vega.py new file mode 100644 index 0000000..b95564d --- /dev/null +++ b/tests/test_vega.py @@ -0,0 +1,95 @@ +import json + +import pytest +from funcy import first # type: ignore + +from dvc_render.vega import BadTemplateError, VegaRenderer +from dvc_render.vega_templates import NoFieldInDataError, Template + +# pylint: disable=missing-function-docstring + + +def test_choose_axes(): + props = {"x": "first_val", "y": "second_val"} + datapoints = [ + {"first_val": 100, "second_val": 100, "val": 2}, + {"first_val": 200, "second_val": 300, "val": 3}, + ] + + plot_content = json.loads( + VegaRenderer(datapoints, "foo", **props).partial_html() + ) + + assert plot_content["data"]["values"] == [ + { + "val": 2, + "first_val": 100, + "second_val": 100, + }, + { + "val": 3, + "first_val": 200, + "second_val": 300, + }, + ] + assert ( + first(plot_content["layer"])["encoding"]["x"]["field"] == "first_val" + ) + assert ( + first(plot_content["layer"])["encoding"]["y"]["field"] == "second_val" + ) + + +def test_confusion(): + datapoints = [ + {"predicted": "B", "actual": "A"}, + {"predicted": "A", "actual": "A"}, + ] + props = {"template": "confusion", "x": "predicted", "y": "actual"} + + plot_content = json.loads( + VegaRenderer(datapoints, "foo", **props).partial_html() + ) + + assert plot_content["data"]["values"] == [ + {"predicted": "B", "actual": "A"}, + {"predicted": "A", "actual": "A"}, + ] + assert plot_content["spec"]["transform"][0]["groupby"] == [ + "actual", + "predicted", + ] + assert plot_content["spec"]["encoding"]["x"]["field"] == "predicted" + assert plot_content["spec"]["encoding"]["y"]["field"] == "actual" + + +def test_bad_template(): + datapoints = [{"val": 2}, {"val": 3}] + props = {"template": Template("name", "content")} + with pytest.raises(BadTemplateError): + VegaRenderer(datapoints, "foo", **props).partial_html() + + +def test_raise_on_wrong_field(): + datapoints = [{"val": 2}, {"val": 3}] + props = {"x": "no_val"} + + with pytest.raises(NoFieldInDataError): + VegaRenderer(datapoints, "foo", **props).partial_html() + + +@pytest.mark.parametrize( + "extension, matches", + ( + (".csv", True), + (".json", True), + (".tsv", True), + (".yaml", True), + (".jpg", False), + (".gif", False), + (".jpeg", False), + (".png", False), + ), +) +def test_matches(extension, matches): + assert VegaRenderer.matches("file" + extension, {}) == matches