├── .gitignore ├── .travis.yml ├── CONTRIBUTING.md ├── LICENSE ├── MANIFEST.in ├── README.md ├── docs ├── Makefile ├── make.bat └── source │ ├── api.rst │ ├── conf.py │ ├── index.rst │ ├── oblib.tests.rst │ ├── overview.rst │ └── pyoblib.png ├── oblib ├── __init__.py ├── constants.py ├── data_model.py ├── identifier.py ├── ob.py ├── parser.py ├── taxonomy.py ├── taxonomy_loader.py ├── tests │ ├── __init__.py │ ├── test_data_model.py │ ├── test_identifier.py │ ├── test_json_clips.py │ ├── test_ob.py │ ├── test_parser.py │ ├── test_taxonomy.py │ ├── test_util.py │ └── test_validator.py ├── util.py └── validator.py ├── requirements.txt ├── scripts ├── cli.sh ├── cli │ └── cli.py ├── dist-cli.sh ├── setup-dev.sh ├── tests-cli.sh └── tests.sh └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Bytecode Files 2 | __pycache__ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # OB Taxonomy Files 7 | solar-taxonomy 8 | 9 | # Build files from docs 10 | docs/build/ 11 | 12 | # OS Generated Files 13 | .DS_Store 14 | 15 | # IDE Config Files 16 | .idea 17 | 18 | # Coverage reports 19 | .coverage 20 | 21 | # Distribution Files 22 | build/ 23 | dist/ 24 | *.egg-info/ 25 | dist-cli/ 26 | .pytest_cache 27 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | 3 | python: 4 | - 3.6 5 | - 3.7 6 | - 3.8 7 | 8 | before_install: 9 | - scripts/setup-dev.sh 10 | - pip install -U pip 11 | - python setup.py install 12 | 13 | script: 14 | - scripts/tests.sh; 15 | - scripts/tests-cli.sh 16 | 17 | after_success: 18 | - bash <(curl -s https://codecov.io/bash) 19 | 20 | notifications: 21 | slack: 22 | secure: jRNXi8OwiiMdsY0rNuWLA194/NICXtljInimE1WiZYxGQ6PMU69X350QsVEs/eX8BpRw5KbFr3ssPf3I1cbtEIMWwUnWQ1M4gk/uGUQ2GIoYUwo9wX6fwH+R3Ooj7JFIZvHsGDVU6nwQM49Uq5BXJ8ce7WjXqThbPuLHHZgmfWPF3hySyOpp9KpqsR/ZnN02708Q4OR+DVlm75TsjVfyBiA61aUFYSpKn0k+AkpQp0/6F2jDrOJVUAbtNcXdY7tOCVjagpEQjy8R46y9BQF27Cqay/VS7zIsvbTDSb2L6fAdHuuigQx8pLC9VBWHDqkKBWbde/Rm6rwVW6LpXANg0+SRUbgBUL0rhRRJ/e7oas55aMRLmUKmTEhKt9kzl4QzksQbm2UJyOc0YxqqivMPxlHp/hKeOQ2Ald94iALJ1qCns3ZBZdbC8Eai6DLhimGywuzNAd7CSZyXQcI9sAnpd0UNZQQchB03VcuaaSm8hedzlztBy1EAReymKJiyWTZJEsm7jGIDsKtKLYVBjs6bq9r8ikRuU+bcX7tcL7XpVcW6qALBTD2yJZbqfcJohp/mJfptcXWDPxCihOyROTOH7l27kucUDQWGq5/xhZaPOQMC0Dv7X7QT54ytsNxT6rRPkmTO3djZIo6DKDA9dYBLbMGJvhrzbjtykoY21P3H+cM= 23 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | Thank you for considering contributing to pyoblib. It's people like you that make pyoblib such a great library. 4 | 5 | There are many ways in which you can contribute. A contribution may be 6 | * writing code which can be incorporated into pyoblib 7 | * improving the documentation 8 | * submitting bug reports and feature requests 9 | 10 | # Ground Rules 11 | 12 | pyoblib contains core source code that may be used by other Orange Button code. By definition, the functionality in 13 | this library should be consumable by multiple other Orange Button projects. If the functionality is only usable in a 14 | single instance it should be placed in another project. 15 | 16 | Source code in Orange Button Core must: 17 | 18 | * Be fully commented 19 | * Contain comprehensive test coverage 20 | * Subject to vulnerability scan 21 | 22 | # Getting started 23 | 24 | You must sign the SunSpec Contributor License Agreement before enhancing the source code or the documentation. 25 | Please see the instructions on how to submit a signed CLA on the [Orange Button Open Source Community web page](https://sunspec.org/ob-open-source-community/). 26 | 27 | Also, please email support@sunspec.org or post a message on the [Orange Button Slack Channel](https://orange-button.slack.com/) 28 | so we are aware of your intent to contribute. 29 | 30 | For all changes follow the procedure documented at the bottom of the 31 | [Orange Button Open Source Community web page](https://sunspec.org/ob-open-source-community/). 32 | 33 | ## Your First Contribution 34 | 35 | Unsure where to begin? Please enquire on our [Slack Channel](https://orange-button.slack.com/). 36 | 37 | ### Writing tests 38 | 39 | All public member functions should have a corresponding test located in a test file in oblib/tests with "test_" being 40 | prefixed before the function name. Whenever a new function or method is written please write a test. Also whenever an 41 | issue is identified add additional tests so that the issue can be fixed and the issue will not re-occur. Private member 42 | function tests are optional although in some cases they may be needed to fix issues. 43 | 44 | The CLI tests only test that the CLI completes and returns exit status 0 (success). The CLI tests do not test the 45 | functionality of the CLI. This should be sufficient since the functionality is already covered in the Python Test cases. 46 | 47 | ### Code style 48 | 49 | The project style guide is [PEP8](https://www.python.org/dev/peps/pep-0008/). Flake8 is a useful tool to test whether 50 | the PEP8 standard has been met (although this testing has not been automated yet). 51 | 52 | Docstrings follow the [Google Style Guide](https://github.com/google/styleguide/blob/gh-pages/pyguide.md) which also 53 | has additional guidance for coding above and beyond PEP8. 54 | 55 | ## How to report a bug 56 | 57 | Please use [GitHub Issues](https://github.com/SunSpecOrangeButton/pyoblib/issues) for all bug reports. 58 | If you find a security vulnerability, do NOT open an issue. Email support@sunspec.org instead. 59 | 60 | ## How to suggest a feature or enhancement 61 | 62 | Please use the [Orange Button Slack Channel](https://orange-button.slack.com/) to suggest features and enhancements. 63 | 64 | # Code review process 65 | 66 | All code is subject to a peer review. When a pull request is submitted at least one person with collaboration status 67 | must review the code before merging. All necessary checks (CLA verification, TravisCI) must pass before a pull request 68 | is merged. 69 | 70 | # Code of Conduct 71 | 72 | Being a library programmed in Python the [Python Community Code of Conduct](https://www.python.org/psf/codeofconduct/) is followed. 73 | 74 | # Community 75 | 76 | The [Orange Button Slack Channel](https://orange-button.slack.com/) is the best online resource for discussions 77 | regarding pyoblib. You are also invited to join regular developer meetings that occur (just ask to be invited on the 78 | Slack Channel). -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | recursive-include oblib/data * -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Orange Button Python Library (pyoblib) 2 | 3 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 4 | [![TravisCI](https://travis-ci.com/SunSpecOrangeButton/pyoblib.svg?branch=master)]( https://travis-ci.com/SunSpecOrangeButton/pyoblib) 5 | [![Documentation Status](https://readthedocs.org/projects/pyoblib/badge/?version=latest)](https://pyoblib.readthedocs.io/en/latest/?badge=latest) 6 | [![codecov](https://codecov.io/gh/SunSpecOrangeButton/pyoblib/branch/master/graph/badge.svg)](https://codecov.io/gh/SunSpecOrangeButton/pyoblib) 7 | 8 | 9 | The Orange Button Python Library, also called, pyoblib, provides functions to interact and work with the SunSpec Orange 10 | Button Taxonomy and provides capabilities that simplify working with Orange Button data. 11 | 12 | Full Documentation can be found at [Read the Docs](https://pyoblib.readthedocs.io/en/latest/). 13 | 14 | ## Getting Started 15 | 16 | ### Requirements 17 | 18 | Python 3.4 - 3.6. 19 | 20 | ### Installation 21 | 22 | For instructions on how to install, refer to the [Installation section](https://pyoblib.readthedocs.io/en/latest/overview.html#installation) 23 | on Read the Docs. 24 | 25 | ## Contributing 26 | 27 | Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull 28 | requests. 29 | 30 | ## Authors 31 | 32 | See the list of [contributors](https://github.com/SunSpecOrangeButton/pyoblib/graphs/contributors) who have participated 33 | in this project. 34 | 35 | ## License 36 | 37 | This project is licensed under the Apache 2.0 License - see the [LICENSE.md](LICENSE.md) file for details 38 | 39 | ## Acknowledgments 40 | 41 | We are greatly thankful to the [contributors](https://github.com/SunSpecOrangeButton/pyoblib/graphs/contributors) of 42 | the Orange Button Python Library for their hard work and dedication. 43 | 44 | * The Orange Button Specification was built by several organizations in the [Orange Button Implementors Network](https://sunspec.org/thank-signing-orange-button-implementor/) with guidance by [XBRL US](https://xbrl.us/home/about/). 45 | * Orange Button GitHub and tool accounts are supplied by [SunSpec Alliance](https://sunspec.org/sunspec-about/). 46 | * The procedures and infrastructure for this library are based upon pvlib. For more information see William F. Holmgren, Clifford W. Hansen, and Mark A. Mikofski. "pvlib python: a python package for modeling solar energy systems." Journal of Open Source Software, 3(29), 884, (2018). [https://doi.org/10.21105/joss.00884](https://doi.org/10.21105/joss.00884) 47 | 48 | 49 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | SOURCEDIR = source 8 | BUILDDIR = build 9 | 10 | # Put it first so that "make" without argument is like "make help". 11 | help: 12 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 13 | 14 | .PHONY: help Makefile 15 | 16 | # Catch-all target: route all unknown targets to Sphinx using the new 17 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 18 | %: Makefile 19 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=source 11 | set BUILDDIR=build 12 | 13 | if "%1" == "" goto help 14 | 15 | %SPHINXBUILD% >NUL 2>NUL 16 | if errorlevel 9009 ( 17 | echo. 18 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 19 | echo.installed, then set the SPHINXBUILD environment variable to point 20 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 21 | echo.may add the Sphinx directory to PATH. 22 | echo. 23 | echo.If you don't have Sphinx installed, grab it from 24 | echo.http://sphinx-doc.org/ 25 | exit /b 1 26 | ) 27 | 28 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 29 | goto end 30 | 31 | :help 32 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 33 | 34 | :end 35 | popd 36 | -------------------------------------------------------------------------------- /docs/source/api.rst: -------------------------------------------------------------------------------- 1 | API Reference 2 | ============== 3 | 4 | Subpackages 5 | ----------- 6 | 7 | .. toctree:: 8 | 9 | oblib.tests 10 | 11 | Submodules 12 | ---------- 13 | 14 | oblib.constants module 15 | ---------------------- 16 | 17 | .. automodule:: oblib.constants 18 | :members: 19 | :undoc-members: 20 | :show-inheritance: 21 | 22 | oblib.data\_model module 23 | ------------------------ 24 | 25 | .. automodule:: oblib.data_model 26 | :members: 27 | :undoc-members: 28 | :show-inheritance: 29 | 30 | oblib.identifier module 31 | ----------------------- 32 | 33 | .. automodule:: oblib.identifier 34 | :members: 35 | :undoc-members: 36 | :show-inheritance: 37 | 38 | oblib.ob module 39 | --------------- 40 | 41 | .. automodule:: oblib.ob 42 | :members: 43 | :undoc-members: 44 | :show-inheritance: 45 | 46 | oblib.parser module 47 | ------------------- 48 | 49 | .. automodule:: oblib.parser 50 | :members: 51 | :undoc-members: 52 | :show-inheritance: 53 | 54 | oblib.taxonomy module 55 | --------------------- 56 | 57 | .. automodule:: oblib.taxonomy 58 | :members: 59 | :undoc-members: 60 | :show-inheritance: 61 | 62 | oblib.taxonomy\_loader module 63 | ----------------------------- 64 | 65 | .. automodule:: oblib.taxonomy_loader 66 | :members: 67 | :undoc-members: 68 | :show-inheritance: 69 | 70 | oblib.util module 71 | ----------------- 72 | 73 | .. automodule:: oblib.util 74 | :members: 75 | :undoc-members: 76 | :show-inheritance: 77 | 78 | oblib.validator module 79 | ---------------------- 80 | 81 | .. automodule:: oblib.validator 82 | :members: 83 | :undoc-members: 84 | :show-inheritance: 85 | 86 | 87 | Module contents 88 | --------------- 89 | 90 | .. automodule:: oblib 91 | :members: 92 | :undoc-members: 93 | :show-inheritance: 94 | -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Configuration file for the Sphinx documentation builder. 4 | # 5 | # This file does only contain a selection of the most common options. For a 6 | # full list see the documentation: 7 | # http://www.sphinx-doc.org/en/master/config 8 | 9 | # -- Path setup -------------------------------------------------------------- 10 | 11 | # If extensions (or modules to document with autodoc) are in another directory, 12 | # add these directories to sys.path here. If the directory is relative to the 13 | # documentation root, use os.path.abspath to make it absolute, like shown here. 14 | # 15 | import os 16 | import sys 17 | sys.path.insert(0, os.path.abspath('../../')) 18 | print(sys.path) 19 | 20 | 21 | # -- Project information ----------------------------------------------------- 22 | 23 | project = 'pyoblib' 24 | copyright = '2019, SunSpec Alliance' 25 | author = 'SunSpec Alliance' 26 | 27 | # The short X.Y version 28 | version = '1.1' 29 | # The full version, including alpha/beta/rc tags 30 | release = 'v1.1.3' 31 | 32 | 33 | # -- General configuration --------------------------------------------------- 34 | 35 | # If your documentation needs a minimal Sphinx version, state it here. 36 | # 37 | # needs_sphinx = '1.0' 38 | 39 | # Add any Sphinx extension module names here, as strings. They can be 40 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 41 | # ones. 42 | extensions = [ 43 | 'sphinx.ext.autodoc', 44 | 'sphinx.ext.autosummary', 45 | 'sphinx.ext.doctest', 46 | 'sphinx.ext.coverage', 47 | ] 48 | 49 | # Add any paths that contain templates here, relative to this directory. 50 | templates_path = ['ntemplates'] 51 | 52 | # The suffix(es) of source filenames. 53 | # You can specify multiple suffix as a list of string: 54 | # 55 | # source_suffix = ['.rst', '.md'] 56 | source_suffix = '.rst' 57 | 58 | # The master toctree document. 59 | master_doc = 'index' 60 | 61 | # The language for content autogenerated by Sphinx. Refer to documentation 62 | # for a list of supported languages. 63 | # 64 | # This is also used if you do content translation via gettext catalogs. 65 | # Usually you set "language" from the command line for these cases. 66 | language = None 67 | 68 | # List of patterns, relative to source directory, that match files and 69 | # directories to ignore when looking for source files. 70 | # This pattern also affects html_static_path and html_extra_path. 71 | exclude_patterns = [] 72 | 73 | # The name of the Pygments (syntax highlighting) style to use. 74 | pygments_style = None 75 | 76 | 77 | # -- Options for HTML output ------------------------------------------------- 78 | 79 | # The theme to use for HTML and HTML Help pages. See the documentation for 80 | # a list of builtin themes. 81 | # 82 | html_theme = 'sphinx_rtd_theme' 83 | 84 | # Theme options are theme-specific and customize the look and feel of a theme 85 | # further. For a list of options available for each theme, see the 86 | # documentation. 87 | # 88 | # html_theme_options = {} 89 | 90 | # Add any paths that contain custom static files (such as style sheets) here, 91 | # relative to this directory. They are copied after the builtin static files, 92 | # so a file named "default.css" will overwrite the builtin "default.css". 93 | html_static_path = ['nstatic'] 94 | 95 | # Custom sidebar templates, must be a dictionary that maps document names 96 | # to template names. 97 | # 98 | # The default sidebars (for documents that don't match any pattern) are 99 | # defined by theme itself. Builtin themes are using these templates by 100 | # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', 101 | # 'searchbox.html']``. 102 | # 103 | # html_sidebars = {} 104 | 105 | 106 | # -- Options for HTMLHelp output --------------------------------------------- 107 | 108 | # Output file base name for HTML help builder. 109 | htmlhelp_basename = 'pyoblibdoc' 110 | 111 | 112 | # -- Options for LaTeX output ------------------------------------------------ 113 | 114 | latex_elements = { 115 | # The paper size ('letterpaper' or 'a4paper'). 116 | # 117 | # 'papersize': 'letterpaper', 118 | 119 | # The font size ('10pt', '11pt' or '12pt'). 120 | # 121 | # 'pointsize': '10pt', 122 | 123 | # Additional stuff for the LaTeX preamble. 124 | # 125 | # 'preamble': '', 126 | 127 | # Latex figure (float) alignment 128 | # 129 | # 'figure_align': 'htbp', 130 | } 131 | 132 | # Grouping the document tree into LaTeX files. List of tuples 133 | # (source start file, target name, title, 134 | # author, documentclass [howto, manual, or own class]). 135 | latex_documents = [ 136 | (master_doc, 'pyoblib.tex', 'pyoblib Documentation', 137 | 'SunSpec Alliance', 'manual'), 138 | ] 139 | 140 | 141 | # -- Options for manual page output ------------------------------------------ 142 | 143 | # One entry per manual page. List of tuples 144 | # (source start file, name, description, authors, manual section). 145 | man_pages = [ 146 | (master_doc, 'pyoblib', 'pyoblib Documentation', 147 | [author], 1) 148 | ] 149 | 150 | 151 | # -- Options for Texinfo output ---------------------------------------------- 152 | 153 | # Grouping the document tree into Texinfo files. List of tuples 154 | # (source start file, target name, title, author, 155 | # dir menu entry, description, category) 156 | texinfo_documents = [ 157 | (master_doc, 'pyoblib', 'pyoblib Documentation', 158 | author, 'pyoblib', 'One line description of project.', 159 | 'Miscellaneous'), 160 | ] 161 | 162 | 163 | # -- Options for Epub output ------------------------------------------------- 164 | 165 | # Bibliographic Dublin Core info. 166 | epub_title = project 167 | 168 | # The unique identifier of the text. This can be a ISBN number 169 | # or the project homepage. 170 | # 171 | # epub_identifier = '' 172 | 173 | # A unique identification for the text. 174 | # 175 | # epub_uid = '' 176 | 177 | # A list of files that should not be packed into the epub file. 178 | epub_exclude_files = ['search.html'] 179 | 180 | 181 | # -- Extension configuration ------------------------------------------------- 182 | -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | Welcome to pyoblib's documentation! 2 | =================================== 3 | 4 | The Orange Button Python Library, also called, pyoblib, provides functions to interact and work with the 5 | SunSpec Orange Button Taxonomy and provides capabilities that simplify working with Orange Button data. 6 | 7 | .. only: not latex 8 | 9 | Contents 10 | 11 | .. toctree:: 12 | :maxdepth: 1 13 | 14 | overview 15 | api 16 | oblib.tests 17 | 18 | Indices and tables 19 | ================== 20 | 21 | * :ref:`genindex` 22 | * :ref:`search` 23 | -------------------------------------------------------------------------------- /docs/source/oblib.tests.rst: -------------------------------------------------------------------------------- 1 | Test Cases API Reference 2 | ======================== 3 | 4 | Submodules 5 | ---------- 6 | 7 | oblib.tests.test\_data\_model module 8 | ------------------------------------ 9 | 10 | .. automodule:: oblib.tests.test_data_model 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | oblib.tests.test\_identifier module 16 | ----------------------------------- 17 | 18 | .. automodule:: oblib.tests.test_identifier 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | 23 | tests.test\_json\_clips module 24 | ------------------------------ 25 | 26 | .. automodule:: oblib.tests.test_json_clips 27 | :members: 28 | :undoc-members: 29 | :show-inheritance: 30 | 31 | tests.test\_ob module 32 | --------------------- 33 | 34 | .. automodule:: oblib.tests.test_ob 35 | :members: 36 | :undoc-members: 37 | :show-inheritance: 38 | 39 | tests.test\_parser module 40 | ------------------------- 41 | 42 | .. automodule:: oblib.tests.test_parser 43 | :members: 44 | :undoc-members: 45 | :show-inheritance: 46 | 47 | oblib.tests.test\_taxonomy module 48 | --------------------------------- 49 | 50 | .. automodule:: oblib.tests.test_taxonomy 51 | :members: 52 | :undoc-members: 53 | :show-inheritance: 54 | 55 | oblib.tests.test\_util module 56 | ----------------------------- 57 | 58 | .. automodule:: oblib.tests.test_util 59 | :members: 60 | :undoc-members: 61 | :show-inheritance: 62 | 63 | oblib.tests.test\_validator module 64 | ---------------------------------- 65 | 66 | .. automodule:: oblib.tests.test_validator 67 | :members: 68 | :undoc-members: 69 | :show-inheritance: 70 | 71 | 72 | Module contents 73 | --------------- 74 | 75 | .. automodule:: oblib.tests 76 | :members: 77 | :undoc-members: 78 | :show-inheritance: 79 | -------------------------------------------------------------------------------- /docs/source/overview.rst: -------------------------------------------------------------------------------- 1 | ========== 2 | Overview 3 | ========== 4 | 5 | The Orange Button Python Library, also called, pyoblib, provides functions to interact and work with the 6 | SunSpec Orange Button Taxonomy and provides capabilities that simplify working with Orange Button data. 7 | 8 | The pyoblib library leverages the Python standard library to the extent possible to minimize required dependencies. 9 | pyoblib is Open Sourced and is maintained by the Orange Button Open Source community. The source code is available on GitHub - 10 | `pyoblib `_. 11 | The code is licensed under Apache 2.0. 12 | 13 | The SunSpec Orange Button Taxonomy is also published as open source on GitHub - 14 | `solar-taxonomy `_. 15 | 16 | 17 | Features 18 | ======== 19 | - Includes an in-memory data model 20 | - Includes in-memory meta-data about the SunSpec Orange Button Taxonomy 21 | - Provides support for XML/JSON input-output 22 | - Provides support for data conversion and data validation 23 | - Supports identifier generation and validation 24 | 25 | 26 | pyoblib Class and Module Structure 27 | ================================== 28 | .. figure:: pyoblib.png 29 | :scale: 75 % 30 | :alt: pyoblib module structure 31 | 32 | 33 | Requirements 34 | ============ 35 | - Python 3.4-3.6 36 | 37 | 38 | Installation 39 | ============ 40 | 41 | Installing the library from PyPI 42 | -------------------------------- 43 | 44 | To install the library from the Python Package Index (PyPI), run the following command:: 45 | 46 | pip install oblib 47 | 48 | Installing the library from GitHub 49 | ---------------------------------- 50 | 51 | Follow the steps outlined below to install the library for development from GitHub. 52 | 53 | 1. Create a fork of the `pyoblib `_ GitHub repository. 54 | 2. Clone it locally. 55 | 3. Navigate to the pyoblib root directory - ``cd pyoblib`` 56 | 4. Run the setup script - ``scripts/setup-dev.sh`` 57 | 5. Install using setup.py - ``python setup.py install`` 58 | 59 | A series of Bash (Mac/Linux) shell scripts are available to assist with development and packaging. 60 | 61 | * cli.sh: Runs the CLI before it is packaged. 62 | * dist-cli.sh: Packages the CLI into a single executable file. 63 | * setup-dev.sh: Downloads the solar-taxonomy, us-gaap taxonomy, and Units registry. 64 | * tests.sh: Runs the python tests. 65 | * tests-cli.sh: Runs the CLI test suite. 66 | 67 | All scripts must be run from the root directory (i.e. ``scripts/tests.sh`` is the correct usage). 68 | Run ``scripts/setup-dev.sh`` before usage of other scripts. 69 | 70 | 71 | Running the Tests 72 | ~~~~~~~~~~~~~~~~~ 73 | 74 | In order to run the tests run the following scripts: 75 | 76 | * tests.sh - Runs the python tests. 77 | * tests-cli.sh - Runs the CLI test suite. 78 | 79 | Installing the CLI Tool 80 | ----------------------- 81 | 82 | Follow the steps outlined below to the Command Line Interface (CLI) tool. 83 | 84 | 1. Download an executable that matches your system type - 85 | 86 | • Mac - :download:`OB Mac Executable <../../dist-cli/Mac/ob>` 87 | • Windows - :download:`OB Windows Executable <../../dist-cli/Windows/ob.exe>` 88 | • Linux - :download:`OB Linux Executable <../../dist-cli/Linux/ob>` 89 | 90 | 2. Register the executable - 91 | 92 | To be able to run the executable from the command line, follow one of the two options - 93 | a. Move the downloaded file to the executable path - 94 | • Mac, Linux - ``sudo mv ob /usr/local/bin`` 95 | b. Or, add the OB executable file path to the system PATH environment variable. 96 | 97 | Now, the CLI tool can be invoked from the command line by using the command ``ob``. 98 | For the full set of commands, use the help option as ``ob --help`` 99 | -------------------------------------------------------------------------------- /docs/source/pyoblib.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SunSpecOrangeButton/pyoblib/5d91e4f94ac7939cd9a8df753313de07b420e722/docs/source/pyoblib.png -------------------------------------------------------------------------------- /oblib/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 SunSpec Alliance 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Initializes the Orange Button package.""" 16 | 17 | 18 | __all__ = ['constants', 'identifier', 'data_model', 'ob', 'parser', 19 | 'taxonomy', 'validator'] 20 | -------------------------------------------------------------------------------- /oblib/constants.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 SunSpec Alliance 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Sets pyoblib constants. 17 | SOLAR_TAXONOMY_DIR : path to solar taxonomy. 18 | """ 19 | 20 | import os 21 | import sys 22 | 23 | BASE_DIR = os.path.dirname(os.path.realpath(__file__)) 24 | 25 | if getattr( sys, 'frozen', False ) : 26 | # Running in a bundle (pyinstaller) 27 | SOLAR_TAXONOMY_DIR = os.path.join(sys._MEIPASS, "solar-taxonomy") 28 | else: 29 | # Running from source 30 | SOLAR_TAXONOMY_DIR = os.path.join(BASE_DIR, "data", "solar-taxonomy") 31 | 32 | 33 | # The following constants are based on hard-coded dates found in other modules. Moving all of them into constants 34 | # is a first step towards standardization. The second step will be analysis to see if some of them can be combined 35 | # and a potential third step will be to move away from hardcoding altogether. 36 | 37 | XML_NS = {"xbrldi:": "{http://xbrl.org/2006/xbrldi}", 38 | "link:": "{http://www.xbrl.org/2003/linkbase}", 39 | "solar:": "{http://xbrl.us/Solar/2020-04-01/solar}", 40 | "dei:": "{http://xbrl.sec.gov/dei/2014-01-31}", 41 | "us-gaap:": "{http://fasb.org/us-gaap/2017-01-31}"} 42 | 43 | XBRL_ORG_INSTANCE = "{http://www.xbrl.org/2003/instance}" 44 | 45 | DEI_NS = "{http://xbrl.sec.gov/dei/2014-01-31}" 46 | 47 | GAAP_NS = "{http://fasb.org/us-gaap/2017-01-31}" 48 | 49 | SOLAR_NS = "{http://xbrl.us/Solar/2020-04-01/solar}" 50 | 51 | TAXONOMY_ALL_FILENAME = "solar_all_2020-04-01_def.xml" 52 | 53 | ROLE_DOCUMENTATION = "http://www.xbrl.org/2003/role/documentation" 54 | 55 | OPTIONAL_NAMESPACES = { 56 | "us-gaap": "http://xbrl.fasb.org/us-gaap/2017/elts/us-gaap-2017-01-31.xsd" 57 | } 58 | 59 | NAMESPACES = { 60 | "xmlns": "http://www.xbrl.org/2003/instance", 61 | "xmlns:link": "http://www.xbrl.org/2003/linkbase", 62 | "xmlns:xlink": "http://www.w3.org/1999/xlink", 63 | "xmlns:xsi": "http://www.w3.org/2001/XMRLSchema-instance", 64 | "xmlns:units": "http://www.xbrl.org/2009/utr", 65 | "xmlns:xbrldi": "http://xbrl.org/2006/xbrldi", 66 | "xmlns:solar": "http://xbrl.us/Solar/2020-04-01/solar" 67 | } 68 | 69 | TAXONOMY_NAME = "https://raw.githubusercontent.com/SunSpecOrangeButton/solar-taxonomy/master/core/solar_all_2020-04-01.xsd" 70 | 71 | DEI_XSD = "dei-2018-01-31.xsd" 72 | 73 | US_GAAP_XSD = "us-gaap-2017-01-31.xsd" 74 | 75 | SOLAR_XSD = "solar_2020-04-01.xsd" 76 | 77 | SOLAR_ALL_PRE_XML = "solar_all_2020-04-01_pre.xml" 78 | 79 | SOLAR_LAB_XML = "solar_2020-04-01_lab.xml" 80 | 81 | SOLAR_CALCULATION_XML = "solar_all_2020-04-01_cal.xml" 82 | -------------------------------------------------------------------------------- /oblib/identifier.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 SunSpec Alliance 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Handles Orange Button identifiers.""" 16 | 17 | import re 18 | import uuid 19 | 20 | REG_EX = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" 21 | 22 | 23 | def identifier(): 24 | """ 25 | Return valid UUID for Orange Button identifiers. 26 | 27 | Returns: 28 | A string containing a valid UUID. 29 | """ 30 | 31 | return str(uuid.uuid4()) 32 | 33 | 34 | def validate(inp): 35 | """ 36 | Validate a UUID string. 37 | 38 | Args: 39 | inp (string): Identifier to validate. 40 | 41 | Returns: 42 | True if the input string is a valid UUID, False otherwise. 43 | """ 44 | return re.search(REG_EX, inp, re.IGNORECASE) is not None 45 | -------------------------------------------------------------------------------- /oblib/ob.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 SunSpec Alliance 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ 16 | Contains generic classes and methods used throughout oblib including but not limited 17 | to Error classes. 18 | """ 19 | 20 | import datetime 21 | 22 | 23 | class OBError(Exception): 24 | """ 25 | Base class for Orange Button data validity exceptions. 26 | """ 27 | def __init__(self, message): 28 | super(OBError, self).__init__(message) 29 | 30 | 31 | class OBTypeError(OBError): 32 | """ 33 | Raised if we try to set a concept to a value with an invalid data type 34 | """ 35 | def __init__(self, message): 36 | super(OBTypeError, self).__init__(message) 37 | 38 | 39 | class OBContextError(OBError): 40 | """ 41 | Raised if we try to set a concept without sufficient Context fields 42 | """ 43 | def __init__(self, message): 44 | super(OBContextError, self).__init__(message) 45 | 46 | 47 | class OBConceptError(OBError): 48 | """ 49 | Raised if we try to set a concept that can't be set in the current 50 | Entrypoint 51 | """ 52 | def __init__(self, message): 53 | super(OBConceptError, self).__init__(message) 54 | 55 | 56 | class OBNotFoundError(OBError): 57 | """ 58 | Raised if we refer to a name that's not found in the taxonomy 59 | """ 60 | def __init__(self, message): 61 | super(OBNotFoundError, self).__init__(message) 62 | 63 | 64 | class OBUnitError(OBError): 65 | """ 66 | Raised if we try to set a concept to a value with incorrect units 67 | """ 68 | def __init__(self, message): 69 | super(OBUnitError, self).__init__(message) 70 | 71 | 72 | class OBValidationError(OBError): 73 | """ 74 | Raised during validation of input data if any portion of code raises an error 75 | """ 76 | def __init__(self, message): 77 | super(OBValidationError, self).__init__(message) 78 | 79 | 80 | class OBMultipleErrors(OBError): 81 | """ 82 | Raised in sections of code which must group errors together and raise them 83 | as a set of functions. 84 | """ 85 | 86 | def __init__(self, message, validation_errors=None): 87 | super(OBMultipleErrors, self).__init__(message) 88 | if validation_errors is not None: 89 | self._errors = validation_errors 90 | else: 91 | self._errors = [] 92 | 93 | def append(self, error): 94 | """ 95 | Appends an exception to the list internally held list of errors. 96 | 97 | Args: 98 | error (any type): If this is a type inherited from OBError it will be 99 | added to the end of the list. If it is type inherited from OBMultipleErrors 100 | the lists will be concatenated. If it is a string it will be converted to 101 | a OBError. If it is any other type it will be converted to a string and 102 | then an OBError will be created using the string as a message. 103 | """ 104 | 105 | if isinstance(error, OBMultipleErrors): 106 | self._errors = self._errors + error.get_errors() 107 | elif isinstance(error, OBError): 108 | self._errors.append(error) 109 | elif isinstance(error, str): 110 | self._errors.append(OBError(error)) 111 | else: 112 | self._errors.append(OBError(str(error))) 113 | 114 | def get_errors(self): 115 | """ 116 | Used to access the list of errors. 117 | 118 | Returns: 119 | List of OBErrors. 120 | """ 121 | return self._errors 122 | 123 | 124 | class OBValidationErrors(OBMultipleErrors): 125 | """ 126 | Raised in sections of code that must return lists of validaition errors. 127 | """ 128 | def __init__(self, message): 129 | super(OBValidationErrors, self).__init__(message) -------------------------------------------------------------------------------- /oblib/parser.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 SunSpec Alliance 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """ Parses JSON/XML input and output data. """ 16 | 17 | 18 | import enum 19 | import json 20 | import xml.etree.ElementTree as ElementTree 21 | 22 | from oblib import constants, data_model, util, ob 23 | 24 | 25 | def _xn(s): 26 | # eXpands the Namespace to be equitable to what is read in by the XML parser. 27 | 28 | if s is None: 29 | return None 30 | for n in constants.XML_NS: 31 | if n in s: 32 | return s.replace(n, constants.XML_NS[n]) 33 | return constants.XBRL_ORG_INSTANCE + s 34 | 35 | # End of XML parsign utility code 36 | 37 | 38 | class FileFormat(enum.Enum): 39 | """ Legal values for file formats. """ 40 | 41 | XML = "XML" 42 | JSON = "JSON" 43 | 44 | 45 | class Parser(object): 46 | """ 47 | Parses JSON/XML input and output data 48 | 49 | taxonomy (Taxonomy): initialized Taxonomy. 50 | """ 51 | 52 | def __init__(self, taxonomy): 53 | """ Initializes parser """ 54 | 55 | self._taxonomy = taxonomy 56 | 57 | def _entrypoint_name(self, doc_concepts): 58 | """ 59 | Used to find the name of the correct entrypoint given a set of concepts from a document (JSON or XML). 60 | Currently assumes that a JSON/XML document contains one and only one entrypoint and raises 61 | an exception if this is not true. 62 | 63 | Args: 64 | doc_concepts (list of strings): A list of all concepts in the input JSON/XML document. 65 | 66 | Returns: 67 | A string contianing the name of the correct entrypoint. 68 | TODO: This is algorithm is fairly slow since it loops through all entry points which is time 69 | consuming for a small number of input concepts. With this said there is not currently enough 70 | support functions in Taxonomy to accomodate other algorithms. It may be better to move this 71 | into taxonomy_semantic and simultaneously improve the speed. 72 | """ 73 | 74 | entrypoints_found = set() 75 | for entrypoint in self._taxonomy.semantic.get_all_entrypoints(): 76 | if entrypoint == "All": 77 | # Ignore the "All" entrypoint, which matches everything -- we're 78 | # looking for a more specific one. 79 | continue 80 | for concept in self._taxonomy.semantic.get_entrypoint_concepts(entrypoint): 81 | for doc_concept in doc_concepts: 82 | if doc_concept == concept: 83 | entrypoints_found.add(entrypoint) 84 | 85 | if len(entrypoints_found) == 0: 86 | raise ob.OBValidationError("No entrypoint found given the set of facts") 87 | elif len(entrypoints_found) == 1: 88 | for entrypoint in entrypoints_found: 89 | return entrypoint 90 | else: 91 | # Multiple candidate entrypoints are found. See if there is one and only one 92 | # perfect fit. 93 | the_one = None 94 | for entrypoint in entrypoints_found: 95 | ok = True 96 | for doc_concept in doc_concepts: 97 | ok2 = False 98 | for doc_concept2 in self._taxonomy.semantic.get_entrypoint_concepts(entrypoint): 99 | if doc_concept == doc_concept2: 100 | ok2 = True 101 | break 102 | if not ok2: 103 | ok = False 104 | break 105 | if ok: 106 | if the_one is None: 107 | the_one = entrypoint 108 | else: 109 | raise ob.OBValidationError("Multiple entrypoints ({}, {}) found given the set of facts".format(the_one, entrypoint)) 110 | if the_one == None: 111 | raise ob.OBValidationError("No entrypoint found given the set of facts") 112 | else: 113 | return the_one 114 | 115 | def from_JSON_string(self, json_string, entrypoint_name=None): 116 | """ 117 | Loads the Entrypoint from a JSON string into an entrypoint. If no entrypoint_name 118 | is given the entrypoint will be derived from the facts. In some cases this is not 119 | possible because more than one entrypoint could exist given the list of facts and 120 | in these cases an entrypoint is required. 121 | 122 | Args: 123 | json_string (str): String containing JSON 124 | entrypoint_name (str): Optional name of the entrypoint. 125 | 126 | Returns: 127 | OBInstance containing the loaded data. 128 | """ 129 | 130 | # Create a validation error which can be used to maintain a list of error messages 131 | validation_errors = ob.OBValidationErrors("Error(s) found in input JSON") 132 | 133 | # Convert string to JSON data 134 | try: 135 | json_data = json.loads(json_string) 136 | except Exception as e: 137 | validation_errors.append(e) 138 | raise validation_errors 139 | 140 | # Perform basic validation that all required parts of the document are present. 141 | if "documentType" not in json_data: 142 | validation_errors.append("JSON is missing documentType tag") 143 | raise validation_errors 144 | if "prefixes" not in json_data: 145 | validation_errors.append("JSON is missing prefixes tag") 146 | raise validation_errors 147 | if "dtsReferences" not in json_data: 148 | validation_errors.append("JSON is missing dtsRererences tag") 149 | raise validation_errors 150 | if "facts" not in json_data: 151 | validation_errors.append("JSON is missing facts tag") 152 | raise validation_errors 153 | facts = json_data["facts"] 154 | 155 | # Loop through facts to determine what type of endpoint this is. 156 | if not entrypoint_name: 157 | fact_names = [] 158 | for id in facts: 159 | fact = facts[id] 160 | if "aspects" not in fact: 161 | validation_errors.append("fact tag is missing aspects tag") 162 | elif "concept" not in fact["aspects"]: 163 | validation_errors.append("aspects tag is missing concept tag") 164 | else: 165 | fact_names.append(fact["aspects"]["concept"]) 166 | try: 167 | entrypoint_name = self._entrypoint_name(fact_names) 168 | except ob.OBValidationError as ve: 169 | validation_errors.append(ve) 170 | raise validation_errors 171 | 172 | # If we reach this point re-initialize the validation errors because all previous errors found 173 | # will be found again. Re-initialization reduces duplicate error messages and ensures that 174 | # errors are found in the correct order. 175 | validation_errors = ob.OBValidationErrors("Error(s) found in input JSON") 176 | 177 | # Create an entrypoint. 178 | ob_instance = data_model.OBInstance(entrypoint_name, self._taxonomy, dev_validation_off=False) 179 | 180 | # Loop through facts. 181 | for id in facts: 182 | 183 | fact = facts[id] 184 | 185 | # Track the current number of errors to see if it grows for this fact 186 | begin_error_count = len(validation_errors.get_errors()) 187 | 188 | # Create kwargs and populate with entity. 189 | kwargs = {} 190 | if "aspects" not in fact: 191 | validation_errors.append("fact tag is missing aspects tag") 192 | else: 193 | if "concept" not in fact["aspects"]: 194 | validation_errors.append("aspects tag is missing concept tag") 195 | 196 | if "entity" not in fact["aspects"]: 197 | validation_errors.append("aspects tag is missing entity tag") 198 | else: 199 | kwargs = {"entity": fact["aspects"]["entity"]} 200 | 201 | # TODO: id is not currently support by Entrypoint. Uncomment when it is. 202 | # if "id" in fact: 203 | # kwargs["id"] = fact["id"] 204 | 205 | if "period" in fact["aspects"]: 206 | period = fact["aspects"]["period"] 207 | if "/" in period: 208 | dates = period.split("/") 209 | if len(dates) != 2: 210 | validation_errors.append("period component is in an incorrect format (yyyy-mm-ddT00:00:00/yyyy-mm-ddT00:00:00 expected)") 211 | else: 212 | start = util.convert_json_datetime(dates[0]) 213 | end = util.convert_json_datetime(dates[1]) 214 | if start is None: 215 | validation_errors.append("period start component is in an incorrect format (yyyy-mm-ddT00:00:00 expected)") 216 | if end is None: 217 | validation_errors.append("period end component is in an incorrect format (yyyy-mm-ddT00:00:00 expected)") 218 | kwargs["duration"] = {} 219 | kwargs["duration"]["start"] = start 220 | kwargs["duration"]["end"] = end 221 | else: 222 | start = util.convert_json_datetime(fact["aspects"]["period"]) 223 | if start is None: 224 | validation_errors.append("start is in an incorrect format (yyyy-mm-ddT00:00:00 expected)") 225 | kwargs["instant"] = start 226 | 227 | elif kwargs is not None: 228 | kwargs["duration"] = "forever" 229 | 230 | # Add axis to kwargs if item is an axis. 231 | # TODO: Exception processing 232 | for axis_chk in fact["aspects"]: 233 | if "Axis" in axis_chk: 234 | kwargs[axis_chk.split(":")[1]] = fact["aspects"][axis_chk] 235 | 236 | if "aspects" in fact and "unit" in fact["aspects"] and kwargs is not None: 237 | kwargs["unit_name"] = fact["aspects"]["unit"] 238 | 239 | if "value" not in fact: 240 | validation_errors.append("fact tag is missing value tag") 241 | 242 | kwargs["fact_id"] = id 243 | 244 | # If validation errors were found for this fact continute to the next fact 245 | if len(validation_errors.get_errors()) > begin_error_count: 246 | continue 247 | 248 | # TODO: Temporary code 249 | # Required to match behavior of to_JSON, once the two are synchronized it should not be required. 250 | value = fact["value"] 251 | if value == "None": 252 | value = None 253 | elif value == "True": 254 | value = True 255 | elif value == "False": 256 | value = False 257 | # Done with temporary code 258 | 259 | try: 260 | ob_instance.set(fact["aspects"]["concept"], value, **kwargs) 261 | # entrypoint.set(fact["aspects"]["xbrl:concept"], fact["value"], **kwargs) 262 | except Exception as e: 263 | validation_errors.append(e) 264 | 265 | # Raise the errors if necessary 266 | if validation_errors.get_errors(): 267 | raise validation_errors 268 | 269 | return ob_instance 270 | 271 | def from_JSON(self, in_filename, entrypoint_name=None): 272 | """ 273 | Imports XBRL as JSON from the given filename. If no entrypoint_name 274 | is given the entrypoint will be derived from the facts. In some cases this is not 275 | possible because more than one entrypoint could exist given the list of facts and 276 | in these cases an entrypoint is required. 277 | 278 | Args: 279 | in_filename (str): input filename 280 | entrypoint_name (str): Optional name of the entrypoint. 281 | 282 | Returns: 283 | OBInstance containing the loaded data. 284 | """ 285 | 286 | with open(in_filename, "r") as infile: 287 | s = infile.read() 288 | return self.from_JSON_string(s, entrypoint_name) 289 | 290 | def from_XML_string(self, xml_string, entrypoint_name=None): 291 | """ 292 | Loads the Entrypoint from an XML string. If no entrypoint_name 293 | is given the entrypoint will be derived from the facts. In some cases this is not 294 | possible because more than one entrypoint could exist given the list of facts and 295 | in these cases an entrypoint is required. 296 | 297 | Args: 298 | xml_string(str): String containing XML. 299 | entrypoint_name (str): Optional name of the entrypoint. 300 | 301 | Returns: 302 | OBInstance containing the loaded data. 303 | """ 304 | 305 | # NOTE: The XML parser has much less effort placed into both the coding and testing as 306 | # opposed to the coding and testing effort performed on the JSON parser. To some extent 307 | # this is on purpose since the hope is that the bulk of Orange Button data will be 308 | # transmitted using JSON. With this you are invited to (a) refactor the XML parsing code 309 | # and (b) create XML test cases if you believe that XML parser should receive the same 310 | # effort level as the JSON parser. 311 | 312 | # Create a validation error which can be used to maintain a list of error messages 313 | validation_errors = ob.OBValidationErrors("Error(s) found in input JSON") 314 | 315 | try: 316 | root = ElementTree.fromstring(xml_string) 317 | except Exception as e: 318 | validation_errors.append(e) 319 | raise validation_errors 320 | 321 | # Read all elements that are not a context or a unit: 322 | if not entrypoint_name: 323 | fact_names = [] 324 | for child in root: 325 | if child.tag != _xn("link:schemaRef") and child.tag != _xn("unit") and child.tag != _xn("context"): 326 | 327 | tag = child.tag 328 | tag = tag.replace(constants.SOLAR_NS, "solar:") 329 | tag = tag.replace(constants.GAAP_NS, "us-gaap:") 330 | tag = tag.replace(constants.DEI_NS, "dei:") 331 | fact_names.append(tag) 332 | try: 333 | entrypoint_name = self._entrypoint_name(fact_names) 334 | except ob.OBValidationError as ve: 335 | validation_errors.append(ve) 336 | raise validation_errors 337 | 338 | # Create an entrypoint. 339 | entrypoint = data_model.OBInstance(entrypoint_name, self._taxonomy, dev_validation_off=True) 340 | 341 | # Read in units 342 | units = {} 343 | for unit in root.iter(_xn("unit")): 344 | units[unit.attrib["id"]] = unit[0].text 345 | 346 | # Read in contexts 347 | contexts = {} 348 | for context in root.iter(_xn("context")): 349 | instant = None 350 | duration = None 351 | entity = None 352 | start_date = None 353 | end_date = None 354 | axis = {} 355 | for elem in context.iter(): 356 | if elem.tag == _xn("period"): 357 | if elem[0].tag == _xn("forever"): 358 | duration = "forever" 359 | elif elem[0].tag == _xn("startDate"): 360 | start_date = elem[0].text 361 | elif elem[0].tag == _xn("endDate"): 362 | end_date = elem[0].text 363 | elif elem[0].tag == _xn("instant"): 364 | instant = elem[0].text 365 | elif elem.tag == _xn("entity"): 366 | for elem2 in elem.iter(): 367 | if elem2.tag == _xn("identifier"): 368 | entity = elem2.text 369 | elif elem2.tag == _xn("segment"): 370 | for elem3 in elem2.iter(): 371 | if elem3.tag == _xn("xbrldi:typedMember"): 372 | for elem4 in elem3.iter(): 373 | if elem4.tag != _xn("xbrldi:typedMember"): 374 | axis[elem3.attrib["dimension"]] = elem4.text 375 | 376 | if duration is None and start_date is not None and end_date is not None: 377 | duration = {"start": start_date, "end": end_date} 378 | kwargs = {} 379 | if instant is not None: 380 | kwargs["instant"] = instant 381 | if duration is not None: 382 | kwargs["duration"] = duration 383 | if entity is not None: 384 | kwargs["entity"] = entity 385 | if axis is not None: 386 | for a in axis: 387 | kwargs[a] = axis[a] 388 | 389 | if instant is None and duration is None: 390 | validation_errors.append( 391 | ob.OBValidationError("Context is missing both a duration and instant tag")) 392 | if entity is None: 393 | validation_errors.append("Context is missing an entity tag") 394 | 395 | try: 396 | dm_ctx = data_model.Context(**kwargs) 397 | contexts[context.attrib["id"]] = dm_ctx 398 | except Exception as e: 399 | validation_errors.append(e) 400 | 401 | # Read all elements that are not a context or a unit: 402 | for child in root: 403 | if child.tag != _xn("link:schemaRef") and child.tag != _xn("unit") and child.tag != _xn("context"): 404 | kwargs = {} 405 | 406 | fact_id = None 407 | if "id" in child.attrib: 408 | fact_id = child.attrib["id"] 409 | 410 | if "contextRef" in child.attrib: 411 | if child.attrib["contextRef"] in contexts: 412 | kwargs["context"] = contexts[child.attrib["contextRef"]] 413 | kwargs["fact_id"] = fact_id 414 | tag = child.tag 415 | tag = tag.replace(constants.SOLAR_NS, "solar:") 416 | tag = tag.replace(constants.GAAP_NS, "us-gaap:") 417 | tag = tag.replace(constants.DEI_NS, "dei:") 418 | try: 419 | entrypoint.set(tag, child.text, **kwargs) 420 | except Exception as e: 421 | validation_errors.append(e) 422 | else: 423 | validation_errors.append("referenced context is missing") 424 | else: 425 | validation_errors.append("Element is missing a context") 426 | 427 | # Raise the errors if necessary 428 | if validation_errors.get_errors(): 429 | raise validation_errors 430 | 431 | # Return populated entrypoint 432 | return entrypoint 433 | 434 | def from_XML(self, in_filename, entrypoint_name=None): 435 | """ 436 | Imports XBRL as XML from the given filename. If no entrypoint_name 437 | is given the entrypoint will be derived from the facts. In some cases this is not 438 | possible because more than one entrypoint could exist given the list of facts and 439 | in these cases an entrypoint is required. 440 | 441 | Args: 442 | in_filename (str): input filename 443 | entrypoint_name (str): Optional name of the entrypoint. 444 | 445 | Returns: 446 | OBInstance containing the loaded data. 447 | """ 448 | 449 | with open(in_filename, "r") as infile: 450 | s = infile.read() 451 | return self.from_XML_string(s, entrypoint_name) 452 | 453 | def to_JSON_string(self, entrypoint): 454 | """ 455 | Returns XBRL as an JSON string given a data model entrypoint. 456 | 457 | entrypoint (Entrypoint): entry point to export to JSON 458 | """ 459 | 460 | return entrypoint.to_JSON_string() 461 | 462 | def to_JSON(self, entrypoint, out_filename): 463 | """ 464 | Exports XBRL as JSON to the given filename given a data model entrypoint. 465 | 466 | Args: 467 | entrypoint (Entrypoint): entry point to export to JSON 468 | out_filename (str): output filename 469 | """ 470 | 471 | entrypoint.to_JSON(out_filename) 472 | 473 | def to_XML_string(self, entrypoint): 474 | """ 475 | Returns XBRL as an XML string given a data model entrypoint. 476 | 477 | Args: 478 | entrypoint (Entrypoint): entry point to export to XML 479 | """ 480 | 481 | return entrypoint.to_XML_string() 482 | 483 | def to_XML(self, entrypoint, out_filename): 484 | """ 485 | Exports XBRL as XML to the given filename given a data model entrypoint. 486 | 487 | Args: 488 | entrypoint (Entrypoint): entry point to export to XML 489 | out_filename (str): output filename 490 | """ 491 | 492 | entrypoint.to_XML(out_filename) 493 | 494 | def convert(self, in_filename, out_filename, file_format, entrypoint_name=None): 495 | """ 496 | Converts and input file (in_filename) to an output file (out_filename) given an input 497 | file format specified by file_format. If no entrypoint_name 498 | is given the entrypoint will be derived from the facts. In some cases this is not 499 | possible because more than one entrypoint could exist given the list of facts and 500 | in these cases an entrypoint is required. 501 | 502 | Args: 503 | in_filename (str): full path to input file 504 | out_filename (str): full path to output file 505 | entrypoint_name (str): Optional name of the entrypoint. 506 | file_format (FileFormat): values are FileFormat.JSON" or FileFormat.XML" 507 | """ 508 | 509 | if file_format == FileFormat.JSON: 510 | entrypoint = self.from_JSON(in_filename, entrypoint_name) 511 | self.to_XML(entrypoint, out_filename) 512 | elif file_format == FileFormat.XML: 513 | entrypoint = self.from_XML(in_filename, entrypoint_name) 514 | self.to_JSON(entrypoint, out_filename) 515 | else: 516 | raise ValueError("file_format must be JSON or XML") 517 | 518 | def validate(self, in_filename, file_format, entrypoint_name=None): 519 | """ 520 | Validates an in input file (in_filename) by loading it. Unlike convert does not produce 521 | an output file. If no entrypoint_name 522 | is given the entrypoint will be derived from the facts. In some cases this is not 523 | possible because more than one entrypoint could exist given the list of facts and 524 | in these cases an entrypoint is required. 525 | 526 | Args: 527 | in_filename (str): full path to input file 528 | entrypoint_name (str): Optional name of the entrypoint. 529 | file_format (FileFormat): values are FileFormat.JSON" or FileFormat.XML" 530 | 531 | TODO: At this point in time errors part output via print statements. Future implementation 532 | should actually return the conditions instead. It also may be desirable to list the 533 | strictness level of the validation checkes. 534 | """ 535 | 536 | if file_format == FileFormat.JSON: 537 | self.from_JSON(in_filename, entrypoint_name) 538 | else: 539 | self.from_XML(in_filename, entrypoint_name) 540 | -------------------------------------------------------------------------------- /oblib/taxonomy_loader.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 SunSpec Alliance 2 | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Handles Loading of Orange Button Taxonomy. No external functionality exposed.""" 16 | 17 | import xml.sax 18 | import os 19 | import sys 20 | 21 | from oblib import constants, util, taxonomy 22 | 23 | 24 | class _TaxonomyUnitsHandler(xml.sax.ContentHandler): 25 | """Loads Taxonomy Units from the units type registry file.""" 26 | 27 | def __init__(self): 28 | self._units = {} 29 | 30 | def startElement(self, name, attrs): 31 | if name == "unit": 32 | for item in attrs.items(): 33 | if item[0] == "id": 34 | 35 | self._curr = taxonomy.Unit() 36 | self._curr.id = item[1] 37 | elif name == "xs:enumeration": 38 | for item in attrs.items(): 39 | if item[0] == "value": 40 | self._curr.append(item[1]) 41 | 42 | def characters(self, content): 43 | self._content = content 44 | 45 | def endElement(self, name): 46 | if name == "unitId": 47 | self._curr.unit_id = self._content 48 | self._units[self._content] = self._curr 49 | elif name == "unitName": 50 | self._curr.unit_name = self._content 51 | elif name == "nsUnit": 52 | self._curr.ns_unit = self._content 53 | elif name == "itemType": 54 | self._curr.item_type = self._content 55 | elif name == "itemTypeDate": 56 | self._curr.item_type_date = util.convert_taxonomy_xsd_date(self._content) 57 | elif name == "symbol": 58 | self._curr.symbol = self._content 59 | elif name == "definition": 60 | self._curr.definition = self._content 61 | elif name == "baseStandard": 62 | 63 | self._curr.base_standard = taxonomy.BaseStandard(self._content) 64 | elif name == "status": 65 | 66 | self._curr.status = taxonomy.UnitStatus(self._content) 67 | elif name == "versionDate": 68 | self._curr.version_date = util.convert_taxonomy_xsd_date(self._content) 69 | 70 | def units(self): 71 | return self._units 72 | 73 | 74 | class _TaxonomyTypesHandler(xml.sax.ContentHandler): 75 | """Loads Taxonomy Types from the solar types xsd file.""" 76 | 77 | def __init__(self): 78 | self._types = {} 79 | 80 | def startElement(self, name, attrs): 81 | if name == "complexType": 82 | for item in attrs.items(): 83 | if item[0] == "name": 84 | self._curr = [] 85 | if ":" in item[1]: 86 | name = item[1] 87 | else: 88 | name = "solar-types:" + item[1] 89 | self._types[name] = self._curr 90 | elif name == "xs:enumeration": 91 | for item in attrs.items(): 92 | if item[0] == "value": 93 | self._curr.append(item[1]) 94 | 95 | def types(self): 96 | return self._types 97 | 98 | 99 | class _TaxonomyNumericHandler(xml.sax.ContentHandler): 100 | """Loads Taxonomy Numeric Types from the numeric us xsd file.""" 101 | 102 | def __init__(self): 103 | """Numeric handler constructor.""" 104 | self._numeric_types = [] 105 | 106 | def startElement(self, name, attrs): 107 | if name == "complexType": 108 | for item in attrs.items(): 109 | if item[0] == "name": 110 | if ":" in item[1]: 111 | name = item[1] 112 | else: 113 | name = "num-us:" + item[1] 114 | self._numeric_types.append(name) 115 | 116 | def numeric_types(self): 117 | return self._numeric_types 118 | 119 | 120 | class _TaxonomyRefPartsHandler(xml.sax.ContentHandler): 121 | """Loads Taxonomy Ref Parts from the numeric us xsd file.""" 122 | 123 | def __init__(self): 124 | """Ref parts constructor.""" 125 | self._ref_parts = [] 126 | 127 | def startElement(self, name, attrs): 128 | if name == "xs:element": 129 | for item in attrs.items(): 130 | if item[0] == "name": 131 | self._ref_parts.append(item[1]) 132 | 133 | def ref_parts(self): 134 | return self._ref_parts 135 | 136 | 137 | class _TaxonomyGenericRolesHandler(xml.sax.ContentHandler): 138 | """Loads Taxonomy Generic Roles from the generic roles xsd file.""" 139 | 140 | def __init__(self): 141 | """Generic role handler constructor.""" 142 | self._generic_roles = [] 143 | self._process = False 144 | 145 | def startElement(self, name, attrs): 146 | if name == "link:definition": 147 | self._process = True 148 | 149 | def endElement(self, name): 150 | if name == "link:definition": 151 | self._process = False 152 | 153 | def characters(self, content): 154 | if self._process: 155 | self._generic_roles.append(content) 156 | 157 | def roles(self): 158 | return self._generic_roles 159 | 160 | 161 | class _TaxonomyDocumentationHandler(xml.sax.ContentHandler): 162 | """Loads Taxonomy Docstrings from Labels file""" 163 | 164 | def __init__(self): 165 | """Ref parts constructor.""" 166 | self._documentation = {} 167 | self._awaiting_text_for_concept = None 168 | 169 | def startElement(self, name, attrs): 170 | # Technically we should be using the labelArc element to connect a label 171 | # element to a loc element and the loc element refers to a concept by its anchor 172 | # within the main xsd, but that's really complicated and in practice the 173 | # xlink:label atrr in the