pax_global_header00006660000000000000000000000064144221627640014522gustar00rootroot0000000000000052 comment=a629d91f59fcdc7d198137607faa7d51c83eae88 isbnlib-3.10.14/000077500000000000000000000000001442216276400133125ustar00rootroot00000000000000isbnlib-3.10.14/.github/000077500000000000000000000000001442216276400146525ustar00rootroot00000000000000isbnlib-3.10.14/.github/CODEOWNERS000066400000000000000000000000421442216276400162410ustar00rootroot00000000000000isbnlib/* @xlcnd docs/* @xlcnd isbnlib-3.10.14/.github/ISSUE_TEMPLATE/000077500000000000000000000000001442216276400170355ustar00rootroot00000000000000isbnlib-3.10.14/.github/ISSUE_TEMPLATE/bug_report.md000066400000000000000000000005441442216276400215320ustar00rootroot00000000000000--- name: Bug report about: Create a report to help us improve title: "[BUG]" labels: bug assignees: '' --- **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Give an example (including error messages). **Additional context** Add any other context about the problem here (OS, python version and isbnlib version). isbnlib-3.10.14/.github/ISSUE_TEMPLATE/feature_request.md000066400000000000000000000011261442216276400225620ustar00rootroot00000000000000--- name: Feature request about: Suggest an idea for this project title: "[FEATURE]" labels: new feature assignees: '' --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context about the feature request here. isbnlib-3.10.14/.github/ISSUE_TEMPLATE/other_issue.md000066400000000000000000000002401442216276400217040ustar00rootroot00000000000000## Required Information *Please, classify the issue below.* **Question, Discussion or Info?** *Type*: here ## Issue Description Describe your issue here isbnlib-3.10.14/.github/PULL_REQUEST_TEMPLATE.md000066400000000000000000000002421442216276400204510ustar00rootroot00000000000000**IMPORTANT** Make your pull request against the ``dev`` branch, please! On follow-up of issue #??? Changes proposed in this pull request: - - - @xlcnd isbnlib-3.10.14/.github/automation/000077500000000000000000000000001442216276400170325ustar00rootroot00000000000000isbnlib-3.10.14/.github/automation/greetings.yml000066400000000000000000000006111442216276400215420ustar00rootroot00000000000000name: Greetings on: [pull_request, issues] jobs: greeting: runs-on: ubuntu-latest steps: - uses: actions/first-interaction@v1 with: repo-token: ${{ secrets.GITHUB_TOKEN }} issue-message: 'Thank you for your interest in `isbnlib`. I hope to answer your issue soon.' pr-message: 'Thanks for you contribution to `isbnlib`. I hope to review it soon.' isbnlib-3.10.14/.github/automation/label.yml000066400000000000000000000002671442216276400206410ustar00rootroot00000000000000name: Labeler on: [pull_request] jobs: label: runs-on: ubuntu-latest steps: - uses: actions/labeler@v2 with: repo-token: "${{ secrets.GITHUB_TOKEN }}" isbnlib-3.10.14/.github/automation/stale.yml000066400000000000000000000006321442216276400206660ustar00rootroot00000000000000name: Mark stale issues and pull requests on: schedule: - cron: "0 3 * * *" jobs: stale: runs-on: ubuntu-latest steps: - uses: actions/stale@v1 with: repo-token: ${{ secrets.GITHUB_TOKEN }} stale-issue-message: 'This needs attention!' stale-pr-message: 'What happened?' stale-issue-label: 'no-issue-activity' stale-pr-label: 'no-pr-activity' isbnlib-3.10.14/.github/dependabot.yml000066400000000000000000000002511442216276400175000ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "github-actions" directory: "/" schedule: interval: daily time: "06:00" open-pull-requests-limit: 10 isbnlib-3.10.14/.github/labeler.yml000066400000000000000000000001471442216276400170050ustar00rootroot00000000000000repo: - ./* test: - isbnlib/test/* docs: - docs/* core: - isbnlib/* dev: - isbnlib/dev/* isbnlib-3.10.14/.github/workflows/000077500000000000000000000000001442216276400167075ustar00rootroot00000000000000isbnlib-3.10.14/.github/workflows/basictests.yml000066400000000000000000000047311442216276400216030ustar00rootroot00000000000000name: tests on: push: pull_request: schedule: - cron: '15 5 * * *' jobs: basic-tests-linux: runs-on: ubuntu-latest strategy: fail-fast: false matrix: # https://github.com/actions/setup-python/blob/main/docs/advanced-usage.md#using-the-python-version-input python-version: ['3.9', '3.10', '3.11', '3.12-dev', 'pypy3.9'] env: GITHUB_OS: linux steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} - name: Update pip run: | python -m pip install --upgrade pip - name: Lint the code with flake8 run: | pip install flake8 # stop the build if there are Python syntax errors or undefined names flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics - name: Sleep for 1-30 seconds run: SECONDS=$[ ($RANDOM % 30) + 1 ];echo $SECONDS;sleep "$SECONDS"s shell: bash - name: Test with pytest run: | pip install wheel pytest coverage pytest-cov python -B -m pytest --cov-config=setup.cfg isbnlib/test basic-tests-macos: runs-on: macos-latest strategy: matrix: python-version: [3.8] env: GITHUB_OS: macos steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} - name: Update pip run: | python -m pip install --upgrade pip - name: Test with pytest run: | pip install wheel pytest coverage pytest-cov pytest -v --cov-config=./setup.cfg ./isbnlib/test basic-tests-windows: runs-on: windows-latest strategy: matrix: python-version: [3.x] env: GITHUB_OS: windows steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} - name: Update pip run: | python -m pip install --upgrade pip - name: Test with pytest run: | pip install wheel pytest coverage pytest-cov pytest -v --cov-config=./setup.cfg ./isbnlib/test isbnlib-3.10.14/.github/workflows/codeql-analysis.yml000066400000000000000000000030271442216276400225240ustar00rootroot00000000000000name: "code scanning" on: push: pull_request: schedule: - cron: '0 2 * * 4' jobs: CodeQL-Build: runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v3 with: # We must fetch at least the immediate parents so that if this is # a pull request then we can checkout the head. fetch-depth: 2 # If this run was triggered by a pull request event, then checkout # the head of the pull request instead of the merge commit. - run: git checkout HEAD^2 if: ${{ github.event_name == 'pull_request' }} # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v2 # Override language selection by uncommenting this and choosing your languages # with: # languages: go, javascript, csharp, python, cpp, java # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild uses: github/codeql-action/autobuild@v2 # ℹ️ Command-line programs to run using the OS shell. # 📚 https://git.io/JvXDl # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines # and modify them (or add more) to build your code if your project # uses a compiled language #- run: | # make bootstrap # make release - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v2 isbnlib-3.10.14/.github/workflows/create-release.yaml000066400000000000000000000014161442216276400224560ustar00rootroot00000000000000on: push: tags: - 'v*' name: Create Release jobs: build: name: Create Release runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v3 - name: Check if it is 'NOT RELEASED' shell: bash run: | [[ ! -z $(tail -1 CHANGES.txt | grep -o 'NOT RELEASED\|TENTATIVE') ]] && echo 'NO_RELEASE condition detected! Skip release.' && exit 1 || exit 0 - name: Create Release id: create_release uses: actions/create-release@v1.1.4 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: tag_name: ${{ github.ref }} release_name: Release ${{ github.ref }} body_path: release.md draft: false prerelease: false isbnlib-3.10.14/.github/workflows/wip.yml000066400000000000000000000003401442216276400202260ustar00rootroot00000000000000name: WIP on: pull_request: types: [ opened, synchronize, reopened, edited ] jobs: wip: runs-on: ubuntu-latest env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} steps: - uses: wip/action@v1.1.1 isbnlib-3.10.14/AUTHORS.md000066400000000000000000000004741442216276400147660ustar00rootroot00000000000000 Main Author =========== xlcnd With fine contributions from ---------------------------- Alex Ioannidis Christian Clauss Daniel Himmelstein Deirdre Connolly flopgui mirelsol Nicolas Cisco Robert Schütz XinyuLiu5566 mcepl --- https://github.com/xlcnd/isbnlib/graphs/contributors isbnlib-3.10.14/CHANGES.txt000066400000000000000000000077721442216276400151400ustar00rootroot00000000000000v3.3.3, 2014-06-16 -- Initial release (based in `isbntools 3.3.3)`. v3.3.4, 2014-06-16 -- Fix small bug with wheel package (based in `isbntools 3.3.3)`. v3.3.5, 2014-06-22 -- Fix bug in 'notisbn' (based in `isbntools 3.3.4)`. v3.3.6, 2014-06-30 -- Small improvements and optional ShelveCache. v3.3.7, 2014-07-07 -- Fix issue #2, better debug logging and expose top exceptions. v3.3.8, 2014-07-07 -- Fix wrong logging identifier. v3.3.9, 2014-07-13 -- Mark as not valid ISBN-13 in series not allocated yet. v3.4.1, 2014-07-16 -- Fix bug #7 and small improvements on the API. v3.4.2, 2014-08-13 -- Add `doi2tex` and updated data. v3.4.3, 2015-01-13 -- Better LOOSE regex and allow 'x' in canonical. v3.4.4, 2015-01-26 -- Helpers sprint and fake_isbn. v3.4.5, 2015-02-05 -- Better yield for openl and better log model. v3.4.6, 2015-02-05 -- Fix bug #13. v3.4.7, 2015-02-11 -- Fix bug #14. v3.4.8, 2015-02-25 -- Fix bug #16, add 'desc' and 'cover' features. v3.4.9, 2015-02-27 -- Fix issue #17 and bug #18, data range 20150227. v3.5.1, 2015-03-10 -- New CoversCache and better unicode printing in Windows. v3.5.2, 2015-03-15 -- Fix bug #19, relative paths on coverscache and data range 20150310. v3.5.3, 2015-03-26 -- Add throttling for web services, data range 20150325 and 'in memory' keys cache. v3.5.4, 2015-04-10 -- Issue #20, fix bugs #21 and #22 and data range 20150401. v3.5.5, 2015-04-22 -- Add logging to vias, fix bug #23, and data range 20150422. v3.5.6, 2015-06-03 -- Deprecated 'bouth23' and data range 20150603. v3.5.7, 2015-11-22 -- Support for py35 and pypy3 and data range 20151118. v3.5.8, 2016-03-07 -- Issue #28 (closing down of xISBN service). v3.5.9, 2016-06-17 -- Improved data quality (close #39 and #40) and new cover (close issue #42). v3.6.1, 2016-06-21 -- Improved data quality (#39 and #40), new cover (#42) and streamlined. v3.6.2, 2016-09-06 -- Updated data. v3.6.3, 2016-11-09 -- Updated data. v3.6.4, 2016-11-12 -- Fix bug #46. v3.6.5, 2016-12-08 -- Updated data. v3.6.6, 2017-01-05 -- Fix bug #47. v3.6.7, 2017-03-11 -- Updated data. v3.6.8, 2017-03-31 -- New functions: check_digit10 and check_digit13. v3.7.1, 2017-05-24 -- Fix #43 (bump middle version). v3.7.2, 2017-06-19 -- Restore xID (improved data quality close #28). v3.7.3, 2018-01-08 -- Updated data. v3.7.4, 2018-01-08 -- Add support for CSL-JSON format (close #48). v3.8.1, 2018-01-24 -- BREAK: stop support for py26, py33 and isbndb. v3.8.2, 2018-01-24 -- Fix bug 'in_virtual'. v3.8.3, 2018-01-29 -- Add 'wcat' to editions. v3.8.4, 2018-03-06 -- Solve issues with non-ASCII searches in 'from_words'. v3.8.5, 2018-06-14 -- NOT RELEASED. v3.9.1, 2018-07-02 -- Issue #51 (closing down of xISBN service). v3.9.2, 2018-09-28 -- Updated data. v3.9.3, 2018-10-05 -- Make it easier to override 'WEBService.data'. v3.9.4, 2019-01-18 -- Fix bibjson and updated data. v3.9.5, 2019-02-10 -- PR #53 and updated data. v3.9.6, 2019-02-24 -- Performance improvements (close #55). v3.9.7, 2019-05-06 -- Editions is now cached and consistent return types. v3.9.8, 2019-05-06 -- Fix bug #58 on 'editions'. v3.9.9, 2019-10-17 -- Better caching, improved security, fix 'catch all exception'. v3.9.10, 2019-12-20 -- Fix issues: 61 (close #61) and 62 (close #62). v3.9.11, 2019-12-20 -- NOT RELEASED. v3.10.0, 2020-03-23 -- Add a 'classify' service (oclc.org). v3.10.1, 2020-05-18 -- Add a 'wiki' (wikipedia) provider for metadata and editions. v3.10.2, 2020-05-26 -- Fix 'goob' and 'wiki' quirks (issue #64 and #65). v3.10.3, 2020-05-27 -- Delete a (quick debug) print statement. v3.10.4, 2020-11-17 -- Add 'Isbn' and fix #67. v3.10.5, 2020-12-31 -- Fix 'csv' and updated data. v3.10.6, 2021-01-26 -- Fix 'wiki' (close #75). v3.10.7, 2021-04-12 -- Common url for GB services. v3.10.8, 2021-05-10 -- New 'Authors' parsing strategy for 'wiki'. v3.10.9, 2021-11-01 -- Fix 'editions'. v3.10.10, 2022-02-25 -- Fix issue #87. v3.10.11, 2022-10-18 -- Fix issues #107 #114. v3.10.12, 2022-10-18 -- Fix tests on 'master'. v3.10.13, 2023-02-15 -- Fix issues #119, #121 and updated data. v3.10.14, 2023-04-26 -- Fix issue #123. isbnlib-3.10.14/CODE_OF_CONDUCT.md000066400000000000000000000125531442216276400161170ustar00rootroot00000000000000 # 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, caste, color, 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 xlcnd@outlook.com. 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][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. [homepage]: https://www.contributor-covenant.org [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html [Mozilla CoC]: https://github.com/mozilla/diversity [FAQ]: https://www.contributor-covenant.org/faq [translations]: https://www.contributor-covenant.org/translations isbnlib-3.10.14/CONTRIBUTING.md000066400000000000000000000055471442216276400155560ustar00rootroot00000000000000# How to Contribute `isbnlib` has a very small code base, so it is a good project to begin your adventure in open-source. > **NOTE**: By contributing you agree with the [license terms](LICENSE-LGPL.txt) (**LGPL v3**) of the project. ## Main Steps 1. Make sure you have a [GitHub account](https://github.com/signup/free) 2. Submit a ticket for your issue or idea (**ONE ticket for each issue or idea**) ([help](https://www.youtube.com/watch?v=TJlYiMp8FuY)), on https://github.com/xlcnd/isbnlib/issues, (if possible wait for some feedback before any serious commitment... :) 3. **Fork** the repository on GitHub and **clone it locally** ([help](https://help.github.com/articles/fork-a-repo)). 4. `pip install -r requirements-dev.txt` (at your local directory). 5. Do your code... (**remember the code must run on python 3.6+ and be OS independent**, you will find [Github Actions](https://docs.github.com/en/actions) very handy for testing with this requirement!) 6. Write tests for your code using `pytest` and put then in the directory `isbnlib/test` 7. Pass **all tests** and with **coverage > 90%**. Check the coverage locally with the command `pytest -v --cov-config=setup.cfg isbnlib/test`. 8. **Check if all requirements are fulfilled**! 9. **Push** your local changes to GitHub and make there a **pull request** ([help](https://help.github.com/articles/using-pull-requests/)) **using `dev` as base branch** (by the way, we follow the *fork & pull* model with this small change). **VERY IMPORTANT:** Don't put in the same pull request unrelated changes in the code, make one pull request for each set of related changes! ## Style Your code **must** be [PEP8](http://legacy.python.org/dev/peps/pep-0008/) compliant and be concise as possible (use `yapf` then check it with `flake8` and `pylint`). Use doc strings ([PEP257](http://legacy.python.org/dev/peps/pep-0257/)) for users and comments (**few**) as signposts for fellow developers. Make your code as clear as possible. ## Red Lines **Don't submit pull requests that are only comments to the code that is already in the repo!** Don't expect kindness if you do that :) You **can** comment and give suggestions on the code at the [issues](https://github.com/xlcnd/isbnlib/issues/5) page or use the link **`Give feedback`** at the bottom of each Github page. **No** doc tests! Remember point 6 above. **Don't** submit pull requests without checking points 8 and 9! ## Suggestions Goto [issues/enhancement](https://github.com/xlcnd/isbnlib/issues?labels=enhancement&page=1&state=open) for possible enhancements to the code. If you have some idea that is not there enter your own. Select some focused issue and enter some comments on how you plan to tackle it. ## Important If you don't have experience with these issues, don't be put off by these requirements, see them as a learning opportunity. Thanks! isbnlib-3.10.14/COPYRIGHT.txt000066400000000000000000000014141442216276400154230ustar00rootroot00000000000000 isbnlib - tools for extracting, cleaning and transforming ISBNs Copyright (C) 2014-2023 Alexandre Lima Conde SPDX-License-Identifier: LGPL-3.0-or-later This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . isbnlib-3.10.14/LICENSE-LGPL-3.0.txt000066400000000000000000000167431442216276400162020ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. isbnlib-3.10.14/PLUGIN.zip000066400000000000000000000254251442216276400150440ustar00rootroot00000000000000PK fjLPLUGIN-isbndb/UT ԣZԣZux PKOKX^PLUGIN-isbndb/.editorconfigUT eK0ZXZux 0{=Ạ)Ҥ ) #{e/%(!A \|3_վC`_{ VL'gpFYtukʠV9>S GŤ1 n$NRdWm.hMJr3CjrcUd i"x+zF܌0h˒ SF+l>c,_G0h- PKOKePLUGIN-isbndb/.gitattributesUT eK0ZXZux %= 0 AB(.: -k[)MN_zq[UX+2wP ܢ7wN #:#Y>ISg3KH(Ldxi<0ӿR.?u9%;CSPKIVGM)PLUGIN-isbndb/.gitignoreUT ֹ[ֹ[ux - {DB/C2d nq\6ߴxД#Nja%~HuN[4r=E  `lp`wV탤\iۙS{![}YBU9 ?PK lFM--PLUGIN-isbndb/CHANGES.txtUT ٸ[ڸ[ux v0.0.1, 2018-10-06 -- Initial alpha release. PK ZAPv!G.PLUGIN-isbndb/INSTRUCTIONSuSMO1W \B>4RP-=!g=Zڮ=߱wE(>iC|ěC[h;:7śPK%|3Lp9 PLUGIN-isbndb/LICENSE-LGPL.txtUT bZ[u\ux Ymoܸ_AWPp}N—3K~J]6%%o̐u|89g:y񳺻}x~t}?Í¿ۏVYR[^|ǢP7nwv?T1Fs}[C[.՟]ŋuX/߼Kn?8AolיJuNt[ʆU+k5Pn-vֶ4m0reߘ[(WVnH|:M,>FX?WMk}|uϰmyAA,H\&=ZD ݮ6;_xDkB`5B LY/z\YVAH\ʛ5$W|QłlݷĊ^5wv?r4 Y0a?єEp3B/u ڒO9)7YYOSO^"wAiۃ j%pEZF{h~kmJBso!c)2P0۰,$[XO:=9WTaa*S`KX)5g|u1q/c_՗E$mEN)rm@l+/+xOG]1\:&P&4#b],g( n&J} XȎhT#|-gT%ł63l8kAJvWGl|-eș2{Ԗz8$T'ΞyT_Kc?n`1lG>@AH []*g+CڮKRU~t&mUvm XG/E5tiqqPThщ &Guߖ E)tecY)H5Y~ X lW zӊv63E1J_LFqEM@d&lkTԚy$grF@K\LPr-hm\Dbہ4 #h%4"^#^65?$B%}wn5= {Yf~ L!'. p7Iw6am^,Τm-1c]7L=(P}LZ:cEH Ubf="L/%0ЌdO꿕Y f=Ja9@ߟ+lH`_e6G 1b1Ӣ&E -)mia [58q"(xA-woz+)"oiePe3˫+SYge|Mԑs#yR!qxv5s S/R)_ywjNV ɝ|#3T`3i$o= j䈳@%2tm^ SCSLꑄ\~ @cipCF{B`u‰8Xn=S~Q;&zD\8uZ3PL:L>"x! WI!V7)qLHRqA"'~ʂO\=bROvHgFY2^7]D@.INemhEfu"'bXOцBٟyܧ~Ĺx}֚}P<\2zlt- FMlEфKc! JPCP5_UVF#<`l(OD"*}A,z8BV`]:) P`?R*IM5g9*& ^DH~x#͊-?ri>yИP+JSSk( ͧS/=õui~!J.ma<6@~D(uO)C=Xn]sr1twA)o8%&kbǢ(hЌ JP%˧xI;W _kPK4XAPq)PLUGIN-isbndb/MANIFEST.inK)MIU+(By)\PKAqSB MzhPLUGIN-isbndb/README.rstURMK0W /ୈ?xڤl;&1I+N[dgf=fmtВ@v# \ Cr4u^JHGj6Rj:<<O)+MĖK.qM.s]xwV)'h Bs\ᛋlZo_\:㴙Y 'R3t9Teaʝwr.A+cՂg#)5ǫ& PK؄VNP ՆPLUGIN-isbndb/WARNINGUT %p\%p\ux %n0D VK ⸉"ZYQofμc9u^CPR2Sf,):WP39ʄԏ>VSx?| n 2 >w^q9nj tc< %5Iz65 kV/k,˓rNvfV}m?PK }gjLPLUGIN-isbndb/isbnlib_isbndb/UT ֣Z֣Zux PK[pQuED$(PLUGIN-isbndb/isbnlib_isbndb/__init__.pymA ER{g`@#f*pXgmgrB*wF I2RUJM+%nd#ozci .pK:-cH;艅!zF5^ْ;9BQ-!o#K1OV5joaKZŽ>PKVN_1 'PLUGIN-isbndb/isbnlib_isbndb/_isbndb.pyUT &p\&p\ux Vmo6_quP507u`9Ɋ3Ze.S/ߑd;Rws/ C("#(9t &w7 Zej d -iQMtNd>}hxhKdߋ2"2׈Ε^N/`ˤ"3hp"ҜgHʺ|}5n\,e&b46Yv3 <&AH)BCw:Q)$=g{?x5M;<ͅԐ86SNg-EjIOڸ'.cm+ґ)KC>VЛwgbѢ¾,ȾX/Rd͆l*=y? }Lo& QP ] s }yY #[Y,M` ـs,t4_i{7KlTyadIzr{O'sG'̓gw.>} fe ,| 0bkRL tLYplLdۿҰhtN;j\'l !UUՆamſ4 3knTҲjp Oqѐ%jtx _tkYM͍:HB=q=Ӓ^1EASY uZ`V Y.:ncڦV3ߌ0D79Qk ,f9at4m)[Xƫk!/ 2jLq[JKϪb){۞WՆMrJrDK!Hq6A^-O[jUK ah^cli±ژL2:z~]nM<풝ooJd}7,|@gT9LJdǚXjyy x|\KN+m}*bS\\o\\>tѕ- ^F:)x(+Ny-G^n2YrVo)[\I㔎 7+4_Z ˬmIÝcxa)O&+Ͱ&} aQ<q%0EY csv(yWe/U|{x>'.ZMGdzÛPK^1PYE-n"PLUGIN-isbndb/requirements-dev.txtE yو蒱wA (ۯ%&דg'F-ЈٚZ+8Cߪa[4QkCs3)hL9~8.P T@5 ޮÍ]@ $sTR O N }c?; 2MܺQM1і*?&eixPKXAP~i0PLUGIN-isbndb/setup.cfg=On0+8#"Tz͡RťP1$+ۊM !N;;;sQ̐ d⫟0NRSmLˮ1ax9"B -Kt=17C\D4/mᅺ䙂dORNª=-<&GyzoM_u^Po}]mvi2W f5Ŝ܍`^.ک)C|&9PKXAP5163PLUGIN-isbndb/setup.py_o0)N!DRڡe[+Z$ڧBN| vm' MsiAZUr3 x@")r nʈ fbYOCAndj0CK(ğRiK?W:/7_r ځ&p<2 p4h ,Aa܈I9D3e\& P 'ư-C*w+-SM]_X$ENaut3=,}艇IOANTtE9y(S8au^䜑+ rdE7yyW$'X*!룙3Ճ:PL&- ŗ@9#; hw],luC鏎=S1_B:c.thW=hK= lL{XyI#9Ί۵{.VFo is㺴x#uc 7_Q+SXu_PK fjLAPLUGIN-isbndb/UTԣZux PKOKX^HPLUGIN-isbndb/.editorconfigUTeK0Zux PKOKefPLUGIN-isbndb/.gitattributesUTeK0Zux PKIVGM)FPLUGIN-isbndb/.gitignoreUTֹ[ux PK lFM--PLUGIN-isbndb/CHANGES.txtUTٸ[ux PK? ZAPv!G.$ PLUGIN-isbndb/INSTRUCTIONS ^ ^ ^ PK%|3Lp9 PLUGIN-isbndb/LICENSE-LGPL.txtUTbZux PK?4XAPq)$ PLUGIN-isbndb/MANIFEST.in PK?AqSB Mzh$ PLUGIN-isbndb/README.rst u,u,u,PK؄VNP ՆPLUGIN-isbndb/WARNINGUT%p\ux PK }gjLAPLUGIN-isbndb/isbnlib_isbndb/UT֣Zux PK?[pQuED$($ PLUGIN-isbndb/isbnlib_isbndb/__init__.py ޫ ޫ ޫ PKVN_1 'PLUGIN-isbndb/isbnlib_isbndb/_isbndb.pyUT&p\ux PK?ewP"$APLUGIN-isbndb/isbnlib_isbndb/test/ JvjJvPK? }n6Li:q+$ EPLUGIN-isbndb/isbnlib_isbndb/test/README.md 9ڰ9PK?  K2-$ PLUGIN-isbndb/isbnlib_isbndb/test/__init__.py }ȐsڰKP?PK?b}Pl<S2$ PLUGIN-isbndb/isbnlib_isbndb/test/test_metadata.py ړ'ړ'ړ'PK?^1PYE-n"$ }PLUGIN-isbndb/requirements-dev.txt ¾,¾,¾,PK?XAP~i0$ cPLUGIN-isbndb/setup.cfg :=:=:=PK?XAP5163$ sPLUGIN-isbndb/setup.py    PK?AqS*k4$ PLUGIN-isbndb/tox.ini YYYPKA"isbnlib-3.10.14/README.rst000066400000000000000000000342711442216276400150100ustar00rootroot00000000000000 .. image:: https://github.com/xlcnd/isbnlib/workflows/tests/badge.svg :target: https://github.com/xlcnd/isbnlib/actions :alt: Built Status .. image:: https://img.shields.io/github/issues/xlcnd/isbnlib/bug.svg?label=bugs&style=flat :target: https://github.com/xlcnd/isbnlib/labels/bug :alt: Bugs .. image:: https://img.shields.io/pypi/dm/isbnlib.svg?style=flat :target: https://pypi.org/project/isbnlib/ :alt: PYPI Downloads Info ==== ``isbnlib`` is a (pure) python library that provides several useful methods and functions to validate, clean, transform, hyphenate and get metadata for ISBN strings. Install ------- From the command line, enter (in some cases you have to precede the command with ``sudo``): .. code-block:: bash $ pip install isbnlib If you use linux systems, you can install using your distribution package manager (all major distributions have packages ``python-isbnlib`` and ``python3-isbnlib``), however (usually) are **very old and don't work well anymore**! ISBN ---- The official form of an ISBN is something like ``ISBN 979-10-90636-07-1``. However for most applications only the numbers are important, you can always 'mask' them if you need (see below). This library works mainly with 'striped' ISBNs (only digits and X) like '0826497527'. You can strip an ISBN-like string by using ``canonical(isbnlike)``. You can 'mask' the ISBN by using ``mask(isbn)``. So in the examples below, when you see 'isbn' in the argument, it is a 'striped' ISBN, when the argument is an 'isbnlike' it is a string like ``ISBN 979-10-90636-07-1`` or even something dirty like ``asdf 979-10-90636-07-1 bla bla``. Two important concepts: **valid ISBN** should be an ISBN that was built according with the rules, this is distinct from **issued ISBN** that is an ISBN that was already issued to a publisher (this is the usage of the libraries and most of the web services). However *isbn.org*, probably by legal reasons, merges the two! So, according to *isbn-international.org*, '9786610326266' is not valid (because the block 978-66... has not been issued yet, however if you use ``is_isbn13('9786610326266')`` you will get ``True`` (because '9786610326266' follows the rules of an ISBN). But the situation is even murkier, try ``meta('9786610326266')`` and you will see that this ISBN was already used! If possible, work with ISBNs in the isbn-13 format (since 2007, only are issued ISBNs in the isbn-13 format). You can always convert isbn-10 to isbn-13, but **not** the reverse (read this_). Read more about ISBN at isbn-international.org_ or wikipedia_. Main Functions -------------- ``is_isbn10(isbn10like)`` Validates as ISBN-10. ``is_isbn13(isbn13like)`` Validates as ISBN-13. ``to_isbn10(isbn13)`` Transforms isbn-13 to isbn-10. ``to_isbn13(isbn10)`` Transforms isbn-10 to isbn-13. ``canonical(isbnlike)`` Keeps only digits and X. You will get strings like `9780321534965` and `954430603X`. ``clean(isbnlike)`` Cleans ISBN (only legal characters). ``notisbn(isbnlike, level='strict')`` Check with the goal to invalidate isbn-like. ``get_isbnlike(text, level='normal')`` Extracts all substrings that seem like ISBNs (very useful for scraping). ``get_canonical_isbn(isbnlike, output='bouth')`` Extracts ISBNs and transform them to the canonical form. ``ean13(isbnlike)`` Transforms an `isbnlike` string into an EAN13 number (validated canonical ISBN-13). ``doi(isbn)`` Returns a DOI's ISBN-A from a ISBN-13. ``mask(isbn, separator='-')`` `Mask` (hyphenate) a canonical ISBN. ``info(isbn)`` Gets the language or country assigned to this ISBN. ``meta(isbn, service='default')`` Gives you the main metadata associated with the ISBN. As `service` parameter you can use: ``'goob'`` uses the **Google Books service** (**no key is needed**) and **is the default option**, ``'wiki'`` uses the **wikipedia.org** api (**no key is needed**), ``'openl'`` uses the **OpenLibrary.org** api (**no key is needed**). You can enter API keys with ``config.add_apikey(service, apikey)`` (see example below). The output can be formatted as ``bibtex``, ``csl`` (CSL-JSON), ``msword``, ``endnote``, ``refworks``, ``opf`` or ``json`` (BibJSON) bibliographic formats with ``registry.bibformatters``. Now, you can extend the functionality of this function by adding plugins, more metadata providers or new bibliographic formatters (check_ for available plugins). ``editions(isbn, service='merge')`` Returns the list of ISBNs of editions related with this ISBN. By default uses 'merge' (merges 'openl', 'thingl' and 'wiki'), but other providers are available: 'openl' (uses the search API from **Open Library**), 'thingl' (uses the service ThingISBN from **LibraryThing**), 'wiki' (uses the service Citation from **Wikipedia**) and 'any' (first tries 'wiki', if no data then 'openl'). ``isbn_from_words(words)`` Returns the most probable ISBN from a list of words (for your geographic area). ``goom(words)`` Returns a list of references from **Google Books multiple references**. ``classify(isbn)`` Returns a dictionary of **classifiers** for a canonical ISBN. For the meaning of these classifiers see OCLC_. Most of the data in the underlying service are for books in english. ``desc(isbn)`` Returns a small description of the book. *Almost all data available are for US books!* ``cover(isbn)`` Returns a dictionary with the url for cover. *Almost all data available are for US books!* ``doi2tex(DOI)`` Returns metadata formatted as BibTeX for a given DOI. ``ren(filename)`` Renames a file using metadata from an ISBN in his filename. See files test_core_ and test_ext_ for **a lot of examples**. Plugins ------- You can extend the functionality of the library by adding plugins (for now, just new metadata providers or new bibliographic formatters). For available plugins check_ here. After install, your plugin will blend transparently in ``isbnlib`` (you will have more options in ``meta`` and ``bibformatters``). For Devs ======== API's Main Namespaces --------------------- In the namespace ``isbnlib`` you have access to the **core functions**: ``is_isbn10``, ``is_isbn13``, ``to_isbn10``, ``to_isbn13``, ``canonical``, ``clean``, ``notisbn``, ``get_isbnlike``, ``get_canonical_isbn``, ``mask``, ``info``, ``check_digit10``, ``check_digit13``, ``doi`` and ``ean13``. In addition, you have access to **metadata functions**, namely: ``meta``, ``editions``, ``ren``, ``desc``, ``cover``, ``goom``, ``classify``, ``doi2tex`` and ``isbn_from_words``. The exceptions raised by these methods can all be caught using ``ISBNLibException``. You can extend the lib by using the classes and functions exposed in namespace ``isbnlib.dev``, namely: * ``WEBService`` a class that handles the access to web services (just by passing an url) and supports ``gzip``. You can subclass it to extend the functionality... but probably you don't need to use it! It is used in the next class. * ``WEBQuery`` a class that uses ``WEBService`` to retrieve and parse data from a web service. You can build a new provider of metadata by subclassing this class. His main methods allow passing custom functions (*handlers*) that specialize them to specific needs (``data_checker`` and ``parser``). It implements a **throttling mechanism** with a default rate of one call per second per service. * ``Metadata`` a class that structures, cleans and 'validates' records of metadata. His method ``merge`` allows to implement a simple merging procedure for records from different sources. The main features of this class, can be implemented by a call to the ``stdmeta`` function instead! * ``vias`` exposes several functions to put calls to services, just by passing the name and a pointer to the service's ``query`` function. ``vias.parallel`` allows to put threaded calls. You can use ``vias.serial`` to make serial calls and ``vias.multi`` to use several cores. The default is ``vias.serial``. The exceptions raised by these methods can all be caught using ``ISBNLibDevException`` (or, more general, ``ISBNLibException``). You **shouldn't raise** this exception in your code, only raise the specific exceptions exposed in ``isbnlib.dev`` whose name ends in Error. In ``isbnlib.dev.helpers`` you can find several methods, that we found very useful, some of then are only used in ``isbntools`` (*an app and framework* that uses ``isbnlib``). With ``isbnlib.config`` you can read and set configuration options: change timeouts with ``seturlopentimeout`` and ``setthreadstimeout``, access api keys with ``apikeys`` and add new one with ``add_apikey``, access and set generic and user-defined options with ``options.get('OPTION1')`` and ``set_option``. Finally, from ``isbnlib.registry`` you can change the metadata service to be used by default (``setdefaultservice``), add a new service (``add_service``), access bibliographic formatters for metadata (``bibformatters``), set the default formatter (``setdefaultbibformatter``), add new formatters (``add_bibformatter``) and set a new cache (``set_cache``) (e.g. to switch off the cache ``set_cache(None)``). The cache only works for calls through metadata functions. These changes only work for the 'current session', so should be done always before calling other methods. Let us concretize these points with a small example. Suppose you want a small script to get metadata using ``Open Library`` formatted in BibTeX. A minimal script would be: .. code-block:: python from isbnlib import meta from isbnlib.registry import bibformatters SERVICE = "openl" # now you can use the service isbn = "9780446310789" bibtex = bibformatters["bibtex"] print(bibtex(meta(isbn, SERVICE))) Patterns of Usage ----------------- The library implements a very simple API with sensible defaults, but there are cases that need your attention (see case 3 below). A. You only need **core functions**: .. code-block:: python # import the core functions you need from isbnlib import canonical, is_isbn10, is_isbn13 isbn = canonical("978-0446310789") if is_isbn13(isbn): ... ... B. You need also **metadata functions**, with **default config**: .. code-block:: python from isbnlib import canonical, meta, description isbn = canonical("978-0446310789") data = meta(isbn) ... C. You need also **metadata functions**, with **special config**: *Lets suppose you need to add an api key for a metadata plugin and change the cache too*. .. code-block:: python from myapp.utils import MyCache # import the functions you need, plus 'config' and 'registry' from isbnlib import canonical, config, meta, registry # you should use 'config' first config.add_apikey("isbndb", "kjshdfkjahsdflkjh") # then 'registry' registry.set_cache(MyCache()) # Only now you should use metadata functions # (there are no adaptions for core functions, # so they can be used at any moment) isbn = canonical("978-0446310789") data = meta(isbn, service="isbndb") ... D. You want to build a **plugin** or use **isbnlib.dev** in your code: You should study very carefully the **public** methods in ``dir(isbnlib.dev)``, start with this template_ and follow the instructions there. For inspiration take a look at goob_. Most of the public bibliographic catalog services return data in **SRU** or **Unimarc** format. It is very easy to write a customer **plugin** for these services, just use porbase_ (SRU) or sbn_ (Unimarc) as templates and consult this project_. Caveats ------- 1. These classes are optimized for one-call to services and not for batch calls. 2. If you inspect the library, you will see that there are a lot of private modules (their name starts with '_'). These modules **should not** be accessed directly since, with high probability, your program will break with a further version of the library! Projects using *isbnlib* ======================== **Open Library** https://github.com/internetarchive/openlibrary **NYPL Library Simplified** https://github.com/NYPL-Simplified **RERO ILS** https://github.com/rero/rero-ils **CERN CDS RDM** https://github.com/CERNDocumentServer/cds-rdm **ResearchHub** https://github.com/ResearchHub/researchhub-backend **Manubot** https://github.com/manubot **isbntools** https://github.com/xlcnd/isbntools **isbnsrv** https://github.com/xlcnd/isbnsrv See the full list here_. Help ==== If you need help, please take a look at github_ or post a question on stackoverflow_ . .. _github: https://github.com/xlcnd/isbnlib/discussions .. _range: https://www.isbn-international.org/range_file_generation .. _isbntools: https://pypi.python.org/pypi/isbntools .. _sourcegraph: http://bit.ly/ISBNLib_srcgraph .. _readthedocs: http://bit.ly/ISBNLib_rtd .. _stackoverflow: http://stackoverflow.com/search?tab=newest&q=isbnlib .. _test_core: https://github.com/xlcnd/isbnlib/blob/master/isbnlib/test/test_core.py .. _test_ext: https://github.com/xlcnd/isbnlib/blob/master/isbnlib/test/test_ext.py .. _isbn-international.org: https://www.isbn-international.org/content/what-isbn .. _wikipedia: http://en.wikipedia.org/wiki/International_Standard_Book_Number .. _python-future.org: http://python-future.org/compatible_idioms.html .. _issue: https://github.com/xlcnd/isbnlib/issues/28 .. _check: https://pypi.python.org/pypi?%3Aaction=search&term=isbnlib_&submit=search .. _template: https://github.com/xlcnd/isbnlib/blob/dev/PLUGIN.zip .. _goob: https://github.com/xlcnd/isbnlib/blob/dev/isbnlib/_goob.py .. _search: https://pypi.python.org/pypi?%3Aaction=search&term=isbnlib&submit=search .. _51: https://github.com/xlcnd/isbnlib/issues/51 .. _here: https://github.com/xlcnd/isbnlib/network/dependents?package_id=UGFja2FnZS01MjIyODAxMQ%3D%3D .. _OCLC: http://classify.oclc.org/classify2/ .. _this: https://bisg.org/news/479346/New-979-ISBN-Prefixes-Expected-in-2020.htm .. _sbn: https://github.com/arangb/isbnlib-sbn/blob/main/isbnlib_sbn/_sbn.py .. _porbase: https://github.com/xlcnd/isbnlib-porbase/blob/dev/isbnlib_porbase/_porbase.py .. _project: https://github.com/xlcnd/isbnlib/issues?q=is%3Aissue+is%3Aopen+label%3Aproject isbnlib-3.10.14/SECURITY.md000066400000000000000000000006021442216276400151010ustar00rootroot00000000000000# Security Policy ## Supported Versions If a vulnerability is found a new maintenance version will be release as soon as possible. All the previous versions should be considered unsafe. ## Reporting a Vulnerability If you found a vulnerability, please send an email to xlcnd@outlook.com, and I will give you access to a private part of the repository to discuss further the issue. isbnlib-3.10.14/isbnlib/000077500000000000000000000000001442216276400147345ustar00rootroot00000000000000isbnlib-3.10.14/isbnlib/__init__.py000066400000000000000000000036071442216276400170530ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa """Library to validate, clean, transform and get metadata of ISBN strings (for devs).""" # Define isbnlib API and set lib environment import logging as _logging from ._core import ( EAN13, GTIN13, RE_ISBN10, RE_ISBN13, RE_LOOSE, RE_NORMAL, RE_STRICT, canonical, check_digit10, check_digit13, clean, get_canonical_isbn, get_isbnlike, is_isbn10, is_isbn13, notisbn, to_isbn10, to_isbn13, ) from ._data.data4info import RDDATE from ._doitotex import doi2tex from ._exceptions import ( ISBNLibException, NotRecognizedServiceError, NotValidDefaultFormatterError, NotValidDefaultServiceError, NotValidISBNError, PluginNotLoadedError, quiet_errors, ) from ._ext import cover, desc, doi, editions, info, isbn_from_words, mask, meta, ren from ._goom import query as goom from ._isbn import Isbn from ._oclc import query_classify as classify # config _logging for lib _nh = _logging.NullHandler() _logging.getLogger('isbnlib').addHandler(_nh) # alias ean13 = EAN13 ISBN13 = EAN13 # dunders __all__ = ( 'canonical', 'check_digit10', 'check_digit13', 'classify', 'clean', 'cover', 'desc', 'doi', 'doi2tex', 'ean13', 'EAN13', 'editions', 'get_canonical_isbn', 'get_isbnlike', 'goom', 'GTIN13', 'info', 'Isbn', 'ISBN13', 'isbn_from_words', 'ISBNLibException', 'is_isbn10', 'is_isbn13', 'mask', 'meta', 'notisbn', 'NotRecognizedServiceError', 'NotValidDefaultFormatterError', 'NotValidDefaultServiceError', 'NotValidISBNError', 'PluginNotLoadedError', 'quiet_errors', 'RDDATE', 'ren', 'to_isbn10', 'to_isbn13', '__support__', '__version__', ) __version__ = '3.10.14' __support__ = 'py27, py35, py36, py37, py38, py39, py310, py311, pypy, pypy3' isbnlib-3.10.14/isbnlib/_core.py000066400000000000000000000167441442216276400164110ustar00rootroot00000000000000# -*- coding: utf-8 -*- # isbnlib - tools for extracting, cleaning and transforming ISBNs # Copyright (C) 2014-2023 Alexandre Lima Conde # SPDX-License-Identifier: LGPL-3.0-or-later # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . """isbnlib main file for ISBN manipulation. Tools for extracting, cleaning, transforming and validating ISBN ids. """ import logging import re LOGGER = logging.getLogger(__name__) RE_ISBN10 = re.compile(r'ISBN\x20(?=.{13}$)\d{1,5}([- ])\d{1,7}' r'\1\d{1,6}\1(\d|X)$|[- 0-9X]{10,16}') RE_ISBN13 = re.compile(r'97[89]{1}(?:-?\d){10,16}|97[89]{1}[- 0-9]{10,16}') RE_STRICT = re.compile( r'^(?:ISBN(?:-1[03])?:? )?(?=[0-9X]{10}$|' r'(?=(?:[0-9]+[- ]){3})' r'[- 0-9X]{13}$|97[89][0-9]{10}$|' r'(?=(?:[0-9]+[- ]){4})' r'[- 0-9]{17}$)(?:97[89][- ]?)?[0-9]{1,5}' r'[- ]?[0-9]+[- ]?[0-9]+[- ]?[0-9X]$', re.I | re.M | re.S, ) RE_NORMAL = re.compile( r'97[89]{1}-?[0-9]{10}|' r'97[89]{1}-[-0-9]{13}|' r'\d{9}[0-9X]{1}|' r'[-0-9X]{10,16}', re.I | re.M | re.S, ) RE_LOOSE = re.compile(r'[- 0-9X]{10,19}', re.I | re.M | re.S) ISBN13_PREFIX = '978' # just the prefix with isbn-10 LEGAL = '0123456789xXisbnISBN- ' def check_digit10(firstninedigits): """Check sum ISBN-10.""" # minimum checks if len(firstninedigits) != 9: return '' try: int(firstninedigits) except ValueError: # pragma: no cover return '' # checksum val = sum( (i + 2) * int(x) for i, x in enumerate(reversed(firstninedigits))) remainder = int(val % 11) if remainder == 0: tenthdigit = 0 else: tenthdigit = 11 - remainder if tenthdigit == 10: tenthdigit = 'X' return str(tenthdigit) def check_digit13(firsttwelvedigits): """Check sum ISBN-13.""" # minimum checks if len(firsttwelvedigits) != 12: return '' try: int(firsttwelvedigits) except ValueError: # pragma: no cover return '' # checksum val = sum( (i % 2 * 2 + 1) * int(x) for i, x in enumerate(firsttwelvedigits)) thirteenthdigit = 10 - int(val % 10) if thirteenthdigit == 10: thirteenthdigit = '0' return str(thirteenthdigit) def _check_structure10(isbn10like): """Check structure of an ISBN-10.""" return bool(re.match(RE_ISBN10, isbn10like)) def _check_structure13(isbn13like): """Check structure of an ISBN-13.""" return bool(re.match(RE_ISBN13, isbn13like)) def is_isbn10(isbn10): """Validate as ISBN-10.""" isbn10 = canonical(isbn10) if len(isbn10) != 10: return False # pragma: no cover return bool(not check_digit10(isbn10[:-1]) != isbn10[-1]) def is_isbn13(isbn13): """Validate as ISBN-13.""" isbn13 = canonical(isbn13) if len(isbn13) != 13: return False # pragma: no cover if isbn13[0:3] not in ('978', '979'): return False return bool(not check_digit13(isbn13[:-1]) != isbn13[-1]) def to_isbn10(isbn13): """Transform isbn-13 to isbn-10.""" isbn13 = canonical(isbn13) # Check prefix if isbn13[:3] != ISBN13_PREFIX: return isbn13 if len(isbn13) == 10 and is_isbn10(isbn13) else '' if not is_isbn13(isbn13): return '' isbn10 = isbn13[3:] check = check_digit10(isbn10[:-1]) # Change check digit return isbn10[:-1] + check if check else '' def to_isbn13(isbn10): """Transform isbn-10 to isbn-13.""" isbn10 = canonical(isbn10) if len(isbn10) == 13 and is_isbn13(isbn10): return isbn10 if not is_isbn10(isbn10): return '' isbn13 = ISBN13_PREFIX + isbn10[:-1] check = check_digit13(isbn13) return isbn13 + check if check else '' def canonical(isbnlike): """Keep only numbers and X.""" numb = [c for c in isbnlike if c in '0123456789Xx'] if numb and numb[-1] == 'x': numb[-1] = 'X' isbn = ''.join(numb) # Filter some special cases if (isbn and len(isbn) not in (10, 13) or isbn in ('0000000000', '0000000000000', '000000000X') or isbn.find('X') not in (9, -1) or isbn.find('x') != -1): return '' return isbn def clean(isbnlike): """Clean ISBN (only legal characters).""" cisbn = [c for c in isbnlike if c in LEGAL] buf = re.sub(r'\s*-\s*', '-', ''.join(cisbn)) return re.sub(r'\s+', ' ', buf).strip() def notisbn(isbnlike, level='strict'): """Check with the goal to invalidate isbn-like. level: 'strict' when certain they are not ISBNs (default) 'loose' only filters obvious NO ISBNs """ if level not in ('strict', 'loose'): # pragma: no cover LOGGER.error('level as no option %s', level) return None isbnlike = canonical(isbnlike) if len(isbnlike) not in (10, 13): return True if level != 'strict': return False if len(isbnlike) == 10: return not is_isbn10(isbnlike) return not is_isbn13(isbnlike) def get_isbnlike(text, level='normal'): """Extract all substrings that seem like ISBNs. level: strict almost as certain they are ISBNs normal (default) loose catch many as possible """ if level == 'normal': # pragma: no cover isbnlike = RE_NORMAL elif level == 'strict': isbnlike = RE_STRICT elif level == 'loose': isbnlike = RE_LOOSE else: LOGGER.error('level as no option %s', level) return [] return isbnlike.findall(text) def get_canonical_isbn(isbnlike, output='bouth'): """Extract ISBNs and transform them to the canonical form. output: isbn10 isbn13 bouth (default) """ if output not in ('bouth', 'isbn10', 'isbn13'): # pragma: no cover LOGGER.error('output as no option %s', output) return '' regex = RE_NORMAL match = regex.search(isbnlike) if match: # Get only canonical characters cisbn = canonical(match.group()) if not cisbn: return '' # Split into a list chars = list(cisbn) # Remove the last digit from `chars` and assign it to `last` last = chars.pop() buf = ''.join(chars) if len(chars) == 9: # Compute the ISBN-10 checksum digit check = check_digit10(buf) else: # Compute the ISBN-13 checksum digit check = check_digit13(buf) # If checksum OK return a `canonical` ISBN if str(check) == last: if output == 'bouth': return cisbn if output == 'isbn10': return cisbn if len(cisbn) == 10 else to_isbn10(cisbn) return to_isbn13(cisbn) if len(cisbn) == 10 else cisbn return '' def ean13(isbnlike): """Transform an `isbnlike` string in an EAN number (canonical ISBN-13).""" ib = canonical(isbnlike) if len(ib) == 13: return ib if is_isbn13(ib) else '' if len(ib) == 10: return to_isbn13(ib) if is_isbn10(ib) else '' return '' # Alias EAN13 = ean13 GTIN13 = ean13 isbnlib-3.10.14/isbnlib/_cover.py000066400000000000000000000014321442216276400165630ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Get image links of the book's cover.""" import logging from .dev import cache from .dev.webquery import query as wquery LOGGER = logging.getLogger(__name__) UA = 'isbnlib (gzip)' SERVICE_URL = ( 'https://www.googleapis.com/books/v1/volumes?q=isbn:{isbn}' '&fields=items/volumeInfo(title,subtitle,authors,publisher,publishedDate,' 'language,industryIdentifiers,description,imageLinks)&maxResults=1') @cache def cover(isbn): """Get the urls for covers from Google Books.""" data = wquery(SERVICE_URL.format(isbn=isbn), user_agent=UA) urls = {} try: urls = data['items'][0]['volumeInfo']['imageLinks'] except (KeyError, IndexError): # pragma: no cover LOGGER.debug('No cover img data for %s', isbn) return urls isbnlib-3.10.14/isbnlib/_data/000077500000000000000000000000001442216276400160045ustar00rootroot00000000000000isbnlib-3.10.14/isbnlib/_data/__init__.py000066400000000000000000000000001442216276400201030ustar00rootroot00000000000000isbnlib-3.10.14/isbnlib/_data/data4info.py000066400000000000000000000221241442216276400202300ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8:noqa # pylint:skip-file # isort:skip_file # fmt:off # Produced by 'isbntools-dev'@'2023-04-24T10:17:23+00:00' # WARNING # THIS FILE WAS PRODUCED BY TOOLS THAT AUTOMATICALLY # GATHER THE RELEVANT INFORMATION FROM SEVERAL SOURCES # DON'T EDIT IT MANUALLY! countries={'978-0':'English language','978-1':'English language','978-2':'French language','978-3':'German language','978-4':'Japan','978-5':'former U.S.S.R','978-600':'Iran','978-601':'Kazakhstan','978-602':'Indonesia','978-603':'Saudi Arabia','978-604':'Vietnam','978-605':'Turkey','978-606':'Romania','978-607':'Mexico','978-608':'North Macedonia','978-609':'Lithuania','978-611':'Thailand','978-612':'Peru','978-613':'Mauritius','978-614':'Lebanon','978-615':'Hungary','978-616':'Thailand','978-617':'Ukraine','978-618':'Greece','978-619':'Bulgaria','978-620':'Mauritius','978-621':'Philippines','978-622':'Iran','978-623':'Indonesia','978-624':'Sri Lanka','978-625':'Turkey','978-626':'Taiwan','978-627':'Pakistan','978-628':'Colombia','978-629':'Malaysia','978-630':'Romania','978-631':'Argentina','978-65':'Brazil','978-7': "China, People's Republic", '978-80':'former Czechoslovakia','978-81':'India','978-82':'Norway','978-83':'Poland','978-84':'Spain','978-85':'Brazil','978-86':'former Yugoslavia','978-87':'Denmark','978-88':'Italy','978-89':'Korea, Republic','978-90':'Netherlands','978-91':'Sweden','978-92':'International NGO Publishers and EU Organizations','978-93':'India','978-94':'Netherlands','978-950':'Argentina','978-951':'Finland','978-952':'Finland','978-953':'Croatia','978-954':'Bulgaria','978-955':'Sri Lanka','978-956':'Chile','978-957':'Taiwan','978-958':'Colombia','978-959':'Cuba','978-960':'Greece','978-961':'Slovenia','978-962':'Hong Kong, China','978-963':'Hungary','978-964':'Iran','978-965':'Israel','978-966':'Ukraine','978-967':'Malaysia','978-968':'Mexico','978-969':'Pakistan','978-970':'Mexico','978-971':'Philippines','978-972':'Portugal','978-973':'Romania','978-974':'Thailand','978-975':'Turkey','978-976':'Caribbean Community','978-977':'Egypt','978-978':'Nigeria','978-979':'Indonesia','978-980':'Venezuela','978-981':'Singapore','978-982':'South Pacific','978-983':'Malaysia','978-984':'Bangladesh','978-985':'Belarus','978-986':'Taiwan','978-987':'Argentina','978-988':'Hong Kong, China','978-989':'Portugal','978-9911':'Montenegro','978-9912':'Tanzania','978-9913':'Uganda','978-9914':'Kenya','978-9915':'Uruguay','978-9916':'Estonia','978-9917':'Bolivia','978-9918':'Malta','978-9919':'Mongolia','978-9920':'Morocco','978-9921':'Kuwait','978-9922':'Iraq','978-9923':'Jordan','978-9924':'Cambodia','978-9925':'Cyprus','978-9926':'Bosnia and Herzegovina','978-9927':'Qatar','978-9928':'Albania','978-9929':'Guatemala','978-9930':'Costa Rica','978-9931':'Algeria','978-9932': "Lao People's Democratic Republic", '978-9933':'Syria','978-9934':'Latvia','978-9935':'Iceland','978-9936':'Afghanistan','978-9937':'Nepal','978-9938':'Tunisia','978-9939':'Armenia','978-9940':'Montenegro','978-9941':'Georgia','978-9942':'Ecuador','978-9943':'Uzbekistan','978-9944':'Turkey','978-9945':'Dominican Republic','978-9946':'Korea, P.D.R.','978-9947':'Algeria','978-9948':'United Arab Emirates','978-9949':'Estonia','978-9950':'Palestine','978-9951':'Kosova','978-9952':'Azerbaijan','978-9953':'Lebanon','978-9954':'Morocco','978-9955':'Lithuania','978-9956':'Cameroon','978-9957':'Jordan','978-9958':'Bosnia and Herzegovina','978-9959':'Libya','978-9960':'Saudi Arabia','978-9961':'Algeria','978-9962':'Panama','978-9963':'Cyprus','978-9964':'Ghana','978-9965':'Kazakhstan','978-9966':'Kenya','978-9967':'Kyrgyz Republic','978-9968':'Costa Rica','978-9969':'Algeria','978-9970':'Uganda','978-9971':'Singapore','978-9972':'Peru','978-9973':'Tunisia','978-9974':'Uruguay','978-9975':'Moldova','978-9976':'Tanzania','978-9977':'Costa Rica','978-9978':'Ecuador','978-9979':'Iceland','978-9980':'Papua New Guinea','978-9981':'Morocco','978-9982':'Zambia','978-9983':'Gambia','978-9984':'Latvia','978-9985':'Estonia','978-9986':'Lithuania','978-9987':'Tanzania','978-9988':'Ghana','978-9989':'North Macedonia','978-99901':'Bahrain','978-99902':'Reserved Agency','978-99903':'Mauritius','978-99904':'Curaçao','978-99905':'Bolivia','978-99906':'Kuwait','978-99908':'Malawi','978-99909':'Malta','978-99910':'Sierra Leone','978-99911':'Lesotho','978-99912':'Botswana','978-99913':'Andorra','978-99914':'International NGO Publishers','978-99915':'Maldives','978-99916':'Namibia','978-99917':'Brunei Darussalam','978-99918':'Faroe Islands','978-99919':'Benin','978-99920':'Andorra','978-99921':'Qatar','978-99922':'Guatemala','978-99923':'El Salvador','978-99924':'Nicaragua','978-99925':'Paraguay','978-99926':'Honduras','978-99927':'Albania','978-99928':'Georgia','978-99929':'Mongolia','978-99930':'Armenia','978-99931':'Seychelles','978-99932':'Malta','978-99933':'Nepal','978-99934':'Dominican Republic','978-99935':'Haiti','978-99936':'Bhutan','978-99937':'Macau','978-99938':'Srpska, Republic of','978-99939':'Guatemala','978-99940':'Georgia','978-99941':'Armenia','978-99942':'Sudan','978-99943':'Albania','978-99944':'Ethiopia','978-99945':'Namibia','978-99946':'Nepal','978-99947':'Tajikistan','978-99948':'Eritrea','978-99949':'Mauritius','978-99950':'Cambodia','978-99951':'Reserved Agency','978-99952':'Mali','978-99953':'Paraguay','978-99954':'Bolivia','978-99955':'Srpska, Republic of','978-99956':'Albania','978-99957':'Malta','978-99958':'Bahrain','978-99959':'Luxembourg','978-99960':'Malawi','978-99961':'El Salvador','978-99962':'Mongolia','978-99963':'Cambodia','978-99964':'Nicaragua','978-99965':'Macau','978-99966':'Kuwait','978-99967':'Paraguay','978-99968':'Botswana','978-99969':'Oman','978-99970':'Haiti','978-99971':'Myanmar','978-99972':'Faroe Islands','978-99973':'Mongolia','978-99974':'Bolivia','978-99975':'Tajikistan','978-99976':'Srpska, Republic of','978-99977':'Rwanda','978-99978':'Mongolia','978-99979':'Honduras','978-99980':'Bhutan','978-99981':'Macau','978-99982':'Benin','978-99983':'El Salvador','978-99984':'Brunei Darussalam','978-99985':'Tajikistan','978-99986':'Myanmar','978-99987':'Luxembourg','978-99988':'Sudan','978-99989':'Paraguay','978-99990':'Ethiopia','978-99992':'Oman','979-10':'France','979-11':'Korea, Republic','979-12':'Italy','979-8':'United States'} identifiers=(('978-0','978-1','978-2','978-3','978-4','978-5','978-7','979-8'),('978-65','978-80','978-81','978-82','978-83','978-84','978-85','978-86','978-87','978-88','978-89','978-90','978-91','978-92','978-93','978-94','979-10','979-11','979-12'),('978-600','978-601','978-602','978-603','978-604','978-605','978-606','978-607','978-608','978-609','978-611','978-612','978-613','978-614','978-615','978-616','978-617','978-618','978-619','978-620','978-621','978-622','978-623','978-624','978-625','978-626','978-627','978-628','978-629','978-630','978-631','978-950','978-951','978-952','978-953','978-954','978-955','978-956','978-957','978-958','978-959','978-960','978-961','978-962','978-963','978-964','978-965','978-966','978-967','978-968','978-969','978-970','978-971','978-972','978-973','978-974','978-975','978-976','978-977','978-978','978-979','978-980','978-981','978-982','978-983','978-984','978-985','978-986','978-987','978-988','978-989'),('978-9911','978-9912','978-9913','978-9914','978-9915','978-9916','978-9917','978-9918','978-9919','978-9920','978-9921','978-9922','978-9923','978-9924','978-9925','978-9926','978-9927','978-9928','978-9929','978-9930','978-9931','978-9932','978-9933','978-9934','978-9935','978-9936','978-9937','978-9938','978-9939','978-9940','978-9941','978-9942','978-9943','978-9944','978-9945','978-9946','978-9947','978-9948','978-9949','978-9950','978-9951','978-9952','978-9953','978-9954','978-9955','978-9956','978-9957','978-9958','978-9959','978-9960','978-9961','978-9962','978-9963','978-9964','978-9965','978-9966','978-9967','978-9968','978-9969','978-9970','978-9971','978-9972','978-9973','978-9974','978-9975','978-9976','978-9977','978-9978','978-9979','978-9980','978-9981','978-9982','978-9983','978-9984','978-9985','978-9986','978-9987','978-9988','978-9989'),('978-99901','978-99902','978-99903','978-99904','978-99905','978-99906','978-99908','978-99909','978-99910','978-99911','978-99912','978-99913','978-99914','978-99915','978-99916','978-99917','978-99918','978-99919','978-99920','978-99921','978-99922','978-99923','978-99924','978-99925','978-99926','978-99927','978-99928','978-99929','978-99930','978-99931','978-99932','978-99933','978-99934','978-99935','978-99936','978-99937','978-99938','978-99939','978-99940','978-99941','978-99942','978-99943','978-99944','978-99945','978-99946','978-99947','978-99948','978-99949','978-99950','978-99951','978-99952','978-99953','978-99954','978-99955','978-99956','978-99957','978-99958','978-99959','978-99960','978-99961','978-99962','978-99963','978-99964','978-99965','978-99966','978-99967','978-99968','978-99969','978-99970','978-99971','978-99972','978-99973','978-99974','978-99975','978-99976','978-99977','978-99978','978-99979','978-99980','978-99981','978-99982','978-99983','978-99984','978-99985','978-99986','978-99987','978-99988','978-99989','978-99990','978-99992')) RDDATE='20230424' isbnlib-3.10.14/isbnlib/_data/data4mask.py000066400000000000000000001067271442216276400202440ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8:noqa # pylint:skip-file # isort:skip_file # fmt:off # Produced by 'isbntools-dev'@'2023-04-24T10:17:23+00:00' # WARNING # THIS FILE WAS PRODUCED BY TOOLS THAT AUTOMATICALLY # GATHER THE RELEVANT INFORMATION FROM SEVERAL SOURCES # DON'T EDIT IT MANUALLY! ranges={'978-0': ((0, 1999999, 2),(2000000, 2279999, 3),(2280000, 2289999, 4),(2290000, 3689999, 3),(3690000, 3699999, 4),(3700000, 6389999, 3),(6390000, 6397999, 4),(6398000, 6399999, 7),(6400000, 6449999, 3),(6450000, 6459999, 7),(6460000, 6479999, 3),(6480000, 6489999, 7),(6490000, 6549999, 3),(6550000, 6559999, 4),(6560000, 6999999, 3),(7000000, 8499999, 4),(8500000, 8999999, 5),(9000000, 9499999, 6),(9500000, 9999999, 7)), '978-1': ((0, 99999, 3),(100000, 299999, 2),(300000, 349999, 3),(350000, 399999, 4),(400000, 699999, 2),(700000, 999999, 4),(1000000, 3979999, 3),(3980000, 5499999, 4),(5500000, 6499999, 5),(6500000, 6799999, 4),(6800000, 6859999, 5),(6860000, 7139999, 4),(7140000, 7169999, 3),(7170000, 7319999, 4),(7320000, 7399999, 7),(7400000, 7749999, 5),(7750000, 7753999, 7),(7754000, 7763999, 5),(7764000, 7764999, 7),(7765000, 7769999, 5),(7770000, 7782999, 7),(7783000, 7899999, 5),(7900000, 7999999, 4),(8000000, 8004999, 5),(8005000, 8049999, 5),(8050000, 8379999, 5),(8380000, 8384999, 7),(8385000, 8671999, 5),(8672000, 8675999, 4),(8676000, 8697999, 5),(8698000, 9159999, 6),(9160000, 9165059, 7),(9165060, 9168699, 6),(9168700, 9169079, 7),(9169080, 9195999, 6),(9196000, 9196549, 7),(9196550, 9729999, 6),(9730000, 9877999, 4),(9878000, 9911499, 6),(9911500, 9911999, 7),(9912000, 9989899, 6),(9989900, 9999999, 7)), '978-2': ((0, 1999999, 2),(2000000, 3499999, 3),(3500000, 3999999, 5),(4000000, 4899999, 3),(4900000, 4949999, 6),(4950000, 4959999, 3),(4960000, 4966999, 4),(4967000, 4969999, 5),(4970000, 6999999, 3),(7000000, 8399999, 4),(8400000, 8999999, 5),(9000000, 9197999, 6),(9198000, 9198099, 5),(9198100, 9199429, 6),(9199430, 9199689, 7),(9199690, 9499999, 6),(9500000, 9999999, 7)), '978-3': ((0, 299999, 2),(300000, 339999, 3),(340000, 369999, 4),(370000, 399999, 5),(400000, 1999999, 2),(2000000, 6999999, 3),(7000000, 8499999, 4),(8500000, 8999999, 5),(9000000, 9499999, 6),(9500000, 9539999, 7),(9540000, 9699999, 5),(9700000, 9849999, 7),(9850000, 9999999, 5)), '978-4': ((0, 1999999, 2),(2000000, 6999999, 3),(7000000, 8499999, 4),(8500000, 8999999, 5),(9000000, 9499999, 6),(9500000, 9999999, 7)), '978-5': ((0, 49999, 5),(50000, 99999, 4),(100000, 1999999, 2),(2000000, 3619999, 3),(3620000, 3623999, 4),(3624000, 3629999, 5),(3630000, 4209999, 3),(4210000, 4299999, 4),(4300000, 4309999, 3),(4310000, 4399999, 4),(4400000, 4409999, 3),(4410000, 4499999, 4),(4500000, 6039999, 3),(6040000, 6049999, 7),(6050000, 6999999, 3),(7000000, 8499999, 4),(8500000, 8999999, 5),(9000000, 9099999, 6),(9100000, 9199999, 5),(9200000, 9299999, 4),(9300000, 9499999, 5),(9500000, 9500999, 7),(9501000, 9799999, 4),(9800000, 9899999, 5),(9900000, 9909999, 7),(9910000, 9999999, 4)), '978-600': ((0, 999999, 2),(1000000, 4999999, 3),(5000000, 8999999, 4),(9000000, 9867999, 5),(9868000, 9929999, 4),(9930000, 9959999, 3),(9960000, 9999999, 5)), '978-601': ((0, 1999999, 2),(2000000, 6999999, 3),(7000000, 7999999, 4),(8000000, 8499999, 5),(8500000, 9999999, 2)), '978-602': ((0, 699999, 2),(700000, 1399999, 4),(1400000, 1499999, 5),(1500000, 1699999, 4),(1700000, 1999999, 5),(2000000, 4999999, 3),(5000000, 5399999, 5),(5400000, 5999999, 4),(6000000, 6199999, 5),(6200000, 6999999, 4),(7000000, 7499999, 5),(7500000, 9499999, 4),(9500000, 9999999, 5)), '978-603': ((0, 499999, 2),(500000, 4999999, 2),(5000000, 7999999, 3),(8000000, 8999999, 4),(9000000, 9999999, 5)), '978-604': ((0, 2999999, 1),(3000000, 3999999, 3),(4000000, 4699999, 2),(4700000, 4979999, 3),(4980000, 4999999, 4),(5000000, 8999999, 2),(9000000, 9799999, 3),(9800000, 9999999, 4)), '978-605': ((0, 299999, 2),(300000, 399999, 3),(400000, 599999, 2),(600000, 699999, 5),(700000, 999999, 2),(1000000, 1999999, 3),(2000000, 2399999, 4),(2400000, 3999999, 3),(4000000, 5999999, 4),(6000000, 7499999, 5),(7500000, 7999999, 4),(8000000, 8999999, 5),(9000000, 9999999, 4)), '978-606': ((0, 999999, 3),(1000000, 4999999, 2),(5000000, 7999999, 3),(8000000, 9099999, 4),(9100000, 9199999, 3),(9200000, 9599999, 5),(9600000, 9749999, 4),(9750000, 9999999, 3)), '978-607': ((0, 3999999, 2),(4000000, 5929999, 3),(5930000, 5999999, 5),(6000000, 7499999, 3),(7500000, 9499999, 4),(9500000, 9999999, 5)), '978-608': ((0, 999999, 1),(1000000, 1999999, 2),(2000000, 4499999, 3),(4500000, 6499999, 4),(6500000, 6999999, 5),(7000000, 9999999, 1)), '978-609': ((0, 3999999, 2),(4000000, 7999999, 3),(8000000, 9499999, 4),(9500000, 9999999, 5)), '978-611': ((0, 9999999, 0),), '978-612': ((0, 2999999, 2),(3000000, 3999999, 3),(4000000, 4499999, 4),(4500000, 4999999, 5),(5000000, 5149999, 4),(5150000, 9999999, 0)), '978-613': ((0, 9999999, 1),), '978-614': ((0, 3999999, 2),(4000000, 7999999, 3),(8000000, 9499999, 4),(9500000, 9999999, 5)), '978-615': ((0, 999999, 2),(1000000, 4999999, 3),(5000000, 7999999, 4),(8000000, 8999999, 5),(9000000, 9999999, 0)), '978-616': ((0, 1999999, 2),(2000000, 6999999, 3),(7000000, 8999999, 4),(9000000, 9999999, 5)), '978-617': ((0, 4999999, 2),(5000000, 6999999, 3),(7000000, 8999999, 4),(9000000, 9999999, 5)), '978-618': ((0, 1999999, 2),(2000000, 4999999, 3),(5000000, 7999999, 4),(8000000, 9999999, 5)), '978-619': ((0, 1499999, 2),(1500000, 6999999, 3),(7000000, 8999999, 4),(9000000, 9999999, 5)), '978-620': ((0, 9999999, 1),), '978-621': ((0, 2999999, 2),(3000000, 3999999, 0),(4000000, 5999999, 3),(6000000, 7999999, 0),(8000000, 8999999, 4),(9000000, 9499999, 0),(9500000, 9999999, 5)), '978-622': ((0, 1099999, 2),(1100000, 1999999, 0),(2000000, 4249999, 3),(4250000, 5199999, 0),(5200000, 8499999, 4),(8500000, 8999999, 0),(9000000, 9999999, 5)), '978-623': ((0, 999999, 2),(1000000, 1299999, 0),(1300000, 4999999, 3),(5000000, 5249999, 0),(5250000, 8799999, 4),(8800000, 9999999, 5)), '978-624': ((0, 499999, 2),(500000, 1999999, 0),(2000000, 2499999, 3),(2500000, 4999999, 0),(5000000, 6449999, 4),(6450000, 9449999, 0),(9450000, 9999999, 5)), '978-625': ((0, 99999, 2),(100000, 3649999, 0),(3650000, 4429999, 3),(4430000, 4449999, 5),(4450000, 4499999, 3),(4500000, 6349999, 0),(6350000, 7793999, 4),(7794000, 7794999, 5),(7795000, 8499999, 4),(8500000, 9899999, 0),(9900000, 9999999, 5)), '978-626': ((0, 499999, 2),(500000, 2999999, 0),(3000000, 4999999, 3),(5000000, 6999999, 0),(7000000, 7999999, 4),(8000000, 9499999, 0),(9500000, 9999999, 5)), '978-627': ((0, 2999999, 0),(3000000, 3199999, 2),(3200000, 4999999, 0),(5000000, 5249999, 3),(5250000, 7499999, 0),(7500000, 7999999, 4),(8000000, 9999999, 0)), '978-628': ((0, 999999, 2),(1000000, 4999999, 0),(5000000, 5499999, 3),(5500000, 7499999, 0),(7500000, 8499999, 4),(8500000, 9499999, 0),(9500000, 9999999, 5)), '978-629': ((0, 299999, 2),(300000, 4699999, 0),(4700000, 4999999, 3),(5000000, 7499999, 0),(7500000, 7999999, 4),(8000000, 9649999, 0),(9650000, 9999999, 5)), '978-630': ((0, 2999999, 0),(3000000, 3499999, 3),(3500000, 6499999, 0),(6500000, 6849999, 4),(6850000, 9999999, 0)), '978-631': ((0, 999999, 2),(1000000, 2999999, 0),(3000000, 3999999, 3),(4000000, 6499999, 0),(6500000, 7499999, 4),(7500000, 8999999, 0),(9000000, 9999999, 5)), '978-65': ((0, 199999, 2),(200000, 2499999, 0),(2500000, 2999999, 3),(3000000, 3029999, 3),(3030000, 4999999, 0),(5000000, 5129999, 4),(5130000, 5349999, 0),(5350000, 6149999, 4),(6150000, 7999999, 0),(8000000, 8182499, 5),(8182500, 8449999, 0),(8450000, 8999999, 5),(9000000, 9024499, 6),(9024500, 9799999, 0),(9800000, 9999999, 6)), '978-7': ((0, 999999, 2),(1000000, 4999999, 3),(5000000, 7999999, 4),(8000000, 8999999, 5),(9000000, 9999999, 6)), '978-80': ((0, 1999999, 2),(2000000, 5299999, 3),(5300000, 5499999, 5),(5500000, 6899999, 3),(6900000, 6999999, 5),(7000000, 8499999, 4),(8500000, 8999999, 5),(9000000, 9989999, 6),(9990000, 9999999, 5)), '978-81': ((0, 1899999, 2),(1900000, 1999999, 5),(2000000, 6999999, 3),(7000000, 8499999, 4),(8500000, 8999999, 5),(9000000, 9999999, 6)), '978-82': ((0, 1999999, 2),(2000000, 6899999, 3),(6900000, 6999999, 6),(7000000, 8999999, 4),(9000000, 9899999, 5),(9900000, 9999999, 6)), '978-83': ((0, 1999999, 2),(2000000, 5999999, 3),(6000000, 6999999, 5),(7000000, 8499999, 4),(8500000, 8999999, 5),(9000000, 9999999, 6)), '978-84': ((0, 999999, 2),(1000000, 1049999, 5),(1050000, 1199999, 4),(1200000, 1299999, 6),(1300000, 1399999, 4),(1400000, 1499999, 3),(1500000, 1999999, 5),(2000000, 6999999, 3),(7000000, 8499999, 4),(8500000, 8999999, 5),(9000000, 9199999, 4),(9200000, 9239999, 6),(9240000, 9299999, 5),(9300000, 9499999, 6),(9500000, 9699999, 5),(9700000, 9999999, 4)), '978-85': ((0, 1999999, 2),(2000000, 4549999, 3),(4550000, 4552999, 6),(4553000, 4559999, 5),(4560000, 5289999, 3),(5290000, 5319999, 5),(5320000, 5339999, 4),(5340000, 5399999, 3),(5400000, 5402999, 5),(5403000, 5403999, 5),(5404000, 5404999, 6),(5405000, 5408999, 5),(5409000, 5409999, 6),(5410000, 5439999, 5),(5440000, 5479999, 4),(5480000, 5499999, 5),(5500000, 5999999, 4),(6000000, 6999999, 5),(7000000, 8499999, 4),(8500000, 8999999, 5),(9000000, 9249999, 6),(9250000, 9449999, 5),(9450000, 9599999, 4),(9600000, 9799999, 2),(9800000, 9999999, 5)), '978-86': ((0, 2999999, 2),(3000000, 5999999, 3),(6000000, 7999999, 4),(8000000, 8999999, 5),(9000000, 9999999, 6)), '978-87': ((0, 2999999, 2),(3000000, 3999999, 0),(4000000, 6499999, 3),(6500000, 6999999, 0),(7000000, 7999999, 4),(8000000, 8499999, 0),(8500000, 9499999, 5),(9500000, 9699999, 0),(9700000, 9999999, 6)), '978-88': ((0, 1999999, 2),(2000000, 3119999, 3),(3120000, 3149999, 5),(3150000, 3189999, 3),(3190000, 3229999, 5),(3230000, 3269999, 3),(3270000, 3389999, 4),(3390000, 3609999, 3),(3610000, 3629999, 4),(3630000, 5489999, 3),(5490000, 5549999, 4),(5550000, 5999999, 3),(6000000, 8499999, 4),(8500000, 8999999, 5),(9000000, 9099999, 6),(9100000, 9269999, 3),(9270000, 9399999, 4),(9400000, 9479999, 6),(9480000, 9999999, 5)), '978-89': ((0, 2499999, 2),(2500000, 5499999, 3),(5500000, 8499999, 4),(8500000, 9499999, 5),(9500000, 9699999, 6),(9700000, 9899999, 5),(9900000, 9999999, 3)), '978-90': ((0, 1999999, 2),(2000000, 4999999, 3),(5000000, 6999999, 4),(7000000, 7999999, 5),(8000000, 8499999, 6),(8500000, 8999999, 4),(9000000, 9099999, 2),(9100000, 9399999, 0),(9400000, 9499999, 2),(9500000, 9999999, 0)), '978-91': ((0, 1999999, 1),(2000000, 4999999, 2),(5000000, 6499999, 3),(6500000, 6999999, 0),(7000000, 8199999, 4),(8200000, 8499999, 0),(8500000, 9499999, 5),(9500000, 9699999, 0),(9700000, 9999999, 6)), '978-92': ((0, 5999999, 1),(6000000, 7999999, 2),(8000000, 8999999, 3),(9000000, 9499999, 4),(9500000, 9899999, 5),(9900000, 9999999, 6)), '978-93': ((0, 999999, 2),(1000000, 4999999, 3),(5000000, 7999999, 4),(8000000, 9599999, 5),(9600000, 9999999, 6)), '978-94': ((0, 5999999, 3),(6000000, 8999999, 4),(9000000, 9999999, 5)), '978-950': ((0, 4999999, 2),(5000000, 8999999, 3),(9000000, 9899999, 4),(9900000, 9999999, 5)), '978-951': ((0, 1999999, 1),(2000000, 5499999, 2),(5500000, 8899999, 3),(8900000, 9499999, 4),(9500000, 9999999, 5)), '978-952': ((0, 1999999, 2),(2000000, 4999999, 3),(5000000, 5999999, 4),(6000000, 6499999, 2),(6500000, 6599999, 5),(6600000, 6699999, 4),(6700000, 6999999, 5),(7000000, 7999999, 4),(8000000, 9499999, 2),(9500000, 9899999, 4),(9900000, 9999999, 5)), '978-953': ((0, 999999, 1),(1000000, 1499999, 2),(1500000, 4799999, 3),(4800000, 4999999, 5),(5000000, 5009999, 3),(5010000, 5099999, 5),(5100000, 5499999, 2),(5500000, 5999999, 5),(6000000, 9499999, 4),(9500000, 9999999, 5)), '978-954': ((0, 2899999, 2),(2900000, 2999999, 4),(3000000, 7999999, 3),(8000000, 8999999, 4),(9000000, 9299999, 5),(9300000, 9999999, 4)), '978-955': ((0, 1999999, 4),(2000000, 3399999, 2),(3400000, 3549999, 4),(3550000, 3599999, 5),(3600000, 3799999, 4),(3800000, 3899999, 5),(3900000, 4099999, 4),(4100000, 4499999, 5),(4500000, 4999999, 4),(5000000, 5499999, 5),(5500000, 7109999, 3),(7110000, 7149999, 5),(7150000, 9499999, 4),(9500000, 9999999, 5)), '978-956': ((0, 899999, 2),(900000, 999999, 5),(1000000, 1999999, 2),(2000000, 5999999, 3),(6000000, 6999999, 4),(7000000, 9999999, 4)), '978-957': ((0, 299999, 2),(300000, 499999, 4),(500000, 1999999, 2),(2000000, 2099999, 4),(2100000, 2799999, 2),(2800000, 3099999, 5),(3100000, 4399999, 2),(4400000, 8199999, 3),(8200000, 9699999, 4),(9700000, 9999999, 5)), '978-958': ((0, 4999999, 2),(5000000, 5099999, 3),(5100000, 5199999, 4),(5200000, 5399999, 5),(5400000, 5599999, 4),(5600000, 5999999, 5),(6000000, 7999999, 3),(8000000, 9499999, 4),(9500000, 9999999, 5)), '978-959': ((0, 1999999, 2),(2000000, 6999999, 3),(7000000, 8499999, 4),(8500000, 9999999, 5)), '978-960': ((0, 1999999, 2),(2000000, 6599999, 3),(6600000, 6899999, 4),(6900000, 6999999, 3),(7000000, 8499999, 4),(8500000, 9299999, 5),(9300000, 9399999, 2),(9400000, 9799999, 4),(9800000, 9999999, 5)), '978-961': ((0, 1999999, 2),(2000000, 5999999, 3),(6000000, 8999999, 4),(9000000, 9799999, 5),(9800000, 9999999, 0)), '978-962': ((0, 1999999, 2),(2000000, 6999999, 3),(7000000, 8499999, 4),(8500000, 8699999, 5),(8700000, 8999999, 4),(9000000, 9999999, 3)), '978-963': ((0, 1999999, 2),(2000000, 6999999, 3),(7000000, 8499999, 4),(8500000, 8999999, 5),(9000000, 9999999, 4)), '978-964': ((0, 1499999, 2),(1500000, 2499999, 3),(2500000, 2999999, 4),(3000000, 5499999, 3),(5500000, 8999999, 4),(9000000, 9699999, 5),(9700000, 9899999, 3),(9900000, 9999999, 4)), '978-965': ((0, 1999999, 2),(2000000, 5999999, 3),(6000000, 6999999, 0),(7000000, 7999999, 4),(8000000, 8999999, 0),(9000000, 9999999, 5)), '978-966': ((0, 1299999, 2),(1300000, 1399999, 3),(1400000, 1499999, 2),(1500000, 1699999, 4),(1700000, 1999999, 3),(2000000, 2789999, 4),(2790000, 2899999, 3),(2900000, 2999999, 4),(3000000, 6999999, 3),(7000000, 8999999, 4),(9000000, 9099999, 5),(9100000, 9499999, 3),(9500000, 9799999, 5),(9800000, 9999999, 3)), '978-967': ((0, 999999, 4),(1000000, 1999999, 5),(2000000, 2499999, 4),(2500000, 2549999, 3),(2550000, 2699999, 5),(2700000, 2799999, 4),(2800000, 2999999, 4),(3000000, 4999999, 3),(5000000, 5999999, 4),(6000000, 8999999, 2),(9000000, 9899999, 3),(9900000, 9989999, 4),(9990000, 9999999, 5)), '978-968': ((100000, 3999999, 2),(4000000, 4999999, 3),(5000000, 7999999, 4),(8000000, 8999999, 3),(9000000, 9999999, 4)), '978-969': ((0, 1999999, 1),(2000000, 2099999, 2),(2100000, 2199999, 3),(2200000, 2299999, 4),(2300000, 2399999, 5),(2400000, 3999999, 2),(4000000, 7499999, 3),(7500000, 9999999, 4)), '978-970': ((100000, 5999999, 2),(6000000, 8999999, 3),(9000000, 9099999, 4),(9100000, 9699999, 5),(9700000, 9999999, 4)), '978-971': ((0, 159999, 3),(160000, 199999, 4),(200000, 299999, 2),(300000, 599999, 4),(600000, 4999999, 2),(5000000, 8499999, 3),(8500000, 9099999, 4),(9100000, 9599999, 5),(9600000, 9699999, 4),(9700000, 9899999, 2),(9900000, 9999999, 4)), '978-972': ((0, 1999999, 1),(2000000, 5499999, 2),(5500000, 7999999, 3),(8000000, 9499999, 4),(9500000, 9999999, 5)), '978-973': ((0, 999999, 1),(1000000, 1699999, 3),(1700000, 1999999, 4),(2000000, 5499999, 2),(5500000, 7599999, 3),(7600000, 8499999, 4),(8500000, 8899999, 5),(8900000, 9499999, 4),(9500000, 9999999, 5)), '978-974': ((0, 1999999, 2),(2000000, 6999999, 3),(7000000, 8499999, 4),(8500000, 8999999, 5),(9000000, 9499999, 5),(9500000, 9999999, 4)), '978-975': ((0, 199999, 5),(200000, 2399999, 2),(2400000, 2499999, 4),(2500000, 5999999, 3),(6000000, 9199999, 4),(9200000, 9899999, 5),(9900000, 9999999, 3)), '978-976': ((0, 3999999, 1),(4000000, 5999999, 2),(6000000, 7999999, 3),(8000000, 9499999, 4),(9500000, 9999999, 5)), '978-977': ((0, 1999999, 2),(2000000, 4999999, 3),(5000000, 6999999, 4),(7000000, 8499999, 3),(8500000, 8929999, 5),(8930000, 8949999, 3),(8950000, 8999999, 4),(9000000, 9899999, 2),(9900000, 9999999, 3)), '978-978': ((0, 1999999, 3),(2000000, 2999999, 4),(3000000, 7799999, 5),(7800000, 7999999, 3),(8000000, 8999999, 4),(9000000, 9999999, 3)), '978-979': ((0, 999999, 3),(1000000, 1499999, 4),(1500000, 1999999, 5),(2000000, 2999999, 2),(3000000, 3999999, 4),(4000000, 7999999, 3),(8000000, 9499999, 4),(9500000, 9999999, 5)), '978-980': ((0, 1999999, 2),(2000000, 5999999, 3),(6000000, 9999999, 4)), '978-981': ((0, 1699999, 2),(1700000, 1799999, 5),(1800000, 1999999, 2),(2000000, 2999999, 3),(3000000, 3099999, 4),(3100000, 3999999, 3),(4000000, 9499999, 4),(9500000, 9899999, 0),(9900000, 9999999, 2)), '978-982': ((0, 999999, 2),(1000000, 6999999, 3),(7000000, 8999999, 2),(9000000, 9799999, 4),(9800000, 9999999, 5)), '978-983': ((0, 199999, 2),(200000, 1999999, 3),(2000000, 3999999, 4),(4000000, 4499999, 5),(4500000, 4999999, 2),(5000000, 7999999, 2),(8000000, 8999999, 3),(9000000, 9899999, 4),(9900000, 9999999, 5)), '978-984': ((0, 3999999, 2),(4000000, 7999999, 3),(8000000, 8999999, 4),(9000000, 9999999, 5)), '978-985': ((0, 3999999, 2),(4000000, 5999999, 3),(6000000, 8799999, 4),(8800000, 8999999, 3),(9000000, 9999999, 5)), '978-986': ((0, 599999, 2),(600000, 699999, 5),(700000, 799999, 4),(800000, 1199999, 2),(1200000, 5399999, 3),(5400000, 7999999, 4),(8000000, 9999999, 5)), '978-987': ((0, 999999, 2),(1000000, 1999999, 4),(2000000, 2999999, 5),(3000000, 3599999, 2),(3600000, 4199999, 4),(4200000, 4399999, 2),(4400000, 4499999, 4),(4500000, 4899999, 5),(4900000, 4999999, 4),(5000000, 8249999, 3),(8250000, 8279999, 4),(8280000, 8299999, 5),(8300000, 8499999, 4),(8500000, 8899999, 2),(8900000, 9499999, 4),(9500000, 9999999, 5)), '978-988': ((0, 1199999, 2),(1200000, 1999999, 5),(2000000, 6999999, 3),(7000000, 7999999, 5),(8000000, 9699999, 4),(9700000, 9999999, 5)), '978-989': ((0, 1999999, 1),(2000000, 3499999, 2),(3500000, 3699999, 5),(3700000, 5299999, 2),(5300000, 5499999, 5),(5500000, 7999999, 3),(8000000, 9499999, 4),(9500000, 9999999, 5)), '978-9911': ((0, 1999999, 0),(2000000, 2499999, 2),(2500000, 5499999, 0),(5500000, 7499999, 3),(7500000, 9999999, 0)), '978-9912': ((0, 3999999, 0),(4000000, 4499999, 2),(4500000, 7499999, 0),(7500000, 7999999, 3),(8000000, 9799999, 0),(9800000, 9999999, 4)), '978-9913': ((0, 799999, 2),(800000, 5999999, 0),(6000000, 6999999, 3),(7000000, 9549999, 0),(9550000, 9999999, 4)), '978-9914': ((0, 3999999, 0),(4000000, 5299999, 2),(5300000, 6999999, 0),(7000000, 7749999, 3),(7750000, 9599999, 0),(9600000, 9999999, 4)), '978-9915': ((0, 3999999, 0),(4000000, 5999999, 2),(6000000, 6499999, 0),(6500000, 7999999, 3),(8000000, 9299999, 0),(9300000, 9999999, 4)), '978-9916': ((0, 999999, 1),(1000000, 3999999, 2),(4000000, 5999999, 1),(6000000, 7999999, 3),(8000000, 9499999, 0),(9500000, 9999999, 4)), '978-9917': ((0, 999999, 1),(1000000, 2999999, 0),(3000000, 3499999, 2),(3500000, 5999999, 0),(6000000, 6999999, 3),(7000000, 9799999, 0),(9800000, 9999999, 4)), '978-9918': ((0, 999999, 1),(1000000, 1999999, 0),(2000000, 2999999, 2),(3000000, 5999999, 0),(6000000, 7999999, 3),(8000000, 9499999, 0),(9500000, 9999999, 4)), '978-9919': ((0, 999999, 1),(1000000, 1999999, 0),(2000000, 2999999, 2),(3000000, 4999999, 0),(5000000, 5999999, 3),(6000000, 8999999, 0),(9000000, 9999999, 4)), '978-9920': ((0, 2999999, 0),(3000000, 4199999, 2),(4200000, 4999999, 0),(5000000, 7999999, 3),(8000000, 8749999, 0),(8750000, 9999999, 4)), '978-9921': ((0, 999999, 1),(1000000, 2999999, 0),(3000000, 3999999, 2),(4000000, 6999999, 0),(7000000, 8999999, 3),(9000000, 9699999, 0),(9700000, 9999999, 4)), '978-9922': ((0, 1999999, 0),(2000000, 2999999, 2),(3000000, 5999999, 0),(6000000, 7999999, 3),(8000000, 8499999, 0),(8500000, 9999999, 4)), '978-9923': ((0, 999999, 1),(1000000, 5999999, 2),(6000000, 6999999, 0),(7000000, 8999999, 3),(9000000, 9399999, 0),(9400000, 9999999, 4)), '978-9924': ((0, 2999999, 0),(3000000, 3999999, 2),(4000000, 4999999, 0),(5000000, 6499999, 3),(6500000, 8999999, 0),(9000000, 9999999, 4)), '978-9925': ((0, 2999999, 1),(3000000, 5499999, 2),(5500000, 7349999, 3),(7350000, 9999999, 4)), '978-9926': ((0, 1999999, 1),(2000000, 3999999, 2),(4000000, 7999999, 3),(8000000, 9999999, 4)), '978-9927': ((0, 999999, 2),(1000000, 3999999, 3),(4000000, 4999999, 4),(5000000, 9999999, 0)), '978-9928': ((0, 999999, 2),(1000000, 3999999, 3),(4000000, 4999999, 4),(5000000, 7999999, 0),(8000000, 8999999, 3),(9000000, 9999999, 2)), '978-9929': ((0, 3999999, 1),(4000000, 5499999, 2),(5500000, 7999999, 3),(8000000, 9999999, 4)), '978-9930': ((0, 4999999, 2),(5000000, 9399999, 3),(9400000, 9999999, 4)), '978-9931': ((0, 2399999, 2),(2400000, 8999999, 3),(9000000, 9999999, 4)), '978-9932': ((0, 3999999, 2),(4000000, 8499999, 3),(8500000, 9999999, 4)), '978-9933': ((0, 999999, 1),(1000000, 3999999, 2),(4000000, 8999999, 3),(9000000, 9999999, 4)), '978-9934': ((0, 999999, 1),(1000000, 4999999, 2),(5000000, 7999999, 3),(8000000, 9999999, 4)), '978-9935': ((0, 999999, 1),(1000000, 3999999, 2),(4000000, 8999999, 3),(9000000, 9999999, 4)), '978-9936': ((0, 1999999, 1),(2000000, 3999999, 2),(4000000, 7999999, 3),(8000000, 9999999, 4)), '978-9937': ((0, 2999999, 1),(3000000, 4999999, 2),(5000000, 7999999, 3),(8000000, 9999999, 4)), '978-9938': ((0, 7999999, 2),(8000000, 9499999, 3),(9500000, 9749999, 4),(9750000, 9909999, 3),(9910000, 9999999, 4)), '978-9939': ((0, 4999999, 1),(5000000, 7999999, 2),(8000000, 8999999, 3),(9000000, 9599999, 4),(9600000, 9799999, 3),(9800000, 9999999, 2)), '978-9940': ((0, 1999999, 1),(2000000, 4999999, 2),(5000000, 8399999, 3),(8400000, 8699999, 2),(8700000, 9999999, 4)), '978-9941': ((0, 999999, 1),(1000000, 3999999, 2),(4000000, 7999999, 3),(8000000, 8999999, 1),(9000000, 9999999, 4)), '978-9942': ((0, 5999999, 2),(6000000, 6999999, 3),(7000000, 7499999, 4),(7500000, 8499999, 3),(8500000, 8999999, 4),(9000000, 9849999, 3),(9850000, 9999999, 4)), '978-9943': ((0, 2999999, 2),(3000000, 3999999, 3),(4000000, 9749999, 4),(9750000, 9999999, 3)), '978-9944': ((0, 999999, 4),(1000000, 4999999, 3),(5000000, 5999999, 4),(6000000, 6999999, 2),(7000000, 7999999, 3),(8000000, 8999999, 2),(9000000, 9999999, 3)), '978-9945': ((0, 99999, 2),(100000, 799999, 3),(800000, 3999999, 2),(4000000, 5699999, 3),(5700000, 5799999, 2),(5800000, 7999999, 3),(8000000, 8099999, 2),(8100000, 8499999, 3),(8500000, 9999999, 4)), '978-9946': ((0, 1999999, 1),(2000000, 3999999, 2),(4000000, 8999999, 3),(9000000, 9999999, 4)), '978-9947': ((0, 1999999, 1),(2000000, 7999999, 2),(8000000, 9999999, 3)), '978-9948': ((0, 3999999, 2),(4000000, 8499999, 3),(8500000, 9999999, 4)), '978-9949': ((0, 899999, 2),(900000, 999999, 3),(1000000, 3999999, 2),(4000000, 6999999, 3),(7000000, 7199999, 2),(7200000, 7499999, 4),(7500000, 8999999, 2),(9000000, 9999999, 4)), '978-9950': ((0, 2999999, 2),(3000000, 8499999, 3),(8500000, 9999999, 4)), '978-9951': ((0, 3899999, 2),(3900000, 8499999, 3),(8500000, 9799999, 4),(9800000, 9999999, 3)), '978-9952': ((0, 1999999, 1),(2000000, 3999999, 2),(4000000, 7999999, 3),(8000000, 9999999, 4)), '978-9953': ((0, 999999, 1),(1000000, 3999999, 2),(4000000, 5999999, 3),(6000000, 8999999, 2),(9000000, 9299999, 4),(9300000, 9699999, 2),(9700000, 9999999, 3)), '978-9954': ((0, 1999999, 1),(2000000, 3999999, 2),(4000000, 7999999, 3),(8000000, 9899999, 4),(9900000, 9999999, 2)), '978-9955': ((0, 3999999, 2),(4000000, 9299999, 3),(9300000, 9999999, 4)), '978-9956': ((0, 999999, 1),(1000000, 3999999, 2),(4000000, 8999999, 3),(9000000, 9999999, 4)), '978-9957': ((0, 3999999, 2),(4000000, 6499999, 3),(6500000, 6799999, 2),(6800000, 6999999, 3),(7000000, 8499999, 2),(8500000, 8799999, 4),(8800000, 9999999, 2)), '978-9958': ((0, 199999, 2),(200000, 299999, 3),(300000, 399999, 4),(400000, 899999, 3),(900000, 999999, 4),(1000000, 1899999, 2),(1900000, 1999999, 4),(2000000, 4999999, 2),(5000000, 8999999, 3),(9000000, 9999999, 4)), '978-9959': ((0, 1999999, 1),(2000000, 7999999, 2),(8000000, 9499999, 3),(9500000, 9699999, 4),(9700000, 9799999, 3),(9800000, 9999999, 2)), '978-9960': ((0, 5999999, 2),(6000000, 8999999, 3),(9000000, 9999999, 4)), '978-9961': ((0, 2999999, 1),(3000000, 6999999, 2),(7000000, 9499999, 3),(9500000, 9999999, 4)), '978-9962': ((0, 5499999, 2),(5500000, 5599999, 4),(5600000, 5999999, 2),(6000000, 8499999, 3),(8500000, 9999999, 4)), '978-9963': ((0, 1999999, 1),(2000000, 2499999, 4),(2500000, 2799999, 3),(2800000, 2999999, 4),(3000000, 5499999, 2),(5500000, 7349999, 3),(7350000, 7499999, 4),(7500000, 9999999, 4)), '978-9964': ((0, 6999999, 1),(7000000, 9499999, 2),(9500000, 9999999, 3)), '978-9965': ((0, 3999999, 2),(4000000, 8999999, 3),(9000000, 9999999, 4)), '978-9966': ((0, 1399999, 3),(1400000, 1499999, 2),(1500000, 1999999, 4),(2000000, 6999999, 2),(7000000, 7499999, 4),(7500000, 8209999, 3),(8210000, 8249999, 4),(8250000, 8259999, 3),(8260000, 8289999, 4),(8290000, 9599999, 3),(9600000, 9999999, 4)), '978-9967': ((0, 3999999, 2),(4000000, 8999999, 3),(9000000, 9999999, 4)), '978-9968': ((0, 4999999, 2),(5000000, 9399999, 3),(9400000, 9999999, 4)), '978-9969': ((0, 699999, 2),(700000, 4999999, 0),(5000000, 6499999, 3),(6500000, 9699999, 0),(9700000, 9999999, 4)), '978-9970': ((0, 3999999, 2),(4000000, 8999999, 3),(9000000, 9999999, 4)), '978-9971': ((0, 5999999, 1),(6000000, 8999999, 2),(9000000, 9899999, 3),(9900000, 9999999, 4)), '978-9972': ((0, 999999, 2),(1000000, 1999999, 1),(2000000, 2499999, 3),(2500000, 2999999, 4),(3000000, 5999999, 2),(6000000, 8999999, 3),(9000000, 9999999, 4)), '978-9973': ((0, 599999, 2),(600000, 899999, 3),(900000, 999999, 4),(1000000, 6999999, 2),(7000000, 9699999, 3),(9700000, 9999999, 4)), '978-9974': ((0, 2999999, 1),(3000000, 5499999, 2),(5500000, 7499999, 3),(7500000, 8799999, 4),(8800000, 9099999, 3),(9100000, 9499999, 2),(9500000, 9999999, 2)), '978-9975': ((0, 999999, 1),(1000000, 2999999, 3),(3000000, 3999999, 4),(4000000, 4499999, 4),(4500000, 8999999, 2),(9000000, 9499999, 3),(9500000, 9999999, 4)), '978-9976': ((0, 4999999, 1),(5000000, 5799999, 4),(5800000, 5899999, 3),(5900000, 8999999, 2),(9000000, 9899999, 3),(9900000, 9999999, 4)), '978-9977': ((0, 8999999, 2),(9000000, 9899999, 3),(9900000, 9999999, 4)), '978-9978': ((0, 2999999, 2),(3000000, 3999999, 3),(4000000, 9499999, 2),(9500000, 9899999, 3),(9900000, 9999999, 4)), '978-9979': ((0, 4999999, 1),(5000000, 6499999, 2),(6500000, 6599999, 3),(6600000, 7599999, 2),(7600000, 8999999, 3),(9000000, 9999999, 4)), '978-9980': ((0, 3999999, 1),(4000000, 8999999, 2),(9000000, 9899999, 3),(9900000, 9999999, 4)), '978-9981': ((0, 999999, 2),(1000000, 1599999, 3),(1600000, 1999999, 4),(2000000, 7999999, 2),(8000000, 9499999, 3),(9500000, 9999999, 4)), '978-9982': ((0, 7999999, 2),(8000000, 9899999, 3),(9900000, 9999999, 4)), '978-9983': ((0, 7999999, 0),(8000000, 9499999, 2),(9500000, 9899999, 3),(9900000, 9999999, 4)), '978-9984': ((0, 4999999, 2),(5000000, 8999999, 3),(9000000, 9999999, 4)), '978-9985': ((0, 4999999, 1),(5000000, 7999999, 2),(8000000, 8999999, 3),(9000000, 9999999, 4)), '978-9986': ((0, 3999999, 2),(4000000, 8999999, 3),(9000000, 9399999, 4),(9400000, 9699999, 3),(9700000, 9999999, 2)), '978-9987': ((0, 3999999, 2),(4000000, 8799999, 3),(8800000, 9999999, 4)), '978-9988': ((0, 3999999, 1),(4000000, 5499999, 2),(5500000, 7499999, 3),(7500000, 9999999, 4)), '978-9989': ((0, 999999, 1),(1000000, 1999999, 3),(2000000, 2999999, 4),(3000000, 5999999, 2),(6000000, 9499999, 3),(9500000, 9999999, 4)), '978-99901': ((0, 4999999, 2),(5000000, 7999999, 3),(8000000, 9999999, 2)), '978-99902': ((0, 9999999, 0),), '978-99903': ((0, 1999999, 1),(2000000, 8999999, 2),(9000000, 9999999, 3)), '978-99904': ((0, 5999999, 1),(6000000, 8999999, 2),(9000000, 9999999, 3)), '978-99905': ((0, 3999999, 1),(4000000, 7999999, 2),(8000000, 9999999, 3)), '978-99906': ((0, 2999999, 1),(3000000, 5999999, 2),(6000000, 6999999, 3),(7000000, 8999999, 2),(9000000, 9499999, 2),(9500000, 9999999, 3)), '978-99908': ((0, 999999, 1),(1000000, 8999999, 2),(9000000, 9999999, 3)), '978-99909': ((0, 3999999, 1),(4000000, 9499999, 2),(9500000, 9999999, 3)), '978-99910': ((0, 2999999, 1),(3000000, 8999999, 2),(9000000, 9999999, 3)), '978-99911': ((0, 5999999, 2),(6000000, 9999999, 3)), '978-99912': ((0, 3999999, 1),(4000000, 5999999, 3),(6000000, 8999999, 2),(9000000, 9999999, 3)), '978-99913': ((0, 2999999, 1),(3000000, 3599999, 2),(3600000, 5999999, 0),(6000000, 6049999, 3),(6050000, 9999999, 0)), '978-99914': ((0, 4999999, 1),(5000000, 6999999, 2),(7000000, 7999999, 1),(8000000, 8999999, 2),(9000000, 9999999, 3)), '978-99915': ((0, 4999999, 1),(5000000, 7999999, 2),(8000000, 9999999, 3)), '978-99916': ((0, 2999999, 1),(3000000, 6999999, 2),(7000000, 9999999, 3)), '978-99917': ((0, 2999999, 1),(3000000, 8899999, 2),(8900000, 9999999, 3)), '978-99918': ((0, 3999999, 1),(4000000, 7999999, 2),(8000000, 9999999, 3)), '978-99919': ((0, 2999999, 1),(3000000, 3999999, 3),(4000000, 7999999, 2),(8000000, 9999999, 3)), '978-99920': ((0, 4999999, 1),(5000000, 8999999, 2),(9000000, 9999999, 3)), '978-99921': ((0, 1999999, 1),(2000000, 6999999, 2),(7000000, 7999999, 3),(8000000, 8999999, 1),(9000000, 9999999, 2)), '978-99922': ((0, 3999999, 1),(4000000, 6999999, 2),(7000000, 9999999, 3)), '978-99923': ((0, 1999999, 1),(2000000, 7999999, 2),(8000000, 9999999, 3)), '978-99924': ((0, 1999999, 1),(2000000, 7999999, 2),(8000000, 9999999, 3)), '978-99925': ((0, 999999, 1),(1000000, 1999999, 2),(2000000, 2999999, 3),(3000000, 3999999, 1),(4000000, 7999999, 2),(8000000, 9999999, 3)), '978-99926': ((0, 999999, 1),(1000000, 5999999, 2),(6000000, 8699999, 3),(8700000, 8999999, 2),(9000000, 9999999, 2)), '978-99927': ((0, 2999999, 1),(3000000, 5999999, 2),(6000000, 9999999, 3)), '978-99928': ((0, 999999, 1),(1000000, 7999999, 2),(8000000, 9999999, 3)), '978-99929': ((0, 4999999, 1),(5000000, 7999999, 2),(8000000, 9999999, 3)), '978-99930': ((0, 4999999, 1),(5000000, 7999999, 2),(8000000, 9999999, 3)), '978-99931': ((0, 4999999, 1),(5000000, 7999999, 2),(8000000, 9999999, 3)), '978-99932': ((0, 999999, 1),(1000000, 5999999, 2),(6000000, 6999999, 3),(7000000, 7999999, 1),(8000000, 9999999, 2)), '978-99933': ((0, 2999999, 1),(3000000, 5999999, 2),(6000000, 9999999, 3)), '978-99934': ((0, 1999999, 1),(2000000, 7999999, 2),(8000000, 9999999, 3)), '978-99935': ((0, 2999999, 1),(3000000, 5999999, 2),(6000000, 6999999, 3),(7000000, 8999999, 1),(9000000, 9999999, 2)), '978-99936': ((0, 999999, 1),(1000000, 5999999, 2),(6000000, 9999999, 3)), '978-99937': ((0, 1999999, 1),(2000000, 5999999, 2),(6000000, 9999999, 3)), '978-99938': ((0, 1999999, 1),(2000000, 5999999, 2),(6000000, 8999999, 3),(9000000, 9999999, 2)), '978-99939': ((0, 2999999, 1),(3000000, 5999999, 2),(6000000, 8999999, 2),(9000000, 9999999, 3)), '978-99940': ((0, 999999, 1),(1000000, 6999999, 2),(7000000, 9999999, 3)), '978-99941': ((0, 2999999, 1),(3000000, 7999999, 2),(8000000, 9999999, 3)), '978-99942': ((0, 4999999, 1),(5000000, 7999999, 2),(8000000, 9999999, 3)), '978-99943': ((0, 2999999, 1),(3000000, 5999999, 2),(6000000, 9999999, 3)), '978-99944': ((0, 4999999, 1),(5000000, 7999999, 2),(8000000, 9999999, 3)), '978-99945': ((0, 4999999, 1),(5000000, 8999999, 2),(9000000, 9999999, 3)), '978-99946': ((0, 2999999, 1),(3000000, 5999999, 2),(6000000, 9999999, 3)), '978-99947': ((0, 2999999, 1),(3000000, 6999999, 2),(7000000, 9999999, 3)), '978-99948': ((0, 4999999, 1),(5000000, 7999999, 2),(8000000, 9999999, 3)), '978-99949': ((0, 1999999, 1),(2000000, 7999999, 2),(8000000, 8999999, 1),(9000000, 9899999, 3),(9900000, 9999999, 2)), '978-99950': ((0, 4999999, 1),(5000000, 7999999, 2),(8000000, 9999999, 3)), '978-99951': ((0, 9999999, 0),), '978-99952': ((0, 4999999, 1),(5000000, 7999999, 2),(8000000, 9999999, 3)), '978-99953': ((0, 2999999, 1),(3000000, 7999999, 2),(8000000, 9399999, 3),(9400000, 9999999, 2)), '978-99954': ((0, 2999999, 1),(3000000, 6999999, 2),(7000000, 8799999, 3),(8800000, 9999999, 2)), '978-99955': ((0, 1999999, 1),(2000000, 5999999, 2),(6000000, 7999999, 3),(8000000, 9999999, 2)), '978-99956': ((0, 5999999, 2),(6000000, 8599999, 3),(8600000, 9999999, 2)), '978-99957': ((0, 1999999, 1),(2000000, 7999999, 2),(8000000, 9499999, 3),(9500000, 9999999, 2)), '978-99958': ((0, 4999999, 1),(5000000, 9399999, 2),(9400000, 9499999, 3),(9500000, 9999999, 3)), '978-99959': ((0, 2999999, 1),(3000000, 5999999, 2),(6000000, 9999999, 3)), '978-99960': ((0, 699999, 0),(700000, 999999, 3),(1000000, 9499999, 2),(9500000, 9999999, 3)), '978-99961': ((0, 2999999, 1),(3000000, 3699999, 3),(3700000, 8999999, 2),(9000000, 9999999, 3)), '978-99962': ((0, 4999999, 1),(5000000, 7999999, 2),(8000000, 9999999, 3)), '978-99963': ((0, 4999999, 2),(5000000, 9199999, 3),(9200000, 9999999, 2)), '978-99964': ((0, 1999999, 1),(2000000, 7999999, 2),(8000000, 9999999, 3)), '978-99965': ((0, 2999999, 1),(3000000, 3599999, 3),(3600000, 6299999, 2),(6300000, 9999999, 3)), '978-99966': ((0, 2999999, 1),(3000000, 6999999, 2),(7000000, 7999999, 3),(8000000, 9699999, 2),(9700000, 9999999, 3)), '978-99967': ((0, 999999, 1),(1000000, 5999999, 2),(6000000, 9999999, 3)), '978-99968': ((0, 3999999, 1),(4000000, 5999999, 3),(6000000, 8999999, 2),(9000000, 9999999, 3)), '978-99969': ((0, 4999999, 1),(5000000, 7999999, 2),(8000000, 9499999, 3),(9500000, 9999999, 2)), '978-99970': ((0, 4999999, 1),(5000000, 8999999, 2),(9000000, 9999999, 3)), '978-99971': ((0, 3999999, 1),(4000000, 8499999, 2),(8500000, 9999999, 3)), '978-99972': ((0, 4999999, 1),(5000000, 8999999, 2),(9000000, 9999999, 3)), '978-99973': ((0, 3999999, 1),(4000000, 7999999, 2),(8000000, 9999999, 3)), '978-99974': ((0, 999999, 1),(1000000, 2599999, 2),(2600000, 3999999, 3),(4000000, 6399999, 2),(6400000, 6499999, 3),(6500000, 7999999, 2),(8000000, 9999999, 3)), '978-99975': ((0, 2999999, 1),(3000000, 3999999, 3),(4000000, 7999999, 2),(8000000, 9999999, 3)), '978-99976': ((0, 999999, 1),(1000000, 1599999, 2),(1600000, 1999999, 3),(2000000, 5999999, 2),(6000000, 7999999, 3),(8000000, 8499999, 0),(8500000, 8999999, 2),(9000000, 9999999, 3)), '978-99977': ((0, 1999999, 1),(2000000, 3999999, 0),(4000000, 6999999, 2),(7000000, 7999999, 3),(8000000, 9949999, 0),(9950000, 9999999, 3)), '978-99978': ((0, 4999999, 1),(5000000, 6999999, 2),(7000000, 9999999, 3)), '978-99979': ((0, 3999999, 1),(4000000, 7999999, 2),(8000000, 9999999, 3)), '978-99980': ((0, 999999, 1),(1000000, 2999999, 0),(3000000, 5999999, 2),(6000000, 7499999, 0),(7500000, 9999999, 3)), '978-99981': ((0, 1999999, 1),(2000000, 2699999, 0),(2700000, 7499999, 2),(7500000, 9999999, 3)), '978-99982': ((0, 1999999, 1),(2000000, 4999999, 0),(5000000, 6899999, 2),(6900000, 8999999, 0),(9000000, 9999999, 3)), '978-99983': ((0, 999999, 1),(1000000, 4999999, 0),(5000000, 6999999, 2),(7000000, 9499999, 0),(9500000, 9999999, 3)), '978-99984': ((0, 999999, 1),(1000000, 4999999, 0),(5000000, 6999999, 2),(7000000, 9499999, 0),(9500000, 9999999, 3)), '978-99985': ((0, 1999999, 1),(2000000, 3499999, 0),(3500000, 7999999, 2),(8000000, 8499999, 0),(8500000, 9999999, 3)), '978-99986': ((0, 999999, 1),(1000000, 4999999, 0),(5000000, 6999999, 2),(7000000, 9499999, 0),(9500000, 9999999, 3)), '978-99987': ((0, 6999999, 0),(7000000, 9999999, 3)), '978-99988': ((0, 999999, 1),(1000000, 4999999, 0),(5000000, 5499999, 2),(5500000, 7999999, 0),(8000000, 8249999, 3),(8250000, 9999999, 0)), '978-99989': ((0, 999999, 1),(1000000, 4999999, 0),(5000000, 6499999, 2),(6500000, 8999999, 0),(9000000, 9999999, 3)), '978-99990': ((0, 999999, 1),(1000000, 4999999, 0),(5000000, 5499999, 2),(5500000, 9749999, 0),(9750000, 9999999, 3)), '978-99992': ((0, 1999999, 1),(2000000, 4999999, 0),(5000000, 6499999, 2),(6500000, 9499999, 0),(9500000, 9999999, 3)), '979-10': ((0, 1999999, 2),(2000000, 6999999, 3),(7000000, 8999999, 4),(9000000, 9759999, 5),(9760000, 9999999, 6)), '979-11': ((0, 2499999, 2),(2500000, 5499999, 3),(5500000, 8499999, 4),(8500000, 9499999, 5),(9500000, 9999999, 6)), '979-12': ((0, 1999999, 0),(2000000, 2999999, 3),(3000000, 5449999, 0),(5450000, 5999999, 4),(6000000, 7999999, 0),(8000000, 8499999, 5),(8500000, 9999999, 0)), '979-8': ((0, 1999999, 0),(2000000, 2299999, 3),(2300000, 3499999, 0),(3500000, 3999999, 4),(4000000, 8499999, 4),(8500000, 8849999, 4),(8850000, 8999999, 5),(9000000, 9849999, 0),(9850000, 9899999, 7),(9900000, 9999999, 0))} RDDATE='20230424' isbnlib-3.10.14/isbnlib/_desc.py000066400000000000000000000020171442216276400163630ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Return a small description of the book.""" import logging from json import loads from textwrap import fill from .dev import cache from .dev.webservice import query as wsquery LOGGER = logging.getLogger(__name__) UA = 'isbnlib (gzip)' SERVICE_URL = ( 'https://www.googleapis.com/books/v1/volumes?q=isbn:{isbn}' '&fields=items/volumeInfo(title,subtitle,authors,publisher,publishedDate,' 'language,industryIdentifiers,description,imageLinks)&maxResults=1') # pylint: disable=broad-except @cache def goo_desc(isbn): """Get description from Google Books api.""" url = SERVICE_URL.format(isbn=isbn) content = wsquery(url, user_agent=UA) try: content = loads(content) content = content['items'][0]['volumeInfo']['description'] # TODO(MV) don't format content here! content = fill(content, width=75) if content else '' return content except Exception: # pragma: no cover LOGGER.debug('No description for %s', isbn) return '' isbnlib-3.10.14/isbnlib/_doitotex.py000066400000000000000000000012241442216276400173030ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Return metadata, of a given DOI, formatted as BibTeX.""" import logging from .dev import cache from .dev.webservice import query LOGGER = logging.getLogger(__name__) URL = 'http://dx.doi.org/{DOI}' UA = 'isbnlib (gzip)' @cache def doi2tex(doi): """Get the bibtex ref for doi.""" data = query( URL.format(DOI=doi), user_agent=UA, appheaders={ 'Accept': 'application/x-bibtex; charset=utf-8', }, ) # noqa pragma: no cover if not data: # pragma: no cover LOGGER.warning('no data return for doi: %s', doi) return data if data else None # pragma: no cover isbnlib-3.10.14/isbnlib/_editions.py000066400000000000000000000047411442216276400172710ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Return editions for a given ISBN.""" import logging from ._core import EAN13, to_isbn13 from ._exceptions import NotRecognizedServiceError, NotValidISBNError from ._openled import query as _oed from ._thinged import query as _ted from ._wikied import query as _wiki from .dev import cache, vias PROVIDERS = ('any', 'merge', 'openl', 'thingl', 'wiki') LOGGER = logging.getLogger(__name__) # pylint: disable=broad-except # pylint: disable=consider-using-dict-items def _fake_provider_any(isbn): """Fake provider 'any' service.""" providers = {'wiki': _wiki, 'openl': _oed, 'thingl': _ted} for provider in providers: try: data = providers[provider](isbn) if len(data) > 1: return list(data) except Exception: # pragma: no cover LOGGER.error( "Some error on editions 'any' service for %s (%s)!", isbn, provider, ) continue # pragma: no cover return [isbn] # pragma: no cover # pylint: disable=broad-except def _fake_provider_merge(isbn): """Fake provider 'merge' service.""" try: # pragma: no cover named_tasks = (('openl', _oed), ('thingl', _ted), ('wiki', _wiki)) results = vias.parallel(named_tasks, isbn) odata = results.get('openl', set()) tdata = results.get('thingl', set()) wdata = results.get('wiki', set()) return list(odata | tdata | wdata) except Exception: # pragma: no cover LOGGER.error("Some error on editions 'merge' service for %s!", isbn) return [isbn] @cache def get_editions(isbn, service): """Select the provider.""" eds = [] if service == 'merge': eds = _fake_provider_merge(isbn) if service == 'any': eds = _fake_provider_any(isbn) if service == 'openl': eds = list(_oed(isbn)) if service == 'thingl': eds = list(_ted(isbn)) if service == 'wiki': eds = list(_wiki(isbn)) return list(set(map(to_isbn13, eds))) if eds else [] def editions(isbn, service='merge'): """Return the list of ISBNs of editions related with this ISBN.""" isbn = EAN13(isbn) if not isbn: LOGGER.critical('%s is not a valid ISBN', isbn) raise NotValidISBNError(isbn) if service not in PROVIDERS: LOGGER.critical('%s is not a recognized editions provider', service) raise NotRecognizedServiceError(service) return get_editions(isbn, service) isbnlib-3.10.14/isbnlib/_exceptions.py000066400000000000000000000043001442216276400176230ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa """Exceptions for isbnlib.""" import sys # pylint: disable=unused-argument def quiet_errors(exc_type, exc_value, traceback): """Define error format suitable for end user scripts. Usage: enter the following lines in your script from isbnlib import quiet_errors sys.excepthook = quiet_errors """ sys.stderr.write('Error: %s\n' % exc_value) # pragma: no cover class ISBNLibException(Exception): """Base class for isbnlib exceptions. This exception should not be raised directly, only subclasses of this exception should be used! """ def __str__(self): """Print message.""" return getattr(self, 'message', '') # pragma: no cover # pylint: disable=super-init-not-called class NotRecognizedServiceError(ISBNLibException): """Exception raised when the service is not in config.py.""" def __init__(self, service): """Define message.""" self.message = '(%s) is not a recognized service' % service # pylint: disable=super-init-not-called class NotValidDefaultServiceError(ISBNLibException): """Exception raised when the service is not valid for default.""" def __init__(self, service): """Define message.""" self.message = '(%s) is not a valid default service' % service # pylint: disable=super-init-not-called class NotValidDefaultFormatterError(ISBNLibException): """Exception raised when the formatter is not valid for default.""" def __init__(self, formatter): """Define message.""" self.message = '(%s) is not a valid default formatter' % formatter # pylint: disable=super-init-not-called class NotValidISBNError(ISBNLibException): """Exception raised when the ISBN is not valid.""" def __init__(self, isbnlike): """Define message.""" self.message = '(%s) is not a valid ISBN' % isbnlike # pylint: disable=super-init-not-called class PluginNotLoadedError(ISBNLibException): # pragma: no cover """Exception raised when the plugin's loader doesn't load the plugin. TODO: Delete this in version 4? """ def __init__(self, path): """Define message.""" self.message = "plugin (%s) wasn't loaded" % path isbnlib-3.10.14/isbnlib/_ext.py000066400000000000000000000051611442216276400162500ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Extra methods.""" import re from ._core import EAN13 from ._cover import cover as gcover from ._desc import goo_desc from ._editions import editions as eds from ._gwords import goos from ._infogroup import infogroup from ._metadata import query from ._msk import msk from .dev._bouth23 import b2u3, u from .dev.helpers import File, cutoff_tokens, last_first def mask(isbn, separator='-'): """`Mask` a canonical ISBN.""" return msk(isbn, separator) def meta(isbn, service='default'): """Get metadata from Google Books ('goob'), Open Library ('openl'), ...""" return query(isbn, service) if isbn else {} def info(isbn): """Get language or country assigned to this ISBN.""" return infogroup(isbn) def editions(isbn, service='merge'): """Return the list of ISBNs of editions related with this ISBN. 'service' can have the values: 'any', 'merge' (default), 'openl' and 'thingl' """ return eds(isbn, service) def isbn_from_words(words): """Return the most probable ISBN from a list of words.""" return goos(words) def doi(isbn): """Return a DOI's ISBN-A from a ISBN-13.""" try: value = '10.%s.%s%s/%s%s' % tuple(msk(EAN13(isbn), '-').split('-')) except TypeError: return '' return value def ren(fp): """Rename a file using metadata from an ISBN in his filename.""" cfp = File(fp) isbn = EAN13(cfp.name) if not isbn: # pragma: no cover return None data = meta(isbn) author = data.get('Authors', u('UNKNOWN')) if author != u('UNKNOWN'): # pragma: no cover author = last_first(author[0])['last'] year = data.get('Year', u('UNKNOWN')) maxlen = 98 - (20 + len(author) + len(year)) title = data.get('Title', u('UNKNOWN')) if title != u('UNKNOWN'): regex1 = re.compile(r'[.,_!?/\\]') regex2 = re.compile(r'\s\s+') title = regex1.sub(' ', title) title = regex2.sub(' ', title) title = title.strip() if title == u('UNKNOWN') or not title: # pragma: no cover return None if ' ' in title: # pragma: no cover tokens = title.split(' ') stitle = cutoff_tokens(tokens, maxlen) title = ' '.join(stitle) isbn13 = data.get('ISBN-13', u('UNKNOWN')) new_name = '%s%s_%s_%s' % (author, year, title, isbn13) return cfp.baserename(b2u3(new_name + cfp.ext)) def cover(isbn): """Get the img urls of the cover of the ISBN.""" isbn = EAN13(isbn) return gcover(isbn) if isbn else {} def desc(isbn): """Return a descripion of the ISBN.""" isbn = EAN13(isbn) return goo_desc(isbn) if isbn else '' isbnlib-3.10.14/isbnlib/_goob.py000066400000000000000000000056351442216276400164040ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Query the Google Books (JSON API v1) service for metadata.""" import logging from .dev import stdmeta from .dev._bouth23 import u from .dev._exceptions import ISBNNotConsistentError, RecordMappingError from .dev.webquery import query as wquery UA = 'isbnlib (gzip)' SERVICE_URL = ( 'https://www.googleapis.com/books/v1/volumes?q={isbn}' '&fields=items/volumeInfo(title,subtitle,authors,publisher,publishedDate,' 'language,industryIdentifiers,description,imageLinks)&maxResults=1') LOGGER = logging.getLogger(__name__) # pylint: disable=broad-except def _mapper(isbn, records): """Map: canonical <- records.""" # canonical: ISBN-13, Title, Authors, Publisher, Year, Language try: canonical = {} canonical['ISBN-13'] = u(isbn) title = records.get('title', u('')).replace(' :', ':') subtitle = records.get('subtitle', u('')) title = title + ' - ' + subtitle if subtitle else title canonical['Title'] = title canonical['Authors'] = records.get('authors', [u('')]) # see issue #64 canonical['Publisher'] = records.get('publisher', u('')).strip('"') if 'publishedDate' in records and len(records['publishedDate']) >= 4: canonical['Year'] = records['publishedDate'][0:4] else: # pragma: no cover canonical['Year'] = u('') canonical['Language'] = records.get('language', u('')) except Exception: # pragma: no cover LOGGER.debug('RecordMappingError for %s with data %s', isbn, records) raise RecordMappingError(isbn) # call stdmeta for extra cleaning and validation return stdmeta(canonical) def _records(isbn, data): """Classify (canonically) the parsed data.""" # put the selected data in records try: recs = data['items'][0]['volumeInfo'] except Exception: # pragma: no cover # don't raise exception! LOGGER.debug('No data from "goob" for isbn %s', isbn) return {} # consistency check (isbn request = isbn response) if recs: ids = recs.get('industryIdentifiers', '') if u('ISBN_13') in repr(ids) and isbn not in repr( ids): # pragma: no cover LOGGER.debug('ISBNNotConsistentError for %s (%s)', isbn, repr(ids)) raise ISBNNotConsistentError('{0} not in {1}'.format( isbn, repr(ids), )) else: return {} # pragma: no cover # map canonical <- records return _mapper(isbn, recs) def query(isbn): """Query the Google Books (JSON API v1) service for metadata.""" data = wquery(SERVICE_URL.format(isbn='isbn:' + isbn), user_agent=UA) if not data: # some times this work (see #119) data = wquery(SERVICE_URL.format(isbn=isbn), user_agent=UA) if not data: LOGGER.debug('No data from "goob" for isbn %s', isbn) return {} return _records(isbn, data) isbnlib-3.10.14/isbnlib/_goom.py000066400000000000000000000047641442216276400164210ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Query the Google Books (JSON API v1) for metadata.""" import logging try: from urllib.parse import quote except ImportError: from urllib import quote from .dev import cache, stdmeta from .dev._bouth23 import u from .dev._exceptions import NoDataForSelectorError, RecordMappingError from .dev.webquery import query as wquery UA = 'isbnlib (gzip)' SERVICE_URL = ( 'https://www.googleapis.com/books/v1/volumes?q={words}' '&fields=items/volumeInfo(title,authors,publisher,publishedDate,' 'language,industryIdentifiers)&maxResults=10') LOGGER = logging.getLogger(__name__) # pylint: disable=broad-except def _mapper(record): """Map canonical <- record.""" # canonical: # -> ISBN-13, Title, Authors, Publisher, Year, Language try: # mapping: canonical <- records if 'industryIdentifiers' not in record: # pragma: no cover return {} canonical = {} isbn = None for ident in record['industryIdentifiers']: if ident['type'] == 'ISBN_13': isbn = ident['identifier'] break if not isbn: # pragma: no cover return {} canonical['ISBN-13'] = isbn canonical['Title'] = record.get('title', u('')).replace(' :', ':') canonical['Authors'] = record.get('authors', []) canonical['Publisher'] = record.get('publisher', u('')) if 'publishedDate' in record and len(record['publishedDate']) >= 4: canonical['Year'] = record['publishedDate'][0:4] else: # pragma: no cover canonical['Year'] = u('') canonical['Language'] = record.get('language', u('')) except Exception: # pragma: no cover raise RecordMappingError(isbn) # call stdmeta for extra cleaning and validation return stdmeta(canonical) # pylint: disable=broad-except def _records(words, data): """Classify (canonically) the parsed data.""" # put the selected data in records try: recs = [d['volumeInfo'] for d in data['items']] except Exception: # pragma: no cover LOGGER.debug('NoDataForSelectorError for (%s)', words) raise NoDataForSelectorError(words) # map canonical <- records return [_mapper(r) for r in recs if _mapper(r)] @cache def query(words): """Query the Google Books (JSON API v1) for metadata.""" words.replace(' ', '+') words = quote(words) data = wquery(SERVICE_URL.format(words=words), UA) return _records(words, data) if data else {} isbnlib-3.10.14/isbnlib/_gwords.py000066400000000000000000000023351442216276400167550ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Use Google to get an ISBN from words from title and author's name.""" import logging from ._core import get_canonical_isbn, get_isbnlike from .dev import cache, webservice try: # pragma: no cover from urllib.parse import quote except ImportError: # pragma: no cover from urllib import quote LOGGER = logging.getLogger(__name__) @cache def goos(words): """Use Google to get an ISBN from words from title and author's name.""" service_url = 'http://www.google.com/search?q=ISBN+' search_url = service_url + quote(words.replace(' ', '+')) user_agent = 'w3m/0.5.3' content = webservice.query( search_url, user_agent=user_agent, appheaders={ 'Content-Type': 'text/plain; charset="UTF-8"', 'Content-Transfer-Encoding': 'Quoted-Printable', }, ) isbns = get_isbnlike(content) isbn = '' try: for item in isbns: isbn = get_canonical_isbn(item, output='isbn13') if isbn: # pragma: no cover break except IndexError: # pragma: no cover pass if not isbns or not isbn: # pragma: no cover LOGGER.debug('No ISBN found for %s', words) return isbn isbnlib-3.10.14/isbnlib/_imcache.py000066400000000000000000000024021442216276400170340ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Read and write to a dict-like cache.""" try: from collections.abc import MutableMapping # noqa except ImportError: # PY27 from collections import MutableMapping # noqa class IMCache(MutableMapping): """Read and write to a dict-like cache.""" MAXLEN = 1000 # pylint: disable=keyword-arg-before-vararg def __init__(self, maxlen=MAXLEN, *a, **k): self.filepath = 'IN MEMORY' self.maxlen = maxlen self.d = dict(*a, **k) while len(self) > maxlen: # pragma: no cache self.popitem() def __iter__(self): return iter(self.d) def __len__(self): return len(self.d) def __getitem__(self, k): return self.d[k] def __setitem__(self, k, v): if k not in self and len(self) == self.maxlen: self.popitem() self.d[k] = v def __contains__(self, key): return key in self.d def __delitem__(self, k): del self.d[k] def __bool__(self): return len(self) != 0 # For PY2 compatibility __nonzero__ = __bool__ def __call__(self, k): """Implement function call operator.""" try: return self.__getitem__(k) except KeyError: return None isbnlib-3.10.14/isbnlib/_infogroup.py000066400000000000000000000017401442216276400174570ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Get the Language/Country of an ISBN.""" import logging from ._core import EAN13 from ._data.data4info import countries, identifiers from ._exceptions import NotValidISBNError LOGGER = logging.getLogger(__name__) def infogroup(isbn): """Get the Language/Country of this ISBN.""" # if isbn is not a valid ISBN this def can give a wrong result! # => clean and validate isbn = EAN13(isbn) if not isbn: LOGGER.critical('%s is not a valid ISBN', isbn) raise NotValidISBNError(isbn) # put isbn in the form 978-... prefix = isbn[0:3] + '-' isbn = prefix + isbn[3:] dtxt = countries idents = identifiers ixi, ixf = 4, 5 for ident in idents: iid = prefix + isbn[ixi:ixf] ixf += 1 # stop if identifier is found if iid in ident: return dtxt[iid] LOGGER.debug( 'Identifier not found for %s (probably not issued yet!)', isbn, ) return '' isbnlib-3.10.14/isbnlib/_isbn.py000066400000000000000000000020461442216276400164020ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Isbn class.""" import logging as _logging from ._core import EAN13, canonical, to_isbn10 from ._exceptions import NotValidISBNError from ._ext import doi, info, mask LOGGER = _logging.getLogger(__name__) # pylint: disable=useless-object-inheritance # pylint: disable=too-many-instance-attributes # pylint: disable=too-few-public-methods # pylint: disable=broad-except class Isbn(object): """Class for ISBN objects.""" def __init__(self, isbnlike): self.ean13 = EAN13(isbnlike) if not self.ean13: LOGGER.debug('error: %s is not a valid ISBN', isbnlike) raise NotValidISBNError(isbnlike) self.canonical = canonical(isbnlike) self.isbn13 = mask(self.ean13) or self.ean13 self.isbn10 = mask(to_isbn10(self.ean13)) or to_isbn10(self.ean13) self.doi = doi(self.ean13) self.info = info(self.ean13) self.issued = '-' in self.isbn13 def __str__(self): return str(vars(self)) def __repr__(self): return self.__str__() isbnlib-3.10.14/isbnlib/_metadata.py000066400000000000000000000016311442216276400172260ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Query providers for metadata.""" import logging from importlib import import_module from ._core import EAN13 from ._exceptions import NotRecognizedServiceError, NotValidISBNError from .dev import cache LOGGER = logging.getLogger(__name__) def get_services(): """Import 'services' only when needed.""" reg = import_module('isbnlib.registry') return reg.services @cache def query(isbn, service='default'): """Query services like Google Books (JSON API), ... for metadata.""" ean = EAN13(isbn) if not ean: LOGGER.critical('%s is not a valid ISBN', isbn) raise NotValidISBNError(isbn) isbn = ean services = get_services() if service not in services: # pragma: no cover LOGGER.critical('%s is not a valid service', service) raise NotRecognizedServiceError(service) meta = services[service](isbn) return meta or {} isbnlib-3.10.14/isbnlib/_msk.py000066400000000000000000000035001442216276400162350ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Hyphenate an ISBN.""" import logging from ._core import EAN13, canonical, to_isbn13 from ._data.data4mask import ranges from ._exceptions import NotValidISBNError LOGGER = logging.getLogger(__name__) def msk(isbn, separator='-'): """Transform a canonical ISBN to a `masked` one. `Mask` the ISBN, separating by identifier ISBN-10 identifiers: country-publisher-title-check Used the iterative version of the `sliding-window` algorithm. Not pretty, but fast! Lines 45-52 implement the search loop: O(n) for n (number of keys), with data structure 'ranges' (see data4mask.py) """ if not isbn: return '' ib = canonical(isbn) ean = EAN13(ib) if len(ib) not in (10, 13) or not ean: LOGGER.critical('%s is not a valid ISBN', isbn) raise NotValidISBNError(isbn) isbn10 = False if len(ib) == 10: check10 = ib[-1] ib = to_isbn13(ib) isbn10 = True idx = None check = ib[-1:] # <-- HACK! cur = 3 igi = cur buf = ib[igi:cur + 1] group = ib[0:cur] + '-' + buf for _ in range(6): # pragma: no cover if group in ranges: sevens = ib[cur + 1:cur + 8].ljust(7, '0') for l in ranges[group]: if l[0] <= int(sevens) <= l[1]: idx = l[2] break break cur += 1 buf = ib[igi:cur + 1] group = group + buf[-1:] # <-- HACK! if idx is not None: # <-- issue #114 (idx=0 is valid too) [thanks @slint] if isbn10: group = group[4:] check = check10 return separator.join( [group, ib[cur + 1:cur + idx + 1], ib[cur + idx + 1:-1], check]) LOGGER.warning('identifier not found!') # pragma: no cover return '' # pragma: no cover isbnlib-3.10.14/isbnlib/_oclc.py000066400000000000000000000052331442216276400163700ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Query the 'classify.oclc.org' service for classifiers.""" import logging import re from .dev import cache from .dev._bouth23 import u from .dev.webquery import query as wquery UA = 'isbnlib (gzip)' SERVICE_URL = 'http://classify.oclc.org/classify2/Classify?isbn={isbn}&maxRecs=1' LOGGER = logging.getLogger(__name__) RE_OWI = re.compile(r'owi="(.*?)"', re.I | re.M | re.S) RE_OCLC = re.compile(r'oclc="(.*?)"', re.I | re.M | re.S) RE_DDC = re.compile(r'(.*?)', re.I | re.M | re.S) RE_LCC = re.compile(r'(.*?)', re.I | re.M | re.S) RE_NSFA = re.compile(r'nsfa="(.*?)"', re.I | re.M | re.S) RE_SFA = re.compile(r' sfa="(.*?)"', re.I | re.M | re.S) RE_HEADINGS = re.compile(r'(.*?)', re.I | re.M | re.S) RE_FLDS = re.compile(r' ident="(.*?)"', re.I | re.M | re.S) RE_VALS = re.compile(r'fast">(.*?)', re.I | re.M | re.S) def data_checker(xml): """Check the response from the service.""" if not xml: LOGGER.debug("The service 'oclc' is temporarily down!") return False if 'response code="102"' in xml: LOGGER.debug("The service 'oclc' is temporarily very slow!") return False return True def parser(xml): """Parse the response from the service.""" if not xml: return {} # pragma: no cover data = {} match = RE_OWI.search(u(xml)) if match: data['owi'] = match.group(1) match = RE_OCLC.search(u(xml)) if match: data['oclc'] = match.group(1) match = RE_LCC.search(u(xml)) if match: buf = match.group() match = RE_SFA.search(buf) if match: data['lcc'] = match.group(1) match = RE_DDC.search(u(xml)) if match: buf = match.group() match = RE_SFA.search(buf) if match: data['ddc'] = match.group(1) fast = parser_headings(xml) if fast: data['fast'] = fast return data # pylint: disable=broad-except def parser_headings(xmlthing): """RE parser for classify.oclc service (headings branch).""" match = RE_HEADINGS.search(u(xmlthing)) if match: try: buf = match.group() flds = RE_FLDS.findall(buf) vals = RE_VALS.findall(buf) return dict(zip(flds, vals)) except Exception: # pragma: no cover LOGGER.debug("Bad parsing of 'headings' for 'oclc' service!") return {} # pragma: no cover @cache def query_classify(isbn): """Query the classify.oclc service for classifiers.""" return (wquery( SERVICE_URL.format(isbn=isbn), user_agent=UA, data_checker=data_checker, parser=parser, ) or {}) isbnlib-3.10.14/isbnlib/_openl.py000066400000000000000000000050041442216276400165610ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Query the openlibrary.org service for metadata.""" import logging import re from .dev import stdmeta from .dev._bouth23 import u from .dev._exceptions import DataNotFoundAtServiceError, RecordMappingError from .dev.webquery import query as wquery UA = 'isbnlib (gzip)' SERVICE_URL = ('http://openlibrary.org/api/books?bibkeys=' 'ISBN:{isbn}&format=json&jscmd=data') LOGGER = logging.getLogger(__name__) # pylint: disable=broad-except def _mapper(isbn, records): """Map canonical <- records.""" # canonical: # -> ISBN-13, Title, Authors, Publisher, Year, Language try: # mapping: canonical <- records canonical = {} canonical['ISBN-13'] = u(isbn) title = records.get('title', u('')).replace(' :', ':') subtitle = records.get('subtitle', u('')) title = title + ' - ' + subtitle if subtitle else title canonical['Title'] = title canonical['Authors'] = [ a['name'] for a in records.get( 'authors', ({ 'name': u(''), }, ), ) ] canonical['Publisher'] = records.get( 'publishers', [ { 'name': u(''), }, ], )[0]['name'] canonical['Year'] = u('') strdate = records.get('publish_date', u('')) if strdate: # pragma: no cover match = re.search(r'\d{4}', strdate) if match: canonical['Year'] = match.group(0) except Exception: # pragma: no cover LOGGER.debug('RecordMappingError for %s with data %s', isbn, records) raise RecordMappingError(isbn) # call stdmeta for extra cleaning and validation return stdmeta(canonical) # pylint: disable=broad-except def _records(isbn, data): """Classify (canonically) the parsed data.""" try: # put the selected data in records records = data['ISBN:%s' % isbn] except Exception: # pragma: no cover # don't raise exception! LOGGER.debug('No data from "openl" for isbn %s', isbn) return {} # map canonical <- records return _mapper(isbn, records) def query(isbn): """Query the openlibrary.org service for metadata.""" try: data = wquery(SERVICE_URL.format(isbn=isbn), user_agent=UA) except DataNotFoundAtServiceError: LOGGER.debug('No data from "openl" for isbn %s', isbn) return {} return _records(isbn, data) isbnlib-3.10.14/isbnlib/_openled.py000066400000000000000000000014771442216276400171040ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Query the Open Library for related ISBNs.""" import logging from . import to_isbn13 from .dev._bouth23 import u from .dev.webquery import query as wquery LOGGER = logging.getLogger(__name__) UA = 'isbnlib (gzip)' SERVICE_URL = 'https://openlibrary.org/search.json?q={isbn}&fields=isbn' # pylint: disable=broad-except def query(isbn): """Query the Open Library for related ISBNs.""" try: data = wquery( SERVICE_URL.format(isbn=isbn), user_agent=UA, ) isbns = {u(to_isbn13(isbn)) for isbn in data['docs'][0]['isbn']} except Exception as ex: # pragma: no cover LOGGER.debug( 'No data from Open Library for isbn %s -- %s', isbn, str(ex), ) return {to_isbn13(isbn)} return isbns isbnlib-3.10.14/isbnlib/_thinged.py000066400000000000000000000022201442216276400170630ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Query the ThingISBN api (Library Thing) for related ISBNs.""" import logging from xml.dom.minidom import parseString from ._core import EAN13 from .dev.webquery import query as wquery LOGGER = logging.getLogger(__name__) UA = 'isbnlib (gzip)' SERVICE_URL = 'http://www.librarything.com/api/thingISBN/{isbn}' def _get_text(topnode): """Get the text values in the child nodes.""" text = '' for node in topnode.childNodes: if node.nodeType == node.TEXT_NODE: text = text + node.data return text def parser_thinged(xml): """Parse the response from the ThingISBN service.""" dom = parseString(xml) nodes = dom.getElementsByTagName('idlist')[0].getElementsByTagName('isbn') return [EAN13(_get_text(isbn)) for isbn in nodes] def query(isbn): """Query the ThingISBN service for related ISBNs.""" data = wquery( SERVICE_URL.format(isbn=isbn), user_agent=UA, parser=parser_thinged, ) if not data: # pragma: no cover LOGGER.debug('No data from ThingISBN for isbn %s', isbn) data = [] data.append(EAN13(isbn)) return set(data) isbnlib-3.10.14/isbnlib/_wiki.py000066400000000000000000000056711442216276400164210ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Query the wikipedia.org service for metadata.""" import logging import re from .dev import stdmeta from .dev._bouth23 import u from .dev._exceptions import DataNotFoundAtServiceError, RecordMappingError from .dev.webquery import query as wquery UA = 'isbnlib (gzip)' SERVICE_URL = 'https://en.wikipedia.org/api/rest_v1/data/citation/mediawiki/{isbn}' LOGGER = logging.getLogger(__name__) # pylint: disable=broad-except def _mapper(isbn, records): """Map canonical <- records.""" # canonical: # -> ISBN-13, Title, Authors, Publisher, Year, Language try: # mapping: canonical <- records canonical = {} canonical['ISBN-13'] = u(isbn) canonical['Title'] = records.get('title', u('')).replace(' :', ':') # try to handle the inconsistent use of fields by Wikipedia (issue #65)! try: authors = [ ' '.join(sublist) for sublist in records.get('author', [u('')]) ] canonical['Authors'] = [ author.replace('.', u('')) for author in authors ] buf = canonical.get('Authors', []) if not buf or len(buf[0]) == 0: raise IndexError except IndexError: try: authors = [ ' '.join(sublist) for sublist in records.get('contributor', [u('')]) ] canonical['Authors'] = [ author.replace('.', u('')) for author in authors ] except IndexError: pass canonical['Publisher'] = records.get('publisher', u('')) or u(' '.join( [pub for pub in records.get('contributor', [u('')])[0] if pub])) canonical['Year'] = u('') strdate = records.get('date', u('')) if strdate: # pragma: no cover match = re.search(r'\d{4}', strdate) if match: canonical['Year'] = match.group(0) except Exception: # pragma: no cover LOGGER.debug('RecordMappingError for %s with data %s', isbn, records) raise RecordMappingError(isbn) # call stdmeta for extra cleaning and validation return stdmeta(canonical) # pylint: disable=broad-except def _records(isbn, data): """Classify (canonically) the parsed data.""" try: # put the selected data in records records = data[0] except Exception: # pragma: no cover # don't raise exception! LOGGER.debug('No data from "wikipedia" for isbn %s', isbn) return {} # map canonical <- records return _mapper(isbn, records) def query(isbn): """Query the wikipedia.org service for metadata.""" try: data = wquery(SERVICE_URL.format(isbn=isbn), user_agent=UA, throttling=0) except DataNotFoundAtServiceError: LOGGER.debug('No data from "wikipedia" for isbn %s', isbn) return {} return _records(isbn, data) isbnlib-3.10.14/isbnlib/_wikied.py000066400000000000000000000016211442216276400167210ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Query the wikipedia.org service for related ISBNs.""" import logging from ._core import to_isbn13 from .dev.webquery import query as wquery UA = 'isbnlib (gzip)' SERVICE_URL = 'https://en.wikipedia.org/api/rest_v1/data/citation/mediawiki/{isbn}' LOGGER = logging.getLogger(__name__) # pylint: disable=broad-except def _parser(isbn, data): """Parse the response from the Wikipedia service.""" editions = [to_isbn13(isbn)] try: records = data[0].get('ISBN', []) eds = {to_isbn13(isbn) for isbn in records} editions.extend(eds) except Exception: # pragma: no cover LOGGER.debug('No data from "wikipedia" for isbn %s', isbn) return editions def query(isbn): """Query the wikipedia.org service for 'editions'.""" data = wquery(SERVICE_URL.format(isbn=isbn), user_agent=UA, throttling=0) return set(_parser(isbn, data)) isbnlib-3.10.14/isbnlib/config.py000066400000000000000000000023241442216276400165540ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Config file for isbnlib.""" # --> Import only external modules! <-- # API keys apikeys = {} def add_apikey(service, apikey): # pragma: no cover """Add API keys.""" global apikeys apikeys[service.lower()] = apikey # Options options = { 'LOAD_FORMATTER_PLUGINS': True, 'LOAD_METADATA_PLUGINS': True, 'THREADS_TIMEOUT': 12, # seconds 'URLOPEN_TIMEOUT': 10, # seconds 'VIAS_MERGE': 'parallel', } def set_option(option, value): # pragma: no cover """Set the value for option.""" global options options[option.upper()] = value # URLOPEN_TIMEOUT is used by webservice def seturlopentimeout(seconds): # pragma: no cover """Set the value of URLOPEN_TIMEOUT (in seconds).""" set_option('URLOPEN_TIMEOUT', seconds) # THREADS_TIMEOUT is a parameter used downstream by Thread calls (see vias.py) def setthreadstimeout(seconds): # pragma: no cover """Set the value of THREADS_TIMEOUT (in seconds).""" set_option('THREADS_TIMEOUT', seconds) def setloadplugins(boolean=True): # pragma: no cover """Set the value for all LOAD_XXX_PLUGINS.""" set_option('LOAD_METADATA_PLUGINS', boolean) set_option('LOAD_FORMATTER_PLUGINS', boolean) isbnlib-3.10.14/isbnlib/dev/000077500000000000000000000000001442216276400155125ustar00rootroot00000000000000isbnlib-3.10.14/isbnlib/dev/__init__.py000066400000000000000000000015101442216276400176200ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Interface for namespace 'isbnlib.dev'.""" from ._data import Metadata, stdmeta from ._decorators import cache from ._exceptions import ( DataNotFoundAtServiceError, DataWrongShapeError, ISBNLibDevException, ISBNLibHTTPError, ISBNLibURLError, NoAPIKeyError, NoDataForSelectorError, NotValidMetadataError, RecordMappingError, ServiceIsDownError, ) from .webquery import WEBQuery from .webservice import WEBService __all__ = ( 'ISBNLibDevException', 'ISBNLibURLError', 'ISBNLibHTTPError', 'DataNotFoundAtServiceError', 'ServiceIsDownError', 'DataWrongShapeError', 'NotValidMetadataError', 'NoDataForSelectorError', 'RecordMappingError', 'NoAPIKeyError', 'Metadata', 'stdmeta', 'WEBService', 'WEBQuery', 'cache', ) isbnlib-3.10.14/isbnlib/dev/_bouth23.py000066400000000000000000000014361442216276400175150ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8:noqa # pylint: skip-file """Help code to run in py2 and py3.""" import sys if sys.version < '3': def s(x): return x def b(x): return x def u(x): try: return unicode(x, 'utf-8') except TypeError: return x def b2u3(x): return x.encode('utf-8') def type3str(): return type(u'') def bstream(x): from StringIO import StringIO return StringIO(x) else: def s(x): return x.decode('utf-8', 'ignore') def b(x): return x.encode('utf-8') def u(x): return x def b2u3(x): return x def type3str(): return type('') def bstream(x): from io import BytesIO return BytesIO(x) isbnlib-3.10.14/isbnlib/dev/_data.py000066400000000000000000000064261442216276400171440ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Handle metadata objects.""" import logging from ._bouth23 import type3str, u from ._exceptions import NotValidMetadataError from ._helpers import normalize_space, titlecase # For now you cannot add custom fields! FIELDS = ('ISBN-13', 'Title', 'Authors', 'Publisher', 'Year', 'Language') LOGGER = logging.getLogger(__name__) # pylint: disable=useless-object-inheritance class Metadata(object): """Class for metadata objects.""" def __init__(self, record=None): """Initialize attributes.""" self._content = None self._set_empty() if record: # pragma: no cover self._content.update((k, v) for k, v in list(record.items())) if not self._validate(): self._set_empty() LOGGER.debug(record) raise NotValidMetadataError() self.clean() @staticmethod def fields(): # pragma: no cover """Return a list of value's fields.""" return list(FIELDS) def clean(self, broom=normalize_space, exclude=()): """Clean fields of value.""" self._content.update( (k, broom(v)) for k, v in list(self._content.items()) if k != 'Authors' and k not in exclude ) if 'Authors' not in exclude: self._content['Authors'] = [ broom(i) for i in self._content['Authors'] ] self._content['Title'] = self._content['Title'].strip(',.:;-_ ') if self._content['Language'].lower() in ('en', 'eng', 'english'): self._content['Title'] = titlecase(self._content['Title']) @property def value(self): """Get value.""" return self._content @value.setter def value(self, record): # pragma: no cover """Set value.""" self._content.update((k, v) for k, v in list(record.items())) if not self._validate(): self._set_empty() LOGGER.debug(record) raise NotValidMetadataError() self.clean() @value.deleter def value(self): # pragma: no cover """Delete value.""" self._set_empty() def merge( self, record, overwrite=(), overrule=lambda x: x == u('') or x == [u('')], ): """Merge the record with value.""" # by default do nothing self._content.update( (k, v) for k, v in list(record.items()) if k in overwrite and not overrule(v) or self._content[k] == u('') ) if not self._validate(): # pragma: no cover self._set_empty() LOGGER.debug(record) raise NotValidMetadataError() self.clean() def _validate(self): """Validate value.""" # 'minimal' check for k in self._content: if not isinstance(self._content[k], type3str()) and k != 'Authors': return False if not isinstance(self._content['Authors'], list): return False return True def _set_empty(self): """Set an empty value record.""" self._content = dict.fromkeys(list(FIELDS), u('')) self._content['Authors'] = [u('')] def stdmeta(records): """Transform data using class Metadata.""" data = Metadata(records) return data.value isbnlib-3.10.14/isbnlib/dev/_decorators.py000066400000000000000000000023521442216276400203720ustar00rootroot00000000000000# -*- coding: utf-8 -*- # isort:skip_file """Decorator for isbnlib.""" from functools import wraps from .._imcache import IMCache im_cache = IMCache(maxlen=200) def cache(func): """Cache decorator (cache).""" # noqa @wraps(func) def memoized_func(*args, **kwargs): from ..registry import metadata_cache # <-- dynamic and lazy cch = metadata_cache if cch is None: # pragma: no cover return func(*args, **kwargs) # Persistent caches will NOT work IF # 'func' has callables in the arguments key = str(func.__name__) + str(args) + str(kwargs) if key in cch: return cch[key] else: value = func(*args, **kwargs) if value: cch[key] = value return value return memoized_func def imcache(func): """Cache decorator (imcache).""" # noqa @wraps(func) def memoized_func(*args, **kwargs): cch = im_cache key = str(func.__name__) + str(args) + str(kwargs) if key in cch: return cch[key] else: value = func(*args, **kwargs) if value: cch[key] = value return value return memoized_func isbnlib-3.10.14/isbnlib/dev/_exceptions.py000066400000000000000000000047541442216276400204160ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Exceptions for 'isbnlib.dev'. The classes in isbnlib.dev should use the exceptions below. """ # TODO(MV) merge these exceptions with the top exceptions on version 4. from .._exceptions import ISBNLibException # pylint: disable=super-init-not-called class ISBNLibDevException(ISBNLibException): """Base class for isbnlib.dev exceptions. This exception should not be raised directly, only subclasses of this exception should be used! """ def __init__(self, msg=None): if msg: self.message = '%s (%s)' % (self.message, msg) def __str__(self): return getattr(self, 'message', '') # pragma: no cover class ISBNLibHTTPError(ISBNLibDevException): """Exception raised for HTTP related errors.""" message = 'an HTTP error has ocurred' class ISBNLibURLError(ISBNLibDevException): """Exception raised for URL related errors.""" message = 'an URL error has ocurred' class DataNotFoundAtServiceError(ISBNLibDevException): """Exception raised when there is no target data from the service.""" message = 'the target data was not found at this service' class ServiceIsDownError(ISBNLibDevException): """Exception raised when the service is not available.""" message = 'the service is down (try later)' class DataWrongShapeError(ISBNLibDevException): """Exception raised when the data hasn't the expected format.""" message = "the data hasn't the expected format" class NoDataForSelectorError(ISBNLibDevException): """Exception raised when there is no data for the selector.""" message = 'no data for this selector' class NotValidMetadataError(ISBNLibDevException): """Exception raised when the metadata hasn't the expected format.""" message = "the metadata hasn't the expected format" class ISBNNotConsistentError(ISBNLibDevException): """Exception raised when the isbn request != isbn response.""" message = 'isbn request != isbn response' class RecordMappingError(ISBNLibDevException): """Exception raised when the mapping records -> canonical doesn't work.""" message = "the mapping `canonical <- records` doesn't work" class NoAPIKeyError(ISBNLibDevException): """Exception raised when the API Key for a service is not found.""" message = 'this service needs an API key' # pylint: disable=redefined-builtin class FileNotFoundError(ISBNLibDevException): """Exception raised when a given file doesn't exist.""" message = "the file wasn't found" isbnlib-3.10.14/isbnlib/dev/_files.py000066400000000000000000000064701442216276400173340ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Helper module to work with files.""" import fnmatch import logging import os import re from stat import S_IRGRP, S_IROTH, S_IRUSR, S_IWGRP, S_IWOTH, S_IWUSR # pylint: disable=redefined-builtin from ._exceptions import FileNotFoundError MAXLEN = 120 ILLEGAL = r'<>:"/\|?*' LOGGER = logging.getLogger(__name__) MODE666 = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH # pylint: disable=useless-object-inheritance class File(object): """Easy manipulation of files in the SAME directory.""" def __init__(self, fp): """Set and validate the basic properties.""" if not self.isfile(fp): raise FileNotFoundError(fp) self.path = os.path.dirname(fp) or os.getcwd() self.basename = os.path.basename(fp) self.name, self.ext = os.path.splitext(self.basename) self.writable = os.access(fp, os.W_OK) def siblings(self): """Collect files and directories in the same directory.""" return [f for f in os.listdir(self.path) if f != self.basename] @staticmethod def isfile(path): """Check if a given path is a file.""" return os.path.isfile(path) @staticmethod def exists(path): """Check if a given path is a file or a directory.""" return os.path.exists(path) @staticmethod def mkwinsafe(name, space=' '): """Delete most common characters not allowed in Windows filenames.""" space = space if space not in ILLEGAL else ' ' name = ''.join(c for c in name if c not in ILLEGAL).replace(' ', space).strip() name = re.sub(r'\s\s+', ' ', name) if space == ' ' else name return name[:MAXLEN] @staticmethod def validate(basename): """Check for a proper basename.""" if basename != os.path.basename(basename): LOGGER.critical('This (%s) is not a basename!', basename) return False name, ext = os.path.splitext(basename) if not name: LOGGER.critical('Not a valid name (length 0)!') return False if not ext: LOGGER.critical('Not a valid extension (length 0)!') return False return True def baserename(self, new_basename): """Rename the file to a 'safe' basename.""" if not self.validate(new_basename): return False name, ext = os.path.splitext(new_basename) name = self.mkwinsafe(name) new_basename = name + ext if new_basename == self.basename: return True if new_basename not in self.siblings(): try: os.rename(self.basename, new_basename) except OSError as err: LOGGER.critical('%s', err) return False self.basename = new_basename self.name = name self.ext = ext else: LOGGER.info( 'The file (%s) already exist in the directory!', new_basename, ) return True @staticmethod def uxchmod(fp, mode=MODE666): """Change the mode of the file (default is 0666).""" return os.chmod(fp, mode) def cwdfiles(pattern='*'): """List the files in current directory that match a given pattern.""" return fnmatch.filter(os.listdir('.'), pattern) isbnlib-3.10.14/isbnlib/dev/_fmt.py000066400000000000000000000102041442216276400170060ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa # pylint: skip-file """Format canonical in bibliographic formats.""" import re import uuid from string import Template from ._helpers import last_first bibtex = r"""@book{$ISBN, title = {$Title}, author = {$AUTHORS}, isbn = {$ISBN}, year = {$Year}, publisher = {$Publisher} }""" endnote = r"""%0 Book %T $Title %A $AUTHORS %@ $ISBN %D $Year %I $Publisher """ ris = r"""TY - BOOK T1 - $Title A1 - $AUTHORS SN - $ISBN Y1 - $Year PB - $Publisher ER - """ msword = (r""" $uid Book $AUTHORS $Title $Year $Publisher """) json = r"""{"type": "book", "title": "$Title", "author": [$AUTHORS], "year": "$Year", "identifier": [{"type": "ISBN", "id": "$ISBN"}], "publisher": "$Publisher"}""" csl = r"""{"type":"book", "id":"$ISBN", "title":"$Title", "author": [$AUTHORS], "issued": {"date-parts": [[$Year]]}, "ISBN":"$ISBN", "publisher":"$Publisher"}""" csv = '"book","$ISBN","$Title","$AUTHORS","$Year","$Publisher"' opf = r""" Book $uid $ISBN $Title $AUTHORS $Publisher $Year isbnlib [http://github.com/xlcnd/isbnlib] """ labels = r"""Type: BOOK Title: $Title Author: $AUTHORS ISBN: $ISBN Year: $Year Publisher: $Publisher""" templates = { 'labels': labels, 'bibtex': bibtex, 'endnote': endnote, 'ris': ris, 'msword': msword, 'json': json, 'csl': csl, 'csv': csv, 'opf': opf, } _fmts = list(templates.keys()) def _gen_proc(name, canonical): if 'ISBN-13' in canonical: canonical['ISBN'] = canonical.pop('ISBN-13') canonical['Title'] = canonical.get('Title').replace('"', '') tpl = templates[name] return Template(tpl).safe_substitute(canonical) def _spec_proc(name, fmtrec, authors): """Fix the Authors records.""" if name not in _fmts: return if not authors: return if name == 'labels': AUTHORS = '\nAuthor: '.join(authors) elif name == 'bibtex': AUTHORS = ' and '.join(authors) elif name == 'ris': AUTHORS = '\nA1 - '.join(authors) elif name == 'endnote': AUTHORS = '\n%A '.join(authors) elif name == 'msword': fmtrec = fmtrec.replace('$uid', str(uuid.uuid4())) person = (r'$last' r'$first') AUTHORS = '\n'.join( Template(person).safe_substitute(last_first(a)) for a in authors) elif name == 'json': AUTHORS = ', '.join('{"name": "$"}'.replace('$', a) for a in authors) elif name == 'csl': AUTHORS = ', '.join('{"literal": "$"}'.replace('$', a) for a in authors) elif name == 'csv': AUTHORS = ', '.join(authors) elif name == 'opf': fmtrec = fmtrec.replace('$uid', str(uuid.uuid4())) creator = (r'$first $last') AUTHORS = '\n '.join( Template(creator).safe_substitute(last_first(author)) for author in authors) return re.sub(r'\$AUTHORS', AUTHORS, fmtrec) def _fmtbib(fmtname, canonical): """Return a canonical record in the selected format.""" return _spec_proc( fmtname, _gen_proc(fmtname, canonical), canonical.get('Authors'), ) isbnlib-3.10.14/isbnlib/dev/_helpers.py000066400000000000000000000041311442216276400176640ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Private helper functions.""" import re from hashlib import md5 from ._bouth23 import b def fake_isbn(title, author='unkown', publisher='unkown', sid=1): """Produce a fake ISBN from the (title, author, publisher) of the book.""" key = '%s %s %s' % (title, author, publisher) # normalize regex1 = re.compile(r'\?|,|\.|!|\:|;', re.I | re.M | re.S) regex2 = re.compile(r'\s\s+', re.I | re.M | re.S) key = regex1.sub(' ', key) key = regex2.sub(' ', key).strip().lower() # hash return (str(sid) + str(int(md5(b(key)).hexdigest()[:10], 16)))[:13] def normalize_space(item): """Normalize white space. Strips leading and trailing white space and replaces sequences of white space characters with a single space. """ item = re.sub(r'\s\s+', ' ', item) return item.strip() def titlecase(st): """Format string in 'title case' (for ascii).""" try: st.encode('ascii') return re.sub( r"[A-Za-z]+('[A-Za-z]+)?", lambda m: m.group(0)[0].upper() + m.group(0)[1:], st, ) except (UnicodeEncodeError, UnicodeDecodeError): # pragma: no cover return st def last_first(author): """Parse an author name into last (name) and first.""" if ',' in author: tokens = author.split(',') last = tokens[0].strip() first = ' '.join(tokens[1:]).strip().replace(' ', ', ') else: tokens = author.split(' ') last = tokens[-1].strip() first = ' '.join(tokens[:-1]).strip() return {'last': last, 'first': first} def cutoff_tokens(tokens, cutoff): """Keep only the tokens with total length <= cutoff.""" ltokens = [len(t) for t in tokens] length = 0 stokens = [] for token, ln in zip(tokens, ltokens): if length + ln <= cutoff: length = length + ln stokens.append(token) else: break return stokens def parse_placeholders(pattern): """Return a list of placeholders in a pattern.""" regex = re.compile(r'({[^}]*})') return regex.findall(pattern) isbnlib-3.10.14/isbnlib/dev/helpers.py000066400000000000000000000010731442216276400175270ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8:noqa # pylint: skip-file """Expose useful features.""" from .._imcache import IMCache from ._files import File, cwdfiles from ._fmt import _fmtbib, _fmts from ._helpers import ( cutoff_tokens, fake_isbn, last_first, normalize_space, parse_placeholders, ) # alias (to keep backwards compatibility) fmtbib = _fmtbib fmts = _fmts __all__ = [ 'File', 'IMCache', 'cutoff_tokens', 'cwdfiles', 'fmtbib', 'fmts', 'last_first', 'normalize_space', 'parse_placeholders', 'fake_isbn', ] isbnlib-3.10.14/isbnlib/dev/vias.py000066400000000000000000000040621442216276400170300ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Process tasks in several modes.""" import logging from ..config import options LOGGER = logging.getLogger(__name__) # pylint: disable=broad-except def serial(named_tasks, arg): """Use serial calls.""" results = {} for name, task in named_tasks: try: results[name] = task(arg) except Exception: # pragma: no cover LOGGER.debug( "No result in 'serial' for %s[%s](%s)", task, name, arg, ) results[name] = None return results # pylint: disable=broad-except def parallel(named_tasks, arg): """Use threaded calls.""" from threading import Thread results = {} def _worker(name, task, arg): try: results[name] = task(arg) except Exception: # pragma: no cover LOGGER.debug( "No result in 'parallel' for %s[%s](%s)", task, name, arg, ) results[name] = None for name, task in named_tasks: t = Thread(target=_worker, args=(name, task, arg)) t.start() t.join(options.get('THREADS_TIMEOUT')) return results # pylint: disable=broad-except def multi(named_tasks, arg): """Use several cores (if available).""" from multiprocessing import Process, Queue results = {} q = Queue() def _worker(name, task, arg, q): try: # pragma: no cover q.put((name, task(arg))) except Exception: # pragma: no cover LOGGER.debug( "No result in 'multi' for %s[%s](%s)", task, name, arg, ) q.put((name, None)) for name, task in named_tasks: p = Process(target=_worker, args=(name, task, arg, q)) p.start() p.join(options.get('THREADS_TIMEOUT')) q.put('STOP') while True: el = q.get() if el == 'STOP': break results[el[0]] = el[1] return results isbnlib-3.10.14/isbnlib/dev/webquery.py000066400000000000000000000043431442216276400177330ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Base class to query a webservice and parse the result to py objects.""" import json import logging from time import sleep from time import time as timestamp from . import webservice from ._exceptions import DataNotFoundAtServiceError, ServiceIsDownError UA = 'isbnlib (gzip)' OUT_OF_SERVICE = 'Temporarily out of service' BOOK_NOT_FOUND = 'No results match your search' LOGGER = logging.getLogger(__name__) THROTTLING = 1 # pylint: disable=useless-object-inheritance class WEBQuery(object): """Base class to query a webservice and parse the result to py objects.""" T = {'id': timestamp()} # noqa def __init__(self, service_url, ua=UA, throttling=THROTTLING): """Initialize & call webservice.""" srv = service_url[8:20] last = WEBQuery.T[srv] if srv in WEBQuery.T else 0.0 wait = 0 if timestamp() - last > throttling else throttling sleep(wait) self.url = service_url self.data = webservice.query(service_url, ua) WEBQuery.T[srv] = timestamp() def check_data(self, data_checker=None): # pragma: no cover """Check the data & handle errors.""" if data_checker: return data_checker(self.data) if self.data == '{}': # noqa LOGGER.warning('DataNotFoundAtServiceError for %s', self.url) raise DataNotFoundAtServiceError(self.url) if BOOK_NOT_FOUND in self.data: LOGGER.warning('DataNotFoundAtServiceError for %s', self.url) raise DataNotFoundAtServiceError(self.url) if OUT_OF_SERVICE in self.data: LOGGER.critical('ServiceIsDownError for %s', self.url) raise ServiceIsDownError(self.url) return True def parse_data(self, parser=json.loads): """Parse the data (default JSON -> PY).""" if parser is None: # pragma: no cover return self.data return parser(self.data) # <-- data is now unicode def query( url, user_agent=UA, data_checker=None, parser=json.loads, throttling=THROTTLING, ): """Put call and return the data from the web service.""" wq = WEBQuery(url, user_agent, throttling) return wq.parse_data(parser) if wq.check_data(data_checker) else {} isbnlib-3.10.14/isbnlib/dev/webservice.py000066400000000000000000000100051442216276400202160ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Query web services.""" import gzip import logging from socket import timeout as sockettimeout from ..config import options from ._bouth23 import bstream, s from ._decorators import imcache from ._exceptions import ISBNLibHTTPError, ISBNLibURLError, ServiceIsDownError # pylint: disable=import-error # pylint: disable=wrong-import-order # pylint: disable=no-name-in-module try: # pragma: no cover from urllib.error import HTTPError, URLError from urllib.parse import urlencode from urllib.request import Request, urlopen except ImportError: # pragma: no cover from urllib import urlencode from urllib2 import HTTPError, Request, URLError, urlopen UA = 'isbnlib (gzip)' LOGGER = logging.getLogger(__name__) # pylint: disable=too-few-public-methods # pylint: disable=useless-object-inheritance class WEBService(object): """Class to query web services.""" def __init__(self, url, user_agent=UA, values=None, appheaders=None): """Initialize main properties.""" # TODO(use urllib.quote to the non-ascii part?) if not url.lower().startswith('http'): LOGGER.critical('Url (%s) not allowed!', url) raise ISBNLibURLError('Url (%s) not allowed!' % url) self._url = url # headers to accept gzipped content headers = {'Accept-Encoding': 'gzip', 'User-Agent': user_agent} # add more user provided headers if appheaders: # pragma: no cover headers.update(appheaders) # if 'data' it does a POST request (data must be urlencoded) data = urlencode(values).encode('utf8') if values else None self._request = Request(url, data, headers=headers) def response(self): """Check errors on response.""" # TODO(http 102) # How to handle "102 http's code"? # - urlopen doesn't catch a 102 code! # https://docs.python.org/3/howto/urllib2.html#error-codes try: response = urlopen( self._request, timeout=options.get('URLOPEN_TIMEOUT'), ) LOGGER.debug('Request headers:\n%s', self._request.header_items()) except HTTPError as e: # pragma: no cover LOGGER.critical( 'ISBNLibHTTPError for %s with code %s [%s]', self._url, e.code, e.msg, ) if e.code in (401, 403, 429): raise ISBNLibHTTPError('%s Are you making many requests?' % e.code) if e.code in (502, 504): raise ISBNLibHTTPError('%s Service temporarily unavailable!' % e.code) raise ISBNLibHTTPError('(%s) %s' % (e.code, e.msg)) except URLError as e: # pragma: no cover LOGGER.critical( 'ISBNLibURLError for %s with reason %s', self._url, e.reason, ) raise ISBNLibURLError(e.reason) except sockettimeout: # pragma: no cover LOGGER.critical( 'ServiceIsDownError for %s with reason %s', self._url, 'timeout', ) raise ServiceIsDownError('service timeout') return response if response else None def data(self): """Return the uncompressed data.""" res = self.response() LOGGER.debug('Response headers:\n%s', res.info()) if res.info().get('Content-Encoding') == 'gzip': buf = bstream(res.read()) f = gzip.GzipFile(fileobj=buf) data = f.read() else: # pragma: no cover data = res.read() return s(data) @imcache def query(url, user_agent=UA, values=None, appheaders=None): """Query to a web service.""" service = WEBService( url, user_agent=user_agent, values=values, appheaders=appheaders, ) data = service.data() LOGGER.debug('Raw data from service:\n%s', data) return data isbnlib-3.10.14/isbnlib/registry.py000066400000000000000000000065711442216276400171670ustar00rootroot00000000000000# -*- coding: utf-8 -*- """Registry for metadata services, formatters and cache.""" import logging from pkg_resources import iter_entry_points from . import NotValidDefaultFormatterError, NotValidDefaultServiceError from . import _goob as goob from . import _openl as openl from . import _wiki as wiki from ._imcache import IMCache from .config import options from .dev._fmt import _fmtbib LOGGER = logging.getLogger(__name__) # SERVICES services = { 'default': goob.query, 'goob': goob.query, 'openl': openl.query, 'wiki': wiki.query, } PROVIDERS = () def setdefaultservice(name): """Set the default service.""" global services services['default'] = services[name.lower()] if name != 'default' and name in services: services['default'] = services[name.lower()] else: LOGGER.critical('Wrong default service') raise NotValidDefaultServiceError(name) def add_service(name, query): # pragma: no cover """Add a new service to services.""" global services services[name.lower()] = query # FORMATTERS bibformatters = { 'default': lambda x: _fmtbib('labels', x), 'labels': lambda x: _fmtbib('labels', x), 'bibtex': lambda x: _fmtbib('bibtex', x), 'csl': lambda x: _fmtbib('csl', x), 'csv': lambda x: _fmtbib('csv', x), 'json': lambda x: _fmtbib('json', x), 'opf': lambda x: _fmtbib('opf', x), 'endnote': lambda x: _fmtbib('endnote', x), 'ris': lambda x: _fmtbib('ris', x), 'refworks': lambda x: _fmtbib('ris', x), 'msword': lambda x: _fmtbib('msword', x), } # pragma: no cover BIBFORMATS = () def setdefaultbibformatter(name): """Set the default formatter.""" global bibformatters if name != 'default' and name in bibformatters: bibformatters['default'] = bibformatters[name.lower()] else: LOGGER.critical('Wrong default bibformatter') raise NotValidDefaultFormatterError(name) def add_bibformatter(name, formatter): # pragma: no cover """Add a new formatter to formatters.""" global bibformatters bibformatters[name] = formatter.lower() # pylint: disable=broad-except def load_plugins(): # pragma: no cover """Load plugins with groups: isbnlib.metadata & isbnlib.formatters.""" # get metadata plugins from entry_points if options.get('LOAD_METADATA_PLUGINS', True): try: for entry in iter_entry_points(group='isbnlib.metadata'): add_service(entry.name, entry.load()) except Exception: LOGGER.critical('Some metadata plugins were not loaded!') global PROVIDERS _buf = list(services.keys()) _buf.remove('default') PROVIDERS = tuple(sorted(_buf)) # get formatters from entry_points if options.get('LOAD_FORMATTER_PLUGINS', True): try: for entry in iter_entry_points(group='isbnlib.formatters'): add_bibformatter(entry.name, entry.load()) except Exception: LOGGER.critical('Some formatters plugins were not loaded!') global BIBFORMATS _buf = list(bibformatters.keys()) _buf.remove('labels') _buf.remove('default') BIBFORMATS = tuple(sorted(_buf)) # load plugins on import load_plugins() del load_plugins # CACHE metadata_cache = IMCache() # should be an instance def set_cache(cache): # pragma: no cover """Set cache for metadata.""" global metadata_cache metadata_cache = cache isbnlib-3.10.14/isbnlib/test/000077500000000000000000000000001442216276400157135ustar00rootroot00000000000000isbnlib-3.10.14/isbnlib/test/__init__.py000066400000000000000000000000001442216276400200120ustar00rootroot00000000000000isbnlib-3.10.14/isbnlib/test/data4tests.py000066400000000000000000000032321442216276400203450ustar00rootroot00000000000000# -*- coding: utf-8 -*- ISBNs = r""" ISBN 9781849284677 qwe iuwer 9780312640583 kjhfds bh bh isbn 978-0312640583 bh bh isbn 978 031264058 3 bh bh isbn978 031264058 3 ISBN 0-330-28498-3 jhjhISBN 1-58182-008-9 ISBN 2-226-05257-7 ISBN 3-7965-1900-8 ISBN 4-19-830127-1 ISBN 5-85270-001-0 ISBN 978-600-119-125-1 ISBN 978-601-7151-13-3 ISBN 978-602-8328-22-7 ISBN 978-603-500-045-1 ISBN 605-384-057-2 ISBN 978-606-8126-35-7 ISBN 978-607-455-035-1 ISBN 978-608-203-023-4 ISBN 978-612-45165-9-7 ISBN 978-614-404-018-8 ISBN 978-615-5014-99-4 ISBN 7-301-10299-2 ISBN 80-85983-44-3 ISBN 81-7215-399-6 ISBN 82-530-0983-6 ISBN 83-08-01587-5 ISBN 84-86546-08-7 ISBN 85-7531-015-1 ISBN 86-341-0846-5 ISBN 87-595-2277-1 ISBN 88-04-47328-2 ISBN 90-5691-187-2 ISBN 91-1-811692-2 ISBN 92-67-10370-9 ISBN 93-8011-236-7 ISBN 94-414-0063-3 ISBN 950-04-0442-7 ISBN 951-0-11369-7 ISBN 952-471-294-6 ISBN 953-157-105-8 ISBN 954-430-603-X ISBN 955-20-3051-X ISBN 956-7291-48-9 ISBN 957-01-7429-3 ISBN 958-04-6278-X ISBN 959-10-0363-3 ISBN 961-6403-23-0 ISBN 962-04-0195-6 ISBN 963-7971-51-3 ISBN 964-6194-70-2 ISBN 965-359-002-2 ISBN 966-95440-5-X ISBN 967-978-753-2 ISBN 968-6031-02-2 ISBN 969-031-02-2 ISBN 970-20-0242-7 ISBN 971-8845-10-0 ISBN 972-37-0274-6 ISBN 973-43-0179-9 ISBN 974-85854-7-6 ISBN 975-293-381-5 ISBN 976-640-140-3 ISBN 977-734-520-8 ISBN 978-37186-2-2 ISBN 979-553-483-1 ISBN 980-01-0194-2 ISBN 981-3018-39-9 ISBN 982-301-001-3 ISBN 983-52-0157-9 ISBN 984-458-089-7 ISBN 986-417-191-7 ISBN 987-98184-2-3 ISBN 978-988-00-3827-3 ISBN 978-9928400529 ISBN 978-9929801646 ISBN 978-9930943106 ISBN 978-9933101473 ISBN 978-9934015960 ISBN 978-99937-1-056-1 ISBN 978-99965-2-047-1 """ # flake8: noqa isbnlib-3.10.14/isbnlib/test/idle_classify.py000066400000000000000000000032741442216276400211050ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa # pylint: skip-file """tests for classifiers.""" from random import randint from time import sleep import pytest from .._oclc import query_classify as query pytestmark = pytest.mark.skip("OCLC doesn't allow so many tests for now!") # this is a slow service q1 = query('9781786330444') or {} sleep(randint(10, 30)) q2 = query('9780425284629') or {} sleep(randint(10, 30)) def test_query(): """Test the query of classifiers (oclc.org) with 'low level' queries.""" assert (len(repr(query('9782253112105'))) > 10) == True assert (len(repr(q1)) > 10) == True assert (len(repr(q2)) > 10) == True sleep(randint(10, 30)) def test_query_no_data(): """Test the query of classifiers (oclc.org) with 'low level' queries (no data).""" assert (len(repr(query('9781849692341'))) == 2) == True sleep(randint(10, 30)) assert (len(repr(query('9781849692343'))) == 2) == True def test_query_exists_ddc(): """Test exists 'DDC'.""" assert (len(repr(q1['ddc'])) > 2) == True assert (len(repr(q2['ddc'])) > 2) == True def test_query_exists_lcc(): """Test exists 'LCC'.""" assert (len(repr(q1['lcc'])) > 2) == True assert (len(repr(q2['lcc'])) > 2) == True def test_query_fast(): """Test exists 'fast' classifiers.""" assert (len(repr(q1['fast'])) > 7) == True assert (len(repr(q2['fast'])) > 7) == True def test_query_owi(): """Test exists 'owi' classifiers.""" assert (len(repr(q1['owi'])) > 5) == True assert (len(repr(q2['owi'])) > 5) == True def test_query_oclc(): """Test exists 'oclc' classifiers.""" assert (len(repr(q1['oclc'])) > 7) == True assert (len(repr(q2['oclc'])) > 7) == True isbnlib-3.10.14/isbnlib/test/test_cache.py000066400000000000000000000014641442216276400203740ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa # pylint: skip-file """Tests for the cache.""" from .._imcache import IMCache cache = IMCache() def setup_module(): cache['123'] = 'abc' # <-- set def teardown_module(): del cache['123'] def test_cache_set(): """Test 'cache' operations (set).""" cache['567'] = 'jkl' assert ('jkl' == cache['567']) == True def test_cache_get(): """Test 'cache' operations (get).""" assert cache.get('123') == cache['123'] assert cache.get('000') == None assert cache.get('000', '') == '' def test_cache_contains(): """Test 'cache' operations (contains).""" assert ('123' in cache) == True def test_cache_del(): """Test 'cache' operations (del).""" cache['567'] = 'jkl' del cache['567'] assert ('567' not in cache) == True isbnlib-3.10.14/isbnlib/test/test_cache_decorator.py000066400000000000000000000020341442216276400224300ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa # pylint: skip-file """Tests for the @cache.""" import pytest from .. import classify, meta, registry # TODO add more tests for other operations cache = registry.metadata_cache pytestmark = pytest.mark.network def setup_module(): meta('9780375869020') # <-- set # classify('9781118241257') # <-- set def teardown_module(): del cache["query('9780375869020', 'default'){}"] def test_cache_meta(): """Test '@cache' meta.""" assert ( (len(repr(cache.get("query('9780375869020', 'default'){}"))) > 100) == True) assert ( len(repr(cache.get("query('9780375869020', 'default'){}"))) == len(repr(cache["query('9780375869020', 'default'){}"]))) # def test_cache_classify(): # """Test '@cache' classify.""" # assert_equals(len(repr(cache.get("query_classify('9781118241257',){}"))) > 5, True) # assert_equals( # len(repr(cache.get("query_classify('9781118241257',){}"))), # len(repr(cache["query_classify('9781118241257',){}"])), # ) isbnlib-3.10.14/isbnlib/test/test_core.py000066400000000000000000000150371442216276400202620ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa # pylint: skip-file from .._core import ( EAN13, _check_structure10, _check_structure13, canonical, check_digit10, check_digit13, clean, ean13, get_canonical_isbn, get_isbnlike, is_isbn10, is_isbn13, notisbn, to_isbn10, to_isbn13, ) from .data4tests import ISBNs # tests def test_check_digit10(): """Test check digit algo for ISBN-10.""" assert check_digit10('082649752') == '7' assert check_digit10('585270001') == '0' assert check_digit10('08264975X') == '' assert check_digit10('08264975') == '' def test_check_digit13(): """Test check digit algo for ISBN-13.""" assert check_digit13('978082649752') == '9' assert check_digit13('97808264975') == '' assert check_digit13('97808264975X') == '' def test__check_structure10(): """Test structure detection for ISBN-10.""" assert _check_structure10('0826497527') == True assert _check_structure10('0826497X27') == True # isbnlike! assert _check_structure10('0826497XI7') == False def test__check_structure13(): """Test structure detection for ISBN-13.""" assert _check_structure13('9780826497529') == True assert _check_structure13('978082649752X') == False def test_is_isbn10(): """Test detection and validation for ISBN-10.""" assert is_isbn10('0826497527') == True assert is_isbn10('isbn 0-8264-9752-7') == True assert is_isbn10('0826497520') == False assert is_isbn10('954430603X') == True def test_is_isbn13(): """Test detection and validation for ISBN-13.""" assert is_isbn13('9780826497529') == True assert is_isbn13('9791090636071') == True assert is_isbn13('isbn 979-10-90636-07-1') == True assert is_isbn13('9780826497520') == False assert is_isbn13('9700000000000') == False assert is_isbn13('9000000000000') == False assert is_isbn13('9710000000000') == False def test_to_isbn10(): """Test transformation of ISBN to ISBN-10.""" assert to_isbn10('9780826497529') == '0826497527' assert to_isbn10('0826497527') == '0826497527' assert to_isbn10('9780826497520') == '' # ISBN13 not valid assert to_isbn10('9790826497529') == '' assert to_isbn10('97808264975X3') == '' assert to_isbn10('978-826497') == '' # (bug #14) assert to_isbn10('isbn 0-8264-9752-7') == '0826497527' assert to_isbn10('isbn 979-10-90636-07-1') == '' assert to_isbn10('isbn 978-0-8264-9752-9') == '0826497527' assert to_isbn10('asdadv isbn 978-0-8264-9752-9') == '0826497527' def test_to_isbn13(): """Test transformation of ISBN to ISBN-13.""" assert to_isbn13('0826497527') == '9780826497529' assert to_isbn13('9780826497529') == '9780826497529' assert to_isbn13('0826497520') == '' # ISBN10 not valid assert to_isbn13('08X6497527') == '' assert to_isbn13('91-43-01019-9') == '9789143010190' # (bug #14) assert to_isbn13('isbn 91-43-01019-9') == '9789143010190' assert to_isbn13('asd isbn 979-10-90636-07-1 blabla') == '9791090636071' def test_clean(): """Test the cleaning of ISBN-like strings.""" assert clean(' 978.0826.497529') == '9780826497529' assert clean('ISBN: 9791090636071') == 'ISBN 9791090636071' assert clean('978,0826497520') == '9780826497520' def test_notisbn(): """Test the impossibility of extracting valid ISBN from ISBN-like strings.""" assert notisbn('0826497527') == False assert notisbn('0826497520') == True assert notisbn('9780826497529', level='strict') == False assert notisbn('9426497529', level='strict') == True assert notisbn('978082649752', level='strict') == True assert notisbn('978082649752', level='loose') == True assert notisbn('9780826400001', level='loose') == False assert notisbn('9780826400001', level='strict') == True assert notisbn('9780826400001', level='badlevel') == None assert notisbn('978 9426497529') == True assert notisbn('9789426497529') == True assert notisbn('979 10 9063607 1') == False assert notisbn('9780826497520') == True def test_get_isbnlike(): """Test the extraction of ISBN-like strings.""" assert len(get_isbnlike(ISBNs)) == 79 assert len(get_isbnlike(ISBNs, 'normal')) == 79 assert len(get_isbnlike(ISBNs, 'strict')) == 69 assert len(get_isbnlike(ISBNs, 'loose')) == 81 assert get_isbnlike(ISBNs, 'e') == [] # issue 60 and 103 # TODO add test... # issue 107 assert get_isbnlike('978-0-9790173-4-6', 'normal')[0] == '978-0-9790173-4-6' assert get_isbnlike('978-9788461784', 'normal')[0] == '978-9788461784' def test_get_canonical_isbn(): """Test the extraction of canonical ISBN from ISBN-like string.""" assert get_canonical_isbn('0826497527', output='bouth') == '0826497527' assert get_canonical_isbn('0826497527') == '0826497527' assert get_canonical_isbn('0826497527', output='isbn10') == '0826497527' assert get_canonical_isbn('0826497527', output='isbn13') == '9780826497529' assert ( get_canonical_isbn('ISBN 0826497527', output='isbn13') == '9780826497529') assert get_canonical_isbn('ISBN 0826497527', output='NOOPTION') == '' assert get_canonical_isbn('0826497520') == '' assert get_canonical_isbn('9780826497529') == '9780826497529' assert get_canonical_isbn('9780826497520') == '' assert get_canonical_isbn('OSX 9780826497529.pdf') == '9780826497529' def test_canonical(): """Test the extraction of 'only numbers and X' from ISBN-like string.""" assert canonical('ISBN 9789720404427') == '9789720404427' assert canonical('ISBN-9780826497529') == '9780826497529' assert canonical('ISBN9780826497529') == '9780826497529' assert canonical('isbn9780826497529') == '9780826497529' assert canonical('isbn 0826497527') == '0826497527' assert canonical('954430603x') == '954430603X' assert canonical('95443060x3') == '' assert canonical('0000000000') == '' assert canonical('000000000X') == '' assert canonical('0000000000000') == '' assert canonical('0000000') == '' assert canonical('') == '' def test_ean13(): """Test the extraction and validation of EAN13 from ISBN-like string.""" assert ean13('ISBN 9789720404427') == '' assert ean13('ISBN 9789720404428') == '9789720404428' assert EAN13('ISBN-9780826497529') == '9780826497529' assert ean13('ISBN9780826497529') == '9780826497529' assert EAN13('isbn9780826497529') == '9780826497529' assert EAN13('isbn 0826497527') == '9780826497529' assert ean13('9700000000000') == '' assert EAN13('9000000000000') == '' assert EAN13('9710000000000') == '' isbnlib-3.10.14/isbnlib/test/test_data.py000066400000000000000000000044161442216276400202420ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa # pylint: skip-file """tests""" import pytest from ..dev import Metadata, stdmeta from ..dev._bouth23 import u def test_stdmeta(): """Test the transformation of raw records into standard metadata.""" # test stdmeta from data r = { 'ISBN-13': u('9780123456789 '), 'Title': u('Bla. Bla /Title .'), 'Publisher': u(''), 'Year': u('2000'), 'Language': u('en'), 'Authors': [u('author1. mba'), u('author2 ')], } R = { 'ISBN-13': u('9780123456789'), 'Title': u('Bla. Bla /Title'), 'Publisher': u(''), 'Year': u('2000'), 'Language': u('en'), 'Authors': [u('author1. mba'), u('author2')], } A = { 'ISBN-13': u('9780123456789 '), 'Title': b'Bla. Bla /Title .', 'Publisher': u(''), 'Year': b'2000', 'Language': u('en'), 'Authors': [u('author1. mba'), u('author2 ')], } B = { 'ISBN-13': u('9780123456789'), 'Title': u('Bla. Bla /Title .'), 'Publisher': u(''), 'Year': u('2000'), 'Language': u('en'), 'Authors': u('author1'), } assert stdmeta(r) == R assert stdmeta(R) == R with pytest.raises(Exception): stdmeta(A) with pytest.raises(Exception): stdmeta(B) def test_metaclass(): """Test the creation of a Metadata class from raw records.""" R = { 'ISBN-13': u('9780123456789'), 'Title': u('Bla. Bla /Title'), 'Publisher': u(''), 'Year': u('2000'), 'Language': u('en'), 'Authors': [u('author1. mba'), u('author2')], } dt = Metadata(R) assert dt.value == R def test_metrge(): """Test the merging of records.""" R = { 'ISBN-13': u('9780123456789'), 'Title': u('Bla. Bla /Title'), 'Publisher': u(''), 'Year': u('2000'), 'Language': u('en'), 'Authors': [u('author1. mba'), u('author2')], } T = { 'ISBN-13': u('9780123456789'), 'Title': u('Bla. Bla /Title'), 'Publisher': u('Pub House'), 'Year': u('2000'), 'Language': u('en'), 'Authors': [u('author1. mba'), u('author2')], } dt = Metadata(R) dt.merge(T) assert dt.value == T isbnlib-3.10.14/isbnlib/test/test_editions.py000066400000000000000000000034271442216276400211500ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa # pylint: skip-file try: from time import process_time as timer except: # for py2 import timeit timer = timeit.default_timer import pytest from .._exceptions import NotRecognizedServiceError, NotValidISBNError from .._ext import editions @pytest.mark.network def test_editions_openl(): """Test the 'openl editions' service.""" assert (len(editions('9780151446476', service='openl')) >= 1) == True @pytest.mark.network def test_editions_thingl(): """Test the 'thingl editions' service.""" assert (len(editions('9780151446476', service='thingl')) > 2) == True @pytest.mark.network def test_editions_wiki(): """Test the 'wiki editions' service.""" assert (len(editions('9780440414803', service='wiki')) > 5) == True @pytest.mark.network def test_editions_any(): """Test the 'any editions' service.""" assert (len(editions('9780151446476', service='any')) > 1) == True @pytest.mark.network def test_editions_merge(): """Test the 'merge editions' service.""" assert (len(editions('9780151446476', service='merge')) > 2) == True def test_editions_NotValidISBNError(): """Test the 'editions' service error detection (NotValidISBNError).""" with pytest.raises(NotValidISBNError): editions('978') def test_editions_NotRecognizedServiceError(): """Test the 'editions' service error detection (NotRecognizedServiceError).""" with pytest.raises(NotRecognizedServiceError): editions('9780156001311', service='xxx') @pytest.mark.network def test_cache(): """Test the 'editions' cache.""" t = timer() assert (len(editions('9780151446476', service='merge')) > 19) == True elapsed_time = timer() - t millis = int(elapsed_time * 1000) assert (millis < 100) == True isbnlib-3.10.14/isbnlib/test/test_exceptions.py000066400000000000000000000014211442216276400215030ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa # pylint: skip-file """tests for Exceptions.""" import pytest from .. import ISBNLibException from .._ext import meta def test_catchall(): """Test the 'catch all' exception (ISBNLibException).""" with pytest.raises(Exception): meta('9781849692343', 'goob', None) def f1(): try: meta('9781849692343') except ISBNLibException as ex: return str(ex.message) assert f1() == '(9781849692343) is not a valid ISBN' def f2(): try: meta('9789720049612', 'xxx') except ISBNLibException as ex: return str(ex.message) assert f2() == '(xxx) is not a recognized service' # NOTE the tests for other Exceptions are spread in the other tests isbnlib-3.10.14/isbnlib/test/test_ext.py000066400000000000000000000044671442216276400201370ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa # pylint: skip-file import pytest from .._ext import cover, desc, doi, isbn_from_words, mask # tests def test_mask(): """Test 'mask' command.""" assert mask('5852700010') == '5-85270-001-0' assert mask('0330284983') == '0-330-28498-3' assert mask('3796519008') == '3-7965-1900-8' assert mask('4198301271') == '4-19-830127-1' assert mask('2226052577') == '2-226-05257-7' assert mask('6053840572') == '605-384-057-2' assert mask('7301102992') == '7-301-10299-2' assert mask('8085983443') == '80-85983-44-3' assert mask('9056911872') == '90-5691-187-2' assert mask('9500404427') == '950-04-0442-7' assert mask('9800101942') == '980-01-0194-2' assert mask('9813018399') == '981-3018-39-9' assert mask('9786001191251') == '978-600-119-125-1' assert mask('9780321534965') == '978-0-321-53496-5' assert mask('9781590593561') == '978-1-59059-356-1' assert mask('9789993075899') == '978-99930-75-89-9' assert mask('0-330284983') == '0-330-28498-3' assert mask('9791090636071') == '979-10-90636-07-1' assert mask('9798847781275') == '979-8-8477-8127-5' # <-- issue #114 assert mask('9786131796364') == '978-613-1-79636-4' # <-- prefix with 1 rule assert mask('isbn 979-10-90636-07-1') == '979-10-90636-07-1' assert mask('') == '' with pytest.raises(Exception): mask('9786') with pytest.raises(Exception): mask('0000000000000') @pytest.mark.network def test_isbn_from_words(): """Test 'isbn_from_words' command.""" assert len(isbn_from_words('old men and sea')) == 13 def test_doi(): """Test 'doi' command.""" assert doi('9780195132861') == '10.978.019/5132861' assert doi('9780321534965') == '10.978.0321/534965' assert doi('9791090636071') == '10.979.1090636/071' @pytest.mark.network def test_desc(): """Test 'desc' command.""" assert (len(desc('9780156001311')) > 10) == True assert desc('9780000000000') == '' @pytest.mark.network def test_cover(): """Test 'cover' command.""" assert (len(repr(cover('9780156001311'))) > 50) == True assert cover('9780000000000') == {} # <-- invalid ISBN assert (len(repr(cover('9781408835029'))) > 50) == True assert ( (len(repr(cover('9789727576807'))) < 50) == True) # <-- no image of any size isbnlib-3.10.14/isbnlib/test/test_files.py000066400000000000000000000041671442216276400204360ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa # pylint: skip-file """ tests """ import locale import os from ..dev._files import File, cwdfiles WINDOWS = os.name == 'nt' ENCODING = locale.getpreferredencoding() if ENCODING == 'UTF-8': TESTFILE = './ç-deleteme.pdf' if WINDOWS else '/tmp/海明威-deleteme.pdf' NEW_BASENAME = 'ç-deleteme-PLEASE.pdf' if WINDOWS else '海明威-deleteme-PLEASE.pdf' else: print( "Your default locale encoding (%s) doesn't allow unicode filenames!" % ENCODING, ) TESTFILE = './deleteme.pdf' NEW_BASENAME = 'deleteme-PLEASE.pdf' def setup_module(): with open(TESTFILE, 'w') as f: f.write('ooo') os.chdir(os.path.dirname(TESTFILE)) def teardown_module(): os.remove(os.path.join(os.path.dirname(TESTFILE), NEW_BASENAME)) def test_isfile(): """Test if a path is a file.""" f = File(TESTFILE) assert f.isfile(TESTFILE) == True def test_exists(): """Test if a path is a file or a directory.""" f = File(TESTFILE) assert f.exists(TESTFILE) == True def test_validate(): """Test if a string is a valid filename for 'ren' command.""" f = File(TESTFILE) assert f.validate('basename.pdf') == True assert f.validate('as/basename.pdf') == False assert f.validate('.basename.pdf') == True assert f.validate('.basename') == False assert f.validate('') == False def test_mkwinsafe(): """Test if a string is a valid basename in Windows.""" f = File(TESTFILE) assert f.mkwinsafe('Açtr: ') == 'Açtr' assert f.mkwinsafe('as/tiõ') == 'astiõ' assert f.mkwinsafe('file ""name?') == 'file name' assert f.mkwinsafe('file ""name?', space='_') == 'file_name' assert f.mkwinsafe('file name ') == 'file name' def test_baserename(): """Test the rename of a basename.""" f = File(TESTFILE) assert f.baserename(NEW_BASENAME) == True assert f.baserename(NEW_BASENAME) == True def test_cwdfiles(): """Test the renaming of files in cwd.""" assert (NEW_BASENAME in cwdfiles()) == True assert (NEW_BASENAME in cwdfiles('*.pdf')) == True assert (NEW_BASENAME in cwdfiles('*.txt')) == False isbnlib-3.10.14/isbnlib/test/test_fmt.py000066400000000000000000000016111442216276400201110ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa # pylint: skip-file """ tests """ from ..dev._bouth23 import u from ..dev._fmt import _fmtbib canonical = { 'ISBN-13': u('9780123456789'), 'Title': u('A book about nothing'), 'Publisher': u('No Paper Press'), 'Year': u('2000'), 'Language': u('en'), 'Authors': [u('John Smith'), u('José Silva')], } def test_fmtbib(): """Test the formatting into several bibliographic formats.""" assert len(_fmtbib('bibtex', canonical)) == 182 assert len(_fmtbib('labels', canonical)) == 158 assert len(_fmtbib('endnote', canonical)) == 103 assert len(_fmtbib('msword', canonical)) == 485 assert len(_fmtbib('json', canonical)) == 229 assert len(_fmtbib('csl', canonical)) == 253 assert len(_fmtbib('csv', canonical)) == 94 assert len(_fmtbib('ris', canonical)) == 130 assert len(_fmtbib('opf', canonical)) == 861 isbnlib-3.10.14/isbnlib/test/test_goom.py000066400000000000000000000005541442216276400202710ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa # pylint: skip-file """ tests """ import pytest from .. import _goom as goom pytestmark = pytest.mark.network def test_goom(): """Test the Google's Multiple Books service.""" assert (len(repr(goom.query('the old man and the sea'))) > 500) == True assert (len(repr(goom.query('plato republic'))) > 500) == True isbnlib-3.10.14/isbnlib/test/test_helpers.py000066400000000000000000000030631442216276400207700ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa # pylint: skip-file """ tests """ from ..dev._helpers import cutoff_tokens, fake_isbn, last_first, parse_placeholders def test_last_first(): """Test the parsing of author's name into (Surname, First Name).""" assert ( last_first('Surname, First Name') == {'last': 'Surname', 'first': 'First Name'}) assert ( last_first('First Name Surname') == {'last': 'Surname', 'first': 'First Name'}) assert ( last_first('Surname1, First1 and Sur2, First2') == {'last': 'Surname1', 'first': 'First1 and Sur2, First2'}) def test_cutoff_tokens(): """Test the 'cutoff_tokens' function.""" assert cutoff_tokens(['1', '23', '456'], 3) == ['1', '23'] def test_parse_placeholders(): """Test the parsing of placeholders.""" assert parse_placeholders('{isbn}_akaj_{name}') == ['{isbn}', '{name}'] def test_fake_isbn(): """Test the 'fake_isbn' function.""" assert fake_isbn(' Hello?? Wer, ! ksDf: asdf. ; ') == '1111006407537' assert ( fake_isbn(' Hello?? Wer, ! ksDf: asdf. ; ', author='') == '1108449680873') assert ( fake_isbn(' Hello?? Wer, ! ksDf: asdf. ; ', author=' ') == '1108449680873') assert ( fake_isbn(' Hello?? Wer, ! ksDf: asdf. ; ', author='', publisher='') == '1181593982422') assert ( fake_isbn(' Hello?? Wer, ! ksDf: asdf. ; ', author='a', publisher='K') == '1895031085488') assert ( fake_isbn(' Hello?? Wer, ! ksDf: asdf. ; ', author='A', publisher='k') == '1895031085488') isbnlib-3.10.14/isbnlib/test/test_info.py000066400000000000000000000022211442216276400202540ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa # pylint: skip-file import pytest from .._ext import info from .._infogroup import infogroup # tests def test_infogroup(): """Test 'infogroup' language/country function.""" assert infogroup('9789727576807') == 'Portugal' assert infogroup('978-972-757-680-7') == 'Portugal' assert infogroup('7500117019') == "China, People's Republic" assert infogroup('7-5001-1701-9') == "China, People's Republic" assert infogroup('9524712946') == 'Finland' assert infogroup('0330284983') == 'English language' assert infogroup('3796519008') == 'German language' with pytest.raises(Exception): infogroup('92xxxxxxxxxxx') with pytest.raises(Exception): infogroup('') assert infogroup('9791090636071') == 'France' assert infogroup('9786131796364') == 'Mauritius' assert infogroup('9789992158104') == 'Qatar' def test_ext_info(): """Test 'info' language/country function.""" assert info('9524712946') == 'Finland' with pytest.raises(Exception): info('') def test_ext_info(): """Test 'info' not issued ISBN.""" assert info('9789999999991') == '' isbnlib-3.10.14/isbnlib/test/test_isbn.py000066400000000000000000000022201442216276400202530ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa # pylint: skip-file """tests""" import pytest from .._isbn import Isbn isbn=Isbn('9781250158062') def test_ean13(): """Test the 'Isbn class' for ean13.""" assert isbn.ean13 == '9781250158062' def test_isbn13(): """Test the 'Isbn class' for isbn13.""" assert isbn.isbn13 == '978-1-250-15806-2' def test_isbn10(): """Test the 'Isbn class' for isbn10.""" assert isbn.isbn10 == '1-250-15806-0' def test_doi(): """Test the 'Isbn class' for doi.""" assert isbn.doi == '10.978.1250/158062' def test_issued(): """Test the 'Isbn class' for 'issued'.""" assert isbn.issued == True isbn2=Isbn('9786610326266') assert isbn2.issued == False def test_info(): """Test the 'Isbn class' for 'info'.""" assert isbn.info == 'English language' def test_errors(): """Test the 'Isbn class' for 'bad isbn'.""" with pytest.raises(Exception): Isbn('781250158062') def test_str(): """Test the 'Isbn class' for 'str'.""" assert (len(str(isbn)) > 20) == True def test_repr(): """Test the 'Isbn class' for 'repr'.""" assert (len(repr(isbn)) > 20) == True isbnlib-3.10.14/isbnlib/test/test_metadata.py000066400000000000000000000026071442216276400211110ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa # pylint: skip-file """tests for metadata.""" from random import randrange import pytest from .._ext import meta from .._metadata import query pytestmark = pytest.mark.network def test_query(): """Test the query of metadata with 'low level' queries.""" # test query from metadata with pytest.raises(Exception): query('9781849692341', 'goob') with pytest.raises(Exception): query('9781849692343', 'goob') # assert_equals(query('9789934015960', 'goob'), {}) assert (len(repr(query('9780321534965'))) > 100) == True assert (len(repr(query('9780321534965', 'goob'))) > 100) == True # assert_equals(len(repr(query('9789934015960'))) > 100, True) assert (len(repr(query(u'9781118241257'))) > 100) == True with pytest.raises(Exception): query('9780000000', 'goob') with pytest.raises(Exception): query(randrange(0, 1000000), 'goob') def test_ext_meta(): """Test the query of metadata with 'high level' meta function.""" # test meta from core assert (len(repr(meta('9780321534965', 'goob'))) > 100) == True assert (len(repr(meta('9780321534965'))) > 100) == True with pytest.raises(Exception): meta('9780000000', 'goob') with pytest.raises(Exception): meta(randrange(0, 1000000), 'goob') with pytest.raises(Exception): meta('9781849692343', 'goob') isbnlib-3.10.14/isbnlib/test/test_openl.py000066400000000000000000000006001442216276400204350ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa # pylint: skip-file """ tests """ import pytest from .._metadata import query pytestmark = pytest.mark.network def test_query(): """Test 'openl' metadata service.""" # test query from metadata assert (len(repr(query('9780195132861', 'openl'))) > 140) == True assert (len(repr(query('9780156001311', 'openl'))) > 140) == True isbnlib-3.10.14/isbnlib/test/test_registry.py000066400000000000000000000014521442216276400211760ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa # pylint: skip-file import pytest from ..registry import setdefaultbibformatter, setdefaultservice # tests def test_setdefaultbibformatter(): """Test setdefaultbibformatter.""" assert setdefaultbibformatter('json') == None with pytest.raises(Exception): setdefaultbibformatter('default') with pytest.raises(Exception): setdefaultbibformatter('') with pytest.raises(Exception): setdefaultbibformatter('xxx') def test_setdefaultservice(): """Test setdefaultservice.""" assert setdefaultservice('goob') == None with pytest.raises(Exception): setdefaultservice('default') with pytest.raises(Exception): setdefaultservice('') with pytest.raises(Exception): setdefaultservice('xxx') isbnlib-3.10.14/isbnlib/test/test_rename.py000066400000000000000000000050721442216276400205770ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa # pylint: skip-file """ tests """ import locale import os import pytest from .._ext import ren from ..dev._bouth23 import b2u3 from ..dev.helpers import cwdfiles pytestmark = pytest.mark.network WINDOWS = os.name == 'nt' ENCODING = locale.getpreferredencoding() if ENCODING != 'UTF-8': print( "Your default locale encoding (%s) doesn't allow unicode filenames!" % ENCODING, ) print('=> Some tests could fail.') TESTFILE_1 = './ç-deleteme.pdf' if WINDOWS else '/tmp/ç-deleteme.pdf' TESTFILE_2 = './ç-deleteme-PLEASE.pdf' if WINDOWS else '/tmp/ç-deleteme-PLEASE.pdf' # F1 = '9780321534965.pdf' # F1 = '9780872203495.pdf' F1 = '9780198520115.pdf' F2 = '9781597499644.pdf' F3 = '9781852330729.pdf' F4 = '9787500117018.pdf' F5 = '9789727576807.pdf' # issue #60 (related with issue #107) F6 = 'Campos2011_Emergências obstétricas_978-9727576807.pdf' # F7 = 'Knuth2008_The Art Of Computer Programming_9780321534965.pdf' # F7a = 'Knuth2008_Introduction To Combinatorial Algorithms And Boolean Functions_9780321534965.pdf' # F7 = 'Plato1997_Complete Works_9780872203495.pdf' # same as F1 F7 = 'Dirac1981_The Principles Of Quantum Mechanics_9780198520115.pdf' # same as F1 F8 = 'Man2001_Genetic Algorithms Concepts And Designs_9781852330729.pdf' F9 = "O'Connor2012_Violent Python A Cookbook for Hackers, Forensic Analysts, Penetra_9781597499644.pdf" F10 = '海明威2007_Lao ren yu hai_9787500117018.pdf' F11 = 'myfile.pdf' FISBN = [F1, F2, F3, F4, F5] FFT = [F6, F7, F8, F9, F10] FILES = FISBN + FFT + [F11] def create_files(files): os.chdir(os.path.dirname(TESTFILE_1)) for fn in files: try: with open(fn, 'w') as f: f.write(b2u3('ooo') + b2u3(fn)) except UnicodeEncodeError: print( "Your default locale (%s) doesn't allow non-ascii filenames!" % locale.CODESET, ) def delete_files(fnpatt): os.chdir(os.path.dirname(TESTFILE_1)) for fn in cwdfiles(fnpatt): os.remove(fn) def setup_module(): # create_files([u(TESTFILE_1), u(TESTFILE_2)]) os.chdir(os.path.dirname(TESTFILE_1)) # create_files(FISBN + [F11]) create_files([F1]) def teardown_module(): delete_files('*.pdf') def test_ren(): """Test 'high level' ren function.""" ren(F1) assert (F7 in cwdfiles('*.pdf')) == True # assert F7 in cwdfiles("*.pdf") or F7a in cwdfiles("*.pdf") is True # create_files([F5]) # ren(F5) # assert 'Campos2011_Emergências obstétricas_9789727576807.pdf' in cwdfiles("*.pdf") is True isbnlib-3.10.14/isbnlib/test/test_speed.py000066400000000000000000000015311442216276400204240ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa # pylint: skip-file """Crude Timer for 'import isbnlib'.""" import sys import time def test_speed_isbnlib(): """Test import speed of 'isbnlib'.""" if sys.version < '3': return True t = time.process_time() import isbnlib elapsed_time = time.process_time() - t millis = int(elapsed_time * 1000) print('(isbnlib) {} milliseconds < 100 milliseconds'.format(millis)) assert millis < 100 isbnlib.__version__ def test_speed_registry(): """Test import speed of 'registry'.""" if sys.version < '3': return True t = time.process_time() from isbnlib import registry elapsed_time = time.process_time() - t millis = int(elapsed_time * 1000) print('(registry) {} milliseconds < 135 milliseconds'.format(millis)) assert millis < 135 registry.BIBFORMATS isbnlib-3.10.14/isbnlib/test/test_vias.py000066400000000000000000000024011442216276400202630ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa # pylint: skip-file """ tests """ import os import platform from ..dev import vias def task1(arg): return arg * arg def task2(arg): return arg + arg def test_vias_serial(): """Test 'vias' (serial).""" named_tasks = (('task1', task1), ('task2', task2)) results = vias.serial(named_tasks, 5) data1 = results.get('task1', 0) data2 = results.get('task2', 0) data = data1 + data2 assert data == 5 * 5 + 5 + 5 def test_vias_parallel(): """Test 'vias' (parallel).""" named_tasks = (('task1', task1), ('task2', task2)) results = vias.parallel(named_tasks, 5) data1 = results.get('task1', 0) data2 = results.get('task2', 0) data = data1 + data2 assert data == 5 * 5 + 5 + 5 def test_vias_multi(): """Test 'vias' (multi).""" # Is NOT allowed in Windows & macOS! if os.getenv('GITHUB_OS', '') in ('windows', 'macOS'): assert True return if platform.system() in ('Windows', 'Darwin'): assert True return named_tasks = (('task1', task1), ('task2', task2)) results = vias.multi(named_tasks, 5) data1 = results.get('task1', 0) data2 = results.get('task2', 0) data = data1 + data2 assert data == 5 * 5 + 5 + 5 isbnlib-3.10.14/isbnlib/test/test_webservice.py000066400000000000000000000005501442216276400214620ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa # pylint: skip-file """ tests """ import pytest from ..dev.webservice import query as wsquery pytestmark = pytest.mark.network def test_webservice(): """Test that values can be passed to a WebService query.""" assert ( (len(repr(wsquery('http://example.org', values={'some': 'values'}))) > 0) == True) isbnlib-3.10.14/isbnlib/test/test_wiki.py000066400000000000000000000010361442216276400202670ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa # pylint: skip-file """ tests for wikipedia.""" import pytest from .._metadata import query pytestmark = pytest.mark.network def test_query(): """Test 'wiki' metadata service.""" # test query from metadata assert (len(repr(query('9780195132861', 'wiki'))) > 100) == True assert (len(repr(query('9780375869020', 'wiki'))) > 100) == True data = query('9780596003302', 'wiki') assert (len(repr(data['Authors'])) > 5) == True assert (len(repr(data['Publisher'])) > 5) == True isbnlib-3.10.14/isbnlib/test/test_words.py000066400000000000000000000006301442216276400204610ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa # pylint: skip-file """ tests """ import pytest from .. import _gwords as words pytestmark = pytest.mark.network def test_words(): """Test 'isbn_from_words' function.""" assert len(words.goos('the old man and the sea')) == 13 # assert len(words.goos('Pessoa Desassossego')) == 13 # assert words.goos('-ISBN -isbn') in ('9781364200329', None) == True isbnlib-3.10.14/release.md000066400000000000000000000002021442216276400152460ustar00rootroot00000000000000**PYPI**: https://pypi.org/project/isbnlib/ ## What's new? 1. Drop support for helper function 'to_utf8tex'. 2. Fix issue #123. isbnlib-3.10.14/requirements-dev.txt000066400000000000000000000005741442216276400173600ustar00rootroot00000000000000coverage[toml]==7.2.3 flake8==6.0.0 flake8-blind-except==0.2.1 flake8-bugbear==23.3.23 flake8-commas==2.1.0 flake8-comprehensions==3.12.0 flake8-deprecated==2.0.1 flake8-docstrings==1.7.0 flake8-import-order==0.18.2 flake8-mutable==1.2.0 flake8-pep3101==2.0.0 flake8-string-format==0.3.0 flake8-tidy-imports==4.8.0 pep8-naming==0.13.3 pytest==7.3.1 pytest-cov==4.0.0 yapf==0.33.0 isbnlib-3.10.14/setup.cfg000066400000000000000000000031001442216276400151250ustar00rootroot00000000000000[metadata] license=LGPL v3 license_file=LICENSE-LGPL-3.0.txt platforms=any description=Extract, clean, transform, hyphenate and metadata for ISBNs (International Standard Book Number). long_description=file: README.rst keywords=ISBN, metadata, World_Catalogue, Google_Books, Wikipedia, Open_Library, BibTeX, EndNote, RefWorks, MSWord, opf, BibJSON classifier= Programming Language :: Python Programming Language :: Python :: 3 Programming Language :: Python :: 3.6 Programming Language :: Python :: 3.7 Programming Language :: Python :: 3.8 Programming Language :: Python :: 3.9 Programming Language :: Python :: 3.10 Programming Language :: Python :: 3.11 License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3) Operating System :: OS Independent Development Status :: 5 - Production/Stable Intended Audience :: Developers Topic :: Text Processing :: General Topic :: Software Development :: Libraries :: Python Modules [bdist_wheel] universal=1 [flake8] max-line-length=88 exclude=*/test/*,*/_data/* max-complexity=11 ignore= E501, W503, E203, D202, W504, C901, D105, D107, D204, E126, E722, E741, I100, I101, I201, N802, N806, S001, W503 extend-ignore=E203,S001 [tool:pytest] addopts = --cov-config=setup.cfg testpaths = isbnlib/test markers = network: tests requiring network connection [coverage:run] source = isbnlib branch = True omit = isbnlib/test/* [coverage:report] fail_under = 90 show_missing = True skip_covered = True isbnlib-3.10.14/setup.py000066400000000000000000000066311442216276400150320ustar00rootroot00000000000000# -*- coding: utf-8 -*- # flake8: noqa # isort:skip_file # isbnlib -- tools for extracting, cleaning and transforming ISBNs # Copyright (C) 2014-2023 Alexandre Lima Conde # SPDX-License-Identifier: LGPL-3.0-or-later # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . from datetime import datetime as dt from setuptools import setup from isbnlib import __version__ PROJECT_NAME = 'isbnlib' PROJECT_PACKAGE_NAME = 'isbnlib' PROJECT_LICENSE = 'LGPL v3' PROJECT_LICENSE_URL = ( 'https://github.com/xlcnd/isbnlib/blob/dev/LICENSE-LGPL-3.0.txt') PROJECT_AUTHOR = 'Alexandre Lima Conde' PROJECT_COPYRIGHT = ' 2014-{}, {}'.format(dt.now().year, PROJECT_AUTHOR) PROJECT_URL = 'https://github.com/xlcnd/isbnlib' PROJECT_EMAIL = 'xlcnd@outlook.com' PROJECT_VERSION = __version__ PROJECT_GITHUB_USERNAME = 'xlcnd' PROJECT_GITHUB_REPOSITORY = 'isbnlib' GITHUB_PATH = '{}/{}'.format( PROJECT_GITHUB_USERNAME, PROJECT_GITHUB_REPOSITORY, ) GITHUB_URL = 'https://github.com/{}'.format(GITHUB_PATH) DOWNLOAD_URL = '{}/archive/{}.zip'.format(GITHUB_URL, 'v' + PROJECT_VERSION) PROJECT_URLS = { 'Bug Reports': '{}/issues'.format(GITHUB_URL), 'Dev Docs': 'https://github.com/xlcnd/isbnlib#info', 'Forum': 'https://stackoverflow.com/search?tab=newest&q=isbnlib', 'License': PROJECT_LICENSE_URL, } PYPI_URL = 'https://pypi.org/project/{}/'.format(PROJECT_PACKAGE_NAME) PYPI_CLASSIFIERS = [ 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: 3.11', 'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)', 'Operating System :: OS Independent', 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Text Processing :: General', 'Topic :: Software Development :: Libraries :: Python Modules', ] PACKAGES = [ 'isbnlib', 'isbnlib/dev', 'isbnlib/_data', ] setup( name=PROJECT_PACKAGE_NAME, version=PROJECT_VERSION, url=PROJECT_URL, download_url=DOWNLOAD_URL, project_urls=PROJECT_URLS, author=PROJECT_AUTHOR, author_email=PROJECT_EMAIL, packages=PACKAGES, license=PROJECT_LICENSE, description= 'Extract, clean, transform, hyphenate and metadata for ISBNs (International Standard Book Number).', long_description_content_type='text/x-rst', long_description=open('README.rst').read(), keywords= 'ISBN metadata World_Catalogue Google_Books Wikipedia Open_Library BibTeX EndNote RefWorks MSWord opf BibJSON', classifiers=PYPI_CLASSIFIERS, )