├── test ├── __init__.py └── test_gen_notes.py ├── docs ├── _static │ └── .gitkeep ├── screenshots │ ├── iphone.jpg │ ├── importing.png │ └── studying.png ├── Makefile ├── index.rst ├── installation.rst ├── conf.py ├── theory.rst ├── changes.rst ├── technical.rst └── importing.rst ├── .coveragerc ├── pytest.ini ├── requirements.txt ├── src ├── config.json ├── graves.txt ├── config.md ├── __init__.py ├── lpcg_dialog.py ├── gen_notes.py └── models.py ├── requirements_dev.txt ├── .gitignore ├── .readthedocs.yaml ├── Makefile ├── README.md ├── ankiweb_page.html ├── designer └── import_dialog.ui └── LICENSE /test/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/_static/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.coveragerc: -------------------------------------------------------------------------------- 1 | [report] 2 | omit = import_dialog*.py -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | addopts = --cov=src --cov-report=term --cov-report=html 3 | -------------------------------------------------------------------------------- /docs/screenshots/iphone.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sobjornstad/AnkiLPCG/HEAD/docs/screenshots/iphone.jpg -------------------------------------------------------------------------------- /docs/screenshots/importing.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sobjornstad/AnkiLPCG/HEAD/docs/screenshots/importing.png -------------------------------------------------------------------------------- /docs/screenshots/studying.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sobjornstad/AnkiLPCG/HEAD/docs/screenshots/studying.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pip>=20.1 2 | 3 | sphinx==5.3.0 4 | sphinx_rtd_theme==1.1.1 5 | readthedocs-sphinx-search==0.3.2 6 | -------------------------------------------------------------------------------- /src/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "defaultLinesOfContext": 2, 3 | "defaultLinesToRecite": 2, 4 | "defaultLinesInGroupsOf": 1, 5 | "endOfStanzaMarker": " ⊗", 6 | "endOfTextMarker": " □" 7 | } 8 | -------------------------------------------------------------------------------- /requirements_dev.txt: -------------------------------------------------------------------------------- 1 | -r requirements.txt 2 | 3 | pytest>=5.4.3 4 | pytest-cov>=2.10.0 5 | pylint>=2.5.2 6 | yapf>=0.30.0 7 | mypy>=0.770 8 | 9 | pyqt6==6.2.2 10 | anki==2.1.50beta2 11 | aqt==2.1.50beta2 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # ide 2 | .vscode/ 3 | 4 | # cache 5 | .mypy_cache/ 6 | .pytest_cache/ 7 | __pycache__/ 8 | venv/ 9 | 10 | # build outputs 11 | src/import_dialog*.py 12 | build*.zip 13 | *.pyc 14 | *.un~ 15 | .coverage 16 | htmlcov/ 17 | docs/_build 18 | build.ankiaddon 19 | 20 | # anki add-on metadata file which appears when live-linking 21 | meta.json 22 | -------------------------------------------------------------------------------- /src/graves.txt: -------------------------------------------------------------------------------- 1 | 2 | @property 3 | def num_successors(self) -> int: 4 | node = self 5 | count = 0 6 | while node.successor is not None: 7 | node = node.successor 8 | count += 1 9 | return count 10 | 11 | @property 12 | def num_predecessors(self) -> int: 13 | node = self 14 | count = 0 15 | while not isinstance(node.predecessor, Beginning): 16 | node = node.predecessor 17 | count += 1 18 | return count -------------------------------------------------------------------------------- /.readthedocs.yaml: -------------------------------------------------------------------------------- 1 | # .readthedocs.yaml 2 | # Read the Docs configuration file 3 | # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details 4 | 5 | # Required 6 | version: 2 7 | 8 | build: 9 | os: ubuntu-22.04 10 | tools: 11 | python: "3.11" 12 | 13 | # Build documentation in the docs/ directory with Sphinx 14 | sphinx: 15 | configuration: docs/conf.py 16 | 17 | # Optionally build your docs in additional formats such as PDF 18 | formats: 19 | - pdf 20 | 21 | # Optionally set the version of Python and requirements required to build your docs 22 | python: 23 | install: 24 | - requirements: requirements.txt 25 | -------------------------------------------------------------------------------- /src/config.md: -------------------------------------------------------------------------------- 1 | LPCG Options: 2 | 3 | **defaultLinesOfContext**, **defaultLinesToRecite**, **defaultLinesInGroupsOf**: These control the values in the respective spin boxes when you open the LPCG import dialog. If you regularly like to use different values than the defaults (2, 1, and 1), you can set them here and avoid having to tweak them every time. 4 | **endOfStanzaMarker**: This string will be added at the end of the last line of each stanza. It should normally begin with a space so it isn’t squashed against the end of the last word on the line. 5 | **endOfTextMarker**: Like *endOfStanzaMarker*, but appears at the end of the last line of the entire text. 6 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: all addon docs forms clean 2 | 3 | all: docs forms addon 4 | docs: 5 | $(MAKE) -C docs html 6 | forms: src/import_dialog5.py src/import_dialog6.py 7 | addon: build.ankiaddon 8 | 9 | src/import_dialog5.py: designer/import_dialog.ui 10 | pyuic5 $^ > $@ 11 | 12 | src/import_dialog6.py: designer/import_dialog.ui 13 | pyuic6 $^ > $@ 14 | 15 | build.ankiaddon: src/* 16 | rm -f $@ 17 | rm -f src/meta.json 18 | rm -rf src/__pycache__ 19 | ( cd src/; zip -r ../$@ * ) 20 | 21 | clean: 22 | make -C docs clean 23 | rm -f *.pyc 24 | rm -f src/*.pyc 25 | rm -f src/__pycache__ 26 | rm -f src/import_dialog.py 27 | rm -f build.ankiaddon 28 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | SOURCEDIR = . 8 | BUILDDIR = _build 9 | 10 | # Put it first so that "make" without argument is like "make help". 11 | help: 12 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 13 | 14 | .PHONY: help Makefile 15 | 16 | # Catch-all target: route all unknown targets to Sphinx using the new 17 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 18 | %: Makefile 19 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | ==== 2 | LPCG 3 | ==== 4 | 5 | Anki **Lyrics/Poetry Cloze Generator** (LPCG) 6 | is an add-on for `Anki`_ 7 | for studying long passages of verbatim text, like poetry or song lyrics. 8 | 9 | For clarity, throughout this documentation, we’ll discuss “poetry,” 10 | but everything applies equally 11 | to songs, speeches, or any other text you might want to memorize. 12 | 13 | .. image:: screenshots/studying.* 14 | :width: 50% 15 | 16 | .. image:: screenshots/iphone.* 17 | :width: 25% 18 | 19 | .. _Anki: https://apps.ankiweb.net 20 | 21 | 22 | Getting Help 23 | ============ 24 | 25 | If you have questions or technical issues 26 | which are not answered by this manual, 27 | you can email me at `anki@sorenbjornstad.com `_. 28 | 29 | If you have found a bug, 30 | would like to suggest a feature, 31 | or have improvements to contribute, 32 | please post on the issue tracker or submit a pull request `at GitHub`_. 33 | 34 | .. _at GitHub: https://github.com/sobjornstad/AnkiLPCG 35 | 36 | 37 | .. toctree:: 38 | :maxdepth: 3 39 | :caption: Contents 40 | 41 | theory 42 | installation 43 | importing 44 | technical 45 | changes 46 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Anki **Lyrics/Poetry Cloze Generator** (LPCG) is an add-on for [Anki][] 2 | to make it easier to study long passages of verbatim text, 3 | like poetry or song lyrics. 4 | 5 | LPCG is licensed under the GNU AGPL version 3, 6 | or at your option, any later version. 7 | 8 | 9 | ## How do I... 10 | 11 | * **Install LPCG**: Visit its [AnkiWeb page][awp]. 12 | * **Use LPCG**: Visit the [documentation on Read the Docs][doc]. 13 | * **Get help with LPCG**: See the [getting help][] section of the documentation. 14 | * **Contribute to LPCG**: 15 | Post on the `Issues` tab of this repository, or submit a pull request. 16 | * **See what's changed**: 17 | See the [changelog][] page of the documentation. 18 | 19 | [Anki]: https://apps.ankiweb.net 20 | [awp]: https://ankiweb.net/shared/info/2084557901 21 | [doc]: https://ankilpcg.readthedocs.io/en/latest/index.html 22 | [getting help]: https://ankilpcg.readthedocs.io/en/latest/index.html#getting-help 23 | [changelog]: https://ankilpcg.readthedocs.io/en/latest/changes.html 24 | 25 | 26 | ## Screenshots 27 | 28 | Importing content into LPCG 29 | Studying on the desktop 30 | Studying on an iPhone 31 | -------------------------------------------------------------------------------- /ankiweb_page.html: -------------------------------------------------------------------------------- 1 | Lyrics/Poetry Cloze Generator (LPCG) is an add-on for Anki to help with studying long passages of verbatim text, like poetry or song lyrics. 2 | 3 | The documentation contains information on recommended study techniques and how to use the add-on, and can be read here. 4 | 5 | The latest version is LPCG 1.4.3. For details on changes, please see the changelog. 6 | 7 | Support 8 | Before asking questions, please take a look at the documentation. 9 | 10 | If you still have questions, you can email me at anki@sorenbjornstad.com. Please do not post reviews asking questions or reporting bugs, as I have no way to respond to them. 11 | 12 | If you have found a bug or wish to suggest an improvement, you can post on the issue tracker or submit a pull request at GitHub. 13 | 14 | Screenshots 15 | Importing a poem into Anki: 16 | 17 | 18 | Studying on the desktop: 19 | 20 | 21 | Studying on mobile: 22 | 23 | -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Installation 3 | ============ 4 | 5 | From AnkiWeb 6 | ============ 7 | 8 | Most users will want to install LPCG through AnkiWeb. 9 | This is the easiest method, and it lets you get updates automatically. 10 | 11 | You can find LPCG on `its AnkiWeb page `_, 12 | which will show instructions for completing the installation. 13 | LPCG, like Anki, is licensed under the `GNU AGPL3`_ license. 14 | 15 | .. _GNU AGPL3: http://www.gnu.org/licenses/agpl.html 16 | 17 | 18 | From source 19 | =========== 20 | 21 | If you want to do development on LPCG, you can install it from source. 22 | The source is available `at GitHub`_. 23 | 24 | 1. Clone the Git repository. 25 | #. Create a virtual environment with ``python -m venv venv``, 26 | and activate it (usually ``. venv/bin/activate``). 27 | #. Install Python dependencies with ``pip install -r requirements.txt``. 28 | LPCG is tested on Python 3.10 but will work on 3.9 too. 29 | #. Ensure you have PyQt5/6 and the ``pyuic5`` // ``pyuic6`` command available 30 | (depending on which version(s) of Qt you want to build against; 31 | both 5 and 6 are supported at the time of this writing). 32 | #. Run ``make`` to generate code for the dialog from Qt Designer 33 | (among other things). 34 | 35 | To run the add-on within Anki, 36 | symlink or move the ``src`` directory into your Anki add-ons directory. 37 | Running ``pytest`` from the root directory will run the unit tests. 38 | 39 | .. _at GitHub: https://github.com/sobjornstad/AnkiLPCG 40 | -------------------------------------------------------------------------------- /src/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | LPCG - Lyrics/Poetry Cloze Generator 3 | Copyright (c) 2016-2023 Soren Bjornstad 4 | and the LPCG community. 5 | 6 | License: GNU AGPL, version 3 or later. 7 | See LICENSE file or for details. 8 | """ 9 | 10 | import sys 11 | 12 | # don't try to set up the UI if running unit tests 13 | if 'pytest' not in sys.modules: 14 | # pylint: disable=import-error, no-name-in-module 15 | # pylint: disable=invalid-name 16 | import aqt 17 | from aqt.qt import QAction # type: ignore 18 | from aqt.utils import showWarning 19 | 20 | from .lpcg_dialog import LPCGDialog 21 | from . import models 22 | 23 | def open_dialog(): 24 | "Launch the add-poem dialog." 25 | current_version = aqt.mw.col.get_config('lpcg_model_version', default="none") 26 | if not models.LpcgOne.is_at_version(current_version): 27 | showWarning( 28 | "Your LPCG note type is out of date and needs to be upgraded " 29 | "before you can use LPCG. To upgrade the note type, restart Anki " 30 | "and respond yes to the prompt.") 31 | return 32 | dialog = LPCGDialog(aqt.mw) 33 | dialog.exec() 34 | 35 | if aqt.mw is not None: 36 | action = QAction(aqt.mw) 37 | action.setText("Import &Lyrics/Poetry") 38 | aqt.mw.form.menuTools.addAction(action) 39 | action.triggered.connect(open_dialog) 40 | 41 | aqt.gui_hooks.profile_did_open.append(models.ensure_note_type) 42 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Configuration file for the Sphinx documentation builder. 4 | # 5 | # This file does only contain a selection of the most common options. For a 6 | # full list see the documentation: 7 | # http://www.sphinx-doc.org/en/master/config 8 | 9 | # -- Path setup -------------------------------------------------------------- 10 | # Instead of adding things manually to the path, we just ensure we install esc 11 | # in editable mode in our environment. 12 | 13 | 14 | # -- Project information ----------------------------------------------------- 15 | 16 | project = 'LPCG' 17 | copyright = '2016--2023, Soren Bjornstad' 18 | author = 'Soren I. Bjornstad' 19 | 20 | # The short X.Y version 21 | version = "1.4.3" 22 | # The full version, including alpha/beta/rc tags 23 | release = version 24 | 25 | 26 | # -- General configuration --------------------------------------------------- 27 | 28 | # If your documentation needs a minimal Sphinx version, state it here. 29 | # 30 | needs_sphinx = '1.8.5' 31 | 32 | # Add any Sphinx extension module names here, as strings. They can be 33 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 34 | # ones. 35 | extensions = [ 36 | 'sphinx.ext.autosectionlabel', 37 | 'sphinx.ext.todo', 38 | ] 39 | 40 | # Add any paths that contain templates here, relative to this directory. 41 | templates_path = ['_templates'] 42 | 43 | # The suffix(es) of source filenames. 44 | # You can specify multiple suffix as a list of string. 45 | source_suffix = '.rst' 46 | 47 | # The master toctree document. 48 | master_doc = 'index' 49 | 50 | # The language for content autogenerated by Sphinx. Refer to documentation 51 | # for a list of supported languages. 52 | # 53 | # This is also used if you do content translation via gettext catalogs. 54 | # Usually you set "language" from the command line for these cases. 55 | language = 'en' 56 | 57 | # List of patterns, relative to source directory, that match files and 58 | # directories to ignore when looking for source files. 59 | # This pattern also affects html_static_path and html_extra_path. 60 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 61 | 62 | # The name of the Pygments (syntax highlighting) style to use. 63 | pygments_style = None 64 | 65 | 66 | # -- Options for HTML output ------------------------------------------------- 67 | 68 | # The theme to use for HTML and HTML Help pages. See the documentation for 69 | # a list of builtin themes. 70 | # 71 | html_theme = 'sphinx_rtd_theme' 72 | 73 | # Theme options are theme-specific and customize the look and feel of a theme 74 | # further. For a list of options available for each theme, see the 75 | # documentation. 76 | # 77 | # html_theme_options = {} 78 | 79 | # Add any paths that contain custom static files (such as style sheets) here, 80 | # relative to this directory. They are copied after the builtin static files, 81 | # so a file named "default.css" will overwrite the builtin "default.css". 82 | html_static_path = ['_static'] 83 | 84 | # Custom sidebar templates, must be a dictionary that maps document names 85 | # to template names. 86 | # 87 | # The default sidebars (for documents that don't match any pattern) are 88 | # defined by theme itself. Builtin themes are using these templates by 89 | # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', 90 | # 'searchbox.html']``. 91 | # 92 | # html_sidebars = {} 93 | 94 | 95 | 96 | # -- Extension configuration ------------------------------------------------- 97 | 98 | # If true, `todo` and `todoList` produce output, else they produce nothing. 99 | todo_include_todos = True 100 | 101 | # Prefix section labels with the names of their documents, to avoid ambiguity 102 | # when the same heading appears on several pages. 103 | autosectionlabel_prefix_document = False 104 | -------------------------------------------------------------------------------- /docs/theory.rst: -------------------------------------------------------------------------------- 1 | 2 | ====== 3 | Theory 4 | ====== 5 | 6 | Spaced-repetition strategies for poetry 7 | ======================================= 8 | 9 | Memorizing poetry can be a tough problem for Anki users: 10 | it isn’t obvious how to divide it into discrete cards. 11 | People often try one of the following approaches: 12 | 13 | * **Putting the whole poem onto one card.** 14 | This is a bad idea because if you have trouble with any part of the poem, 15 | you’ll have to fail the entire card, 16 | thus you will review far more often than you need to. 17 | * **Creating one card per line and defining an order for the cards**, 18 | so Anki asks for the lines in order. 19 | Aside from this being impossible in the current version of Anki, 20 | spaced-repetition scheduling doesn’t work properly 21 | unless the cards are in random order. 22 | 23 | LPCG takes a different approach: 24 | it generates cards that can stand on their own and make perfect sense in random order. 25 | Each card shows several lines from the poem 26 | and then asks you to recite some following lines. 27 | By default, it shows two lines of context and asks you to recite one line, 28 | and tests each line exactly once, but the details can be changed if needed. 29 | 30 | In my experience, LPCG is not a good way to *memorize* poetry: 31 | not seeing the full context makes initial acquisition unnecessarily difficult. 32 | However, it is a great way to *review* poetry. 33 | This is fine, because as most Anki users know, 34 | the big problem isn’t learning things in the first place, 35 | it’s remembering them for long periods of time. 36 | 37 | If you don’t know a good way of initially learning poems, 38 | look at the :ref:`Initial memorization` section, below. 39 | 40 | 41 | Initial memorization 42 | ==================== 43 | 44 | The LPCG method works best if you memorize your poems 45 | before you start reviewing them in Anki. 46 | As alluded to in the :ref:`Spaced-repetition strategies for poetry` section, 47 | there are a lot of good ways to memorize poetry initially; 48 | it’s retaining it that’s hard. 49 | 50 | If you're already good at memorizing poetry, 51 | don’t listen to me, just use your own method; 52 | there's nothing magical about this one. 53 | But if you don’t have a good method, 54 | here’s one that works well for me and many others. 55 | 56 | 1. If you haven’t already done so, 57 | read through the poem carefully so you have a general idea of how it goes. 58 | 2. Read through the poem again, line by line. This time, immediately after you 59 | read each line, look away from the page and repeat the line back. If you 60 | stumble or get it wrong, try again until you get it right: read the line 61 | again, then look away and repeat it again. It is helpful but not strictly 62 | necessary to speak out loud. 63 | 3. Repeat step 2, but take two lines at a time – then repeat with three, four, 64 | five, and six. You will find it gets a little bit harder each time, but not 65 | much, since you’re getting more familiar with the poem as well; before you 66 | know it you’ll be able to remember six lines at a time. It is unnecessary to 67 | continue this process beyond six lines. 68 | 4. Set the poem aside until the next day – it is truly remarkable how much 69 | easier it is to continue after a good night’s sleep. Do not skip this step! 70 | The rest will be easy if you do it and quite frustrating if you don’t. 71 | 5. Try reciting the poem straight through. If the text is easy, you may have it 72 | already; otherwise, go back and work on any spots you don’t have down yet. 73 | No particular method is necessary at this point. Don’t work for more than a 74 | few minutes; just touching all the difficult spots is enough. 75 | 6. The next day, repeat step 5. Most likely the poem will now come very 76 | naturally to you. Particularly difficult texts may require one more day. 77 | 78 | Once you have the poem learned, 79 | put it into Anki if you want to remember it beyond the next couple of weeks 80 | -- this is where LPCG comes into play. 81 | 82 | It is totally fine to take breaks during step 3, even doing it over several 83 | days; you’ll spend 90% of your concentrated time in this step, and it’s not 84 | helpful to try to work when you’re tired. 85 | -------------------------------------------------------------------------------- /docs/changes.rst: -------------------------------------------------------------------------------- 1 | ========= 2 | Changelog 3 | ========= 4 | 5 | LPCG 1.4.3 6 | ========== 7 | 8 | Released on December 6, 2023. 9 | 10 | * Fix “wrapped C/C++ object of type QPushButton has been deleted” error 11 | occurring when generating cards with LPCG more than once per Anki session, or 12 | opening the add or edit screen after using LPCG. 13 | 14 | 15 | LPCG 1.4.2 16 | ========== 17 | 18 | * Add support for Qt 6, in advance of Anki moving to that GUI toolkit version. 19 | Builds of Anki that use Qt 5 will continue to work. 20 | 21 | 22 | LPCG 1.4.1 23 | ========== 24 | 25 | Released on July 24, 2021. 26 | 27 | * Update all deprecated function and type names 28 | to current versions as of Anki 2.1.45. 29 | * Drop support for earlier Anki versions. 30 | * Accept :kbd:`Ctrl+Enter` for :guilabel:`Add Notes` in the poem editor, 31 | just like in Anki's standard add-notes dialog. 32 | 33 | 34 | LPCG 1.4.0 35 | ========== 36 | 37 | Released on November 15, 2020. 38 | 39 | * Add an *Author* field to the note type, 40 | which can optionally be set when adding poems 41 | (thanks to @cashweaver). 42 | The author displays just underneath the title and index when reviewing, 43 | if present. 44 | * The Add Notes access key has been changed from :kbd:`a` to :kbd:`d` 45 | to resolve a conflict with :guilabel:`Author` 46 | (all the letters in *Author* were already taken!). 47 | * Allow quotation marks to be used in the title of a poem, 48 | now that Anki is able to escape quotation marks in searches. 49 | * Make the default values of the import spinboxes configurable. 50 | * Add screenshots to the README. 51 | 52 | 53 | LPCG 1.3.0 54 | ========== 55 | 56 | * Added options *Lines to Recite* and *Lines in Groups of*. 57 | * Add a *Prompt* field to the note type. 58 | This was added to support showing the user 59 | how many lines they're being asked to recite, 60 | but could be used for other things in the future. 61 | Backwards compatibility with existing notes is maintained 62 | by displaying ``[...]`` if the field is empty. 63 | * The *Line* field now wraps each (or the only) line in ``

`` tags, 64 | to support multiple-line recitation with correct indentation. 65 | Existing LPCG notes without ``

`` tags will still display fine as well. 66 | * Invert color of cloze deletions in night mode, 67 | as the default color is unnecessarily difficult to read on many screens. 68 | * Added some automated regression testing. 69 | * Add a *Help* button to the import dialog leading to the documentation. 70 | * Under-the-hood refactorings and updates to newer features offered by Anki. 71 | * Refresh the documentation and move to Read the Docs 72 | for a nice multi-page view instead of relying on GitHub's Markdown rendering. 73 | 74 | 75 | LPCG 1.2.1 76 | ========== 77 | 78 | * Provide a useful error message when generating notes 79 | and the LPCG note type is missing a required field. 80 | 81 | 82 | LPCG 1.2.0 83 | ========== 84 | 85 | * Support for Anki 2.1 (only). 86 | * Fixed several minor bugs in splitting poems into stanzas 87 | that could result in end-of-stanza and end-of-poem markers 88 | appearing on lines by themselves. 89 | * Fixed text flowing off the right side of mobile device screens 90 | (thanks to Jonta). 91 | 92 | 93 | LPCG 1.1.0 94 | ========== 95 | 96 | * Added support for changing the number of lines of context you want to see 97 | for a given poem. 98 | The default remains 2. 99 | 100 | This is the last version that supports Anki 2.0. 101 | 102 | 103 | LPCG 1.0.0 104 | ========== 105 | 106 | LPCG was completely rewritten 107 | and became a proper Anki add-on instead of a stand-alone Python script. 108 | A new note type is also used with this version. 109 | 110 | 111 | LPCG 0.9.4 112 | ========== 113 | 114 | * Improve the user experience when the temporary folder is not writable 115 | or the user specifies a nonexistent file. 116 | * Add a message explaining that Anki should have opened to import notes, 117 | in case it doesn't and the user is left sitting there wondering 118 | what's supposed to happen next. 119 | 120 | 121 | LPCG 0.9.3 122 | ========== 123 | 124 | * Fix typo in code that caused LPCG not to import successfully at all. 125 | 126 | 127 | LPCG 0.9.2 128 | ========== 129 | 130 | * Fix off-by-one error sometimes resulting in incorrect card generation. 131 | * Allow dragging and dropping files onto the terminal window to work correctly 132 | in more situations. 133 | 134 | 135 | LPCG 0.9.1 136 | ========== 137 | 138 | * Tags should not be mandatory. 139 | 140 | 141 | LPCG 0.9.0 142 | ========== 143 | 144 | * First public release. 145 | -------------------------------------------------------------------------------- /docs/technical.rst: -------------------------------------------------------------------------------- 1 | =================================== 2 | Technical Details and Customization 3 | =================================== 4 | 5 | Here's some technical and architectural mumbo-jumbo 6 | that you probably don't need to use LPCG 7 | but might be useful if you want to customize LPCG or are just curious. 8 | 9 | 10 | The LPCG note type 11 | ================== 12 | 13 | The note type has five fields: 14 | 15 | Line 16 | Contains the line or lines this card asks you to recite. 17 | Since LPCG 1.3, each line is enclosed in a ``

`` tag. 18 | For backwards compatibility, 19 | the template is also required to correctly display this field 20 | if it contains a single line without any ``

`` tags. 21 | 22 | Both the *Line* and *Context* fields 23 | look kind of oddly spaced in the editor due to the use of ``

`` tags, 24 | because the editor doesn’t use the same styling as the review window 25 | and this can't easily be customized. 26 | 27 | Context 28 | Contains the several lines prior to *Line*, 29 | to give you an idea of what to recite. 30 | 31 | Title 32 | The title of the poem that this line comes from. 33 | 34 | Sequence 35 | The line number (counting only text lines, not comments or blank lines) 36 | of the first line of the *Line* field in the original poem. 37 | 38 | If the *Lines in Groups of* :ref:`setting ` 39 | was set to a value greater than 1, 40 | the actual line number in the original poem is 41 | the sequence number multiplied by *Lines in Groups of*, 42 | minus *Lines in Groups of*, plus 1. 43 | 44 | Prompt 45 | If this field is populated, it will appear instead of ``[...]`` 46 | on the question side. 47 | 48 | *New in LPCG 1.3.* 49 | 50 | It is safe to add additional fields to the note type 51 | if you wish to include more metadata on your poems. 52 | The only likely issue would be if LPCG added a new field in the future 53 | and its name happened to conflict with yours; 54 | even then, this wouldn't cause any data loss, 55 | you'd just have to rename your own field if you wanted to continue using it. 56 | 57 | 58 | Why separate notes? 59 | =================== 60 | 61 | LPCG takes the approach of creating a series of unrelated notes, 62 | rather than a single note. 63 | Creating one note per poem would have a number of serious disadvantages: 64 | 65 | * Sibling burying would get in the way – it can of course be turned off, but 66 | this would be confusing to some users. 67 | * The amount of template boilerplate required would be absurd, and extremely 68 | large templates can cause syncing and other issues. 69 | * LPCG would not be able to support poems of arbitrary length, since note types 70 | cannot contain an arbitrary number of fields or card types; at some point you 71 | would have to create multiple notes for the same poem, which would break the 72 | neat correspondence anyway. 73 | 74 | The Sequence field helps to mitigate the disadvantages of having separate notes 75 | – by searching for a given poem (e.g., ``"note:LPCG 1.0" "Title:My Poem"``) 76 | and then sorting by the Sequence field, 77 | you can still see and select the whole poem at once. 78 | 79 | One possible area for future improvement 80 | would be caching the poem or its parsed representation 81 | so that a poem's notes could be edited from a poem-editor-like text box 82 | after initial creation. 83 | At the moment, this feels like gold-plating since poems rarely need editing 84 | and I have not seen any demand for such a feature. 85 | 86 | 87 | Customizing styling 88 | =================== 89 | 90 | If you’d like to customize the width of indents, you can make some changes in the styling section of the card types dialog: 91 | 92 | * **Hanging indent** (when a line is too long for the screen): 93 | Change ``margin-left`` and ``text-indent`` in the ``.lines`` class. 94 | They should be inverses of each other 95 | (e.g., if ``text-indent`` is 30 pixels, ``margin-left`` should be -30 pixels). 96 | You’ll also need to change ``margin-left`` in the ``.cloze`` section 97 | to match ``text-indent``. 98 | * **Manual indent** (when an indent is given in the original poem text): 99 | Change ``margin-left`` in the ``.indent`` class. 100 | 101 | The end-of-stanza and end-of-poem markers can be changed in the add-on config 102 | (choose :menuselection:`Tools --> Add-ons`, 103 | select LPCG in the list on the left, 104 | and click the :guilabel:`Config` button). 105 | 106 | As of version 1.3, LPCG inverts the color of cloze deletions in night mode, 107 | as the default solid blue is quite difficult to read in night mode 108 | on many screens. 109 | If you don't like the color, 110 | you can change it in the styling rule ``.nightMode .cloze``. 111 | -------------------------------------------------------------------------------- /src/lpcg_dialog.py: -------------------------------------------------------------------------------- 1 | """ 2 | Dialog box for importing texts. 3 | """ 4 | 5 | import codecs 6 | 7 | # pylint: disable=no-name-in-module 8 | from aqt.deckchooser import DeckChooser 9 | from aqt.qt import QDesktopServices, QDialog, QUrl, qtmajor 10 | from aqt.utils import getFile, showWarning, askUser, tooltip 11 | from anki.notes import Note 12 | 13 | if qtmajor > 5: 14 | from . import import_dialog6 as lpcg_form 15 | else: 16 | from . import import_dialog5 as lpcg_form # type: ignore 17 | 18 | # pylint: disable=wrong-import-position 19 | from .gen_notes import add_notes, cleanse_text 20 | from . import models 21 | 22 | 23 | class LPCGDialog(QDialog): 24 | """ 25 | Import Lyrics/Poetry dialog, the core of the add-on. The user can either 26 | enter the text of a poem in the editor or import a text file from somewhere 27 | else on the computer. The poem can be entered with usual markup (blank 28 | lines between stanzas, one level of indentation with tabs or spaces in 29 | front of lines). LPCG then processes it into notes with two lines of 30 | context and adds them to the user's collection. 31 | """ 32 | def __init__(self, mw): 33 | self.mw = mw 34 | 35 | QDialog.__init__(self) 36 | self.form = lpcg_form.Ui_Dialog() 37 | self.form.setupUi(self) 38 | self.deckChooser = DeckChooser(self.mw, self.form.deckChooser) 39 | 40 | self.form.addCardsButton.clicked.connect(self.accept) 41 | self.form.cancelButton.clicked.connect(self.reject) 42 | self.form.openFileButton.clicked.connect(self.onOpenFile) 43 | self.form.helpButton.clicked.connect(self.onHelp) 44 | 45 | self.addonConfig = self.mw.addonManager.getConfig(__name__) 46 | self.form.contextLinesSpin.setValue(self.addonConfig['defaultLinesOfContext']) 47 | self.form.reciteLinesSpin.setValue(self.addonConfig['defaultLinesToRecite']) 48 | self.form.groupLinesSpin.setValue(self.addonConfig['defaultLinesInGroupsOf']) 49 | 50 | def accept(self): 51 | "On close, create notes from the contents of the poem editor." 52 | title = self.form.titleBox.text().strip() 53 | 54 | if not title: 55 | showWarning("You must enter a title for this poem.") 56 | return 57 | escaped_title = title.replace('"', '\\"') 58 | if self.mw.col.find_notes(f'"note:{models.LpcgOne.name}" ' # pylint: disable=no-member 59 | f'"Title:{escaped_title}"'): 60 | showWarning("You already have a poem by that title in your " 61 | "database. Please check to see if you've already " 62 | "added it, or use a different name.") 63 | return 64 | if not self.form.textBox.toPlainText().strip(): 65 | showWarning("There's nothing to generate cards from! " 66 | "Please type a poem in the box, or use the " 67 | '"Open File" button to import a text file.') 68 | return 69 | 70 | author = self.form.authorBox.text().strip() 71 | tags = self.mw.col.tags.split(self.form.tagsBox.text()) 72 | text = cleanse_text(self.form.textBox.toPlainText().strip(), self.addonConfig) 73 | context_lines = self.form.contextLinesSpin.value() 74 | recite_lines = self.form.reciteLinesSpin.value() 75 | group_lines = self.form.groupLinesSpin.value() 76 | did = self.deckChooser.selectedId() 77 | 78 | try: 79 | notes_generated = add_notes(self.mw.col, Note, title, author, tags, text, did, 80 | context_lines, group_lines, recite_lines) 81 | except KeyError as e: 82 | showWarning( 83 | "The field {field} was not found on the {name} note type" 84 | " in your collection. If you don't have any LPCG notes" 85 | " yet, you can delete the note type in Tools -> Manage" 86 | " Note Types and restart Anki to fix this problem." 87 | " Otherwise, please add the field back to the note type. " 88 | .format(field=str(e), name=models.LpcgOne.name)) # pylint: disable=no-member 89 | return 90 | 91 | if notes_generated: 92 | super(LPCGDialog, self).accept() 93 | self.deckChooser.cleanup() 94 | self.mw.reset() 95 | tooltip("%i notes added." % notes_generated) 96 | 97 | def onOpenFile(self): 98 | """ 99 | Read a text file (in UTF-8 encoding) and replace the contents of the 100 | poem editor with the contents of the file. 101 | """ 102 | if (self.form.textBox.toPlainText().strip() 103 | and not askUser("Importing a file will replace the current " 104 | "contents of the poem editor. Continue?")): 105 | return 106 | filename = getFile(self, "Import file", None, key="import") 107 | if not filename: # canceled 108 | return 109 | with codecs.open(filename, 'r', 'utf-8') as f: 110 | text = f.read() 111 | self.form.textBox.setPlainText(text) 112 | 113 | def onHelp(self): 114 | """ 115 | Open the documentation on importing files in a browser. 116 | """ 117 | doc_url = "https://ankilpcg.readthedocs.io/en/latest/importing.html" 118 | QDesktopServices.openUrl(QUrl(doc_url)) 119 | -------------------------------------------------------------------------------- /docs/importing.rst: -------------------------------------------------------------------------------- 1 | =============== 2 | Importing Poems 3 | =============== 4 | 5 | To add a poem to your collection, 6 | choose :menuselection:`Tools --> Import Lyrics/Poetry`. 7 | You will see the following window: 8 | 9 | .. image:: screenshots/importing.* 10 | 11 | Set the options and enter a poem as described below, 12 | then click :guilabel:`Add notes` 13 | to add notes for the new poem to your collection. 14 | 15 | 16 | Basic options 17 | ============= 18 | 19 | The **Title** of your poem will appear at the top of all your cards 20 | so you know what you're reviewing. 21 | It's also used to warn you 22 | if you already have a poem by that title in your collection. 23 | 24 | The **Author**, if provided, will also appear at the top of your cards, 25 | underneath the title. 26 | 27 | The **Tags** and **Deck** 28 | will be attached to all notes generated from this poem 29 | and work the same way as they do elsewhere in Anki. 30 | 31 | 32 | The poem editor 33 | =============== 34 | 35 | The large text box, called the *poem editor*, 36 | contains the text from which your cards will be generated. 37 | You can either type or paste a poem directly into the editor 38 | or open a plain text file somewhere on your computer 39 | using the **Open file** button. 40 | 41 | The poem editor recognizes standard typographical conventions for poetry: 42 | 43 | Stanza breaks 44 | Leaving a blank line 45 | (that is, a line containing no characters, or only whitespace) 46 | starts a new stanza. 47 | Blank lines at the start or end of the poem are ignored, 48 | and consecutive blank lines are treated as a single blank line. 49 | 50 | Stanza breaks don't appear as vertical space during reviews. 51 | Instead, the character **⊗** appears at the end of a line that ends a stanza, 52 | and the character **□** appears at the end of the poem's final line. 53 | 54 | Indentation 55 | Placing any number of spaces or tabs at the start of a line 56 | creates an indented line. 57 | Only one level of indentation is recognized, 58 | as poems that use more than one level of indentation are extremely rare, 59 | and this frees you from minutiae about how many spaces or tabs to use. 60 | 61 | LPCG also applies a hanging indent at review time 62 | to any lines that do not fit on your device's screen in their entirety. 63 | This hanging indent is twice the size of a "hard" indent 64 | that's part of the poem. 65 | 66 | Comments 67 | Lines beginning with the comment character ``#`` are ignored, 68 | as is anything after the first ``#`` within a text line; 69 | everything else in the editor will be treated as the text of your poem. 70 | 71 | If you keep your poems in text files, 72 | you might want to use this to include annotations 73 | or information about the title or author. 74 | 75 | 76 | Here is an example of a correctly formatted poem: 77 | :: 78 | 79 | # from “Little Gidding,” movement II 80 | # by T.S. Eliot 81 | 82 | Ash on an old man’s sleeve 83 | Is all the ash the burnt roses leave. 84 | Dust in the air suspended 85 | Marks the place where a story ended. 86 | Dust inbreathed was a house – 87 | The wall, the wainscot and the mouse. 88 | The death of hope and despair, 89 | This is the death of air. 90 | 91 | There are flood and drouth 92 | Over the eyes and in the mouth, 93 | Dead water and dead sand 94 | Contending for the upper hand. 95 | The parched eviscerate soil 96 | Gapes at the vanity of toil, 97 | Laughs without mirth. 98 | This is the death of earth. 99 | 100 | 101 | Generation settings 102 | =================== 103 | 104 | The three numeric spin-boxes 105 | allow you to customize how much text appears on each card. 106 | Tweaking these settings is entirely optional; 107 | the default values are sufficient for most poems. 108 | You can change the default values in the add-on config 109 | (:menuselection:`Tools --> Add-ons --> LPCG --> Config`). 110 | 111 | Lines of Context 112 | The number of lines that will be shown 113 | on the question side of each card as a prompt. 114 | With the default of 2, you'll see 2 lines of the poem 115 | and then be asked to recite the following line(s). 116 | 117 | At the very beginning of the poem, 118 | fewer lines of context will be available 119 | (e.g., there is no context at all for the first line 120 | save the title of the poem). 121 | If fewer lines of context are available than the value of this option, 122 | the text ``[Beginning]`` will appear on the question side of the card, 123 | followed by whatever context is available (if any). 124 | 125 | Lines to Recite 126 | The number of lines that will be revealed 127 | on the answer side of each card. 128 | With the default of 1, a single line will be shown after the context lines. 129 | 130 | If *Lines to Recite* is more than 1, 131 | the cloze prompt ``[...]`` on the generated cards 132 | will show the number of lines that you need to recite, 133 | e.g., ``[...3]`` if there are three lines to recite. 134 | 135 | If the number of lines in your poem 136 | is not evenly divisible by *Lines to Recite* 137 | (e.g., you set it to 3 in a 16-line poem), 138 | one or more cards at the end will have fewer lines to recite; 139 | the cloze prompt will be adjusted accordingly. 140 | 141 | *New in LPCG 1.3.* 142 | 143 | Lines in Groups of 144 | .. warning:: 145 | This option can be confusing. 146 | If the two preceding options are enough to meet your needs, 147 | don't even bother reading this section! 148 | 149 | If this option is greater than 1, 150 | the physical lines in the poem editor will be grouped into "virtual lines" 151 | which will then be treated in accordance 152 | with the *Lines of Context* and *Lines to Recite* options. 153 | This can be useful if your poem has a large number of extremely short lines. 154 | 155 | For example, if you set *Lines in Groups of* to 2, 156 | *Lines of Context* to 2, 157 | and *Lines to Recite* to 1, 158 | you'll get cards that show 4 physical lines of context 159 | and ask you to recite 2 lines. 160 | 161 | At first glance, this may appear to be exactly the same thing as 162 | doubling the values of *Lines of Context* and *Lines to Recite*. 163 | However, increasing those values 164 | merely increases the number of lines that appear on each card, 165 | keeping the number of cards and the amount of overlap the same, 166 | whereas grouping lines 167 | results in generating fewer cards that have less overlap. 168 | The best way to understand this is by example. 169 | Say we have the following uninspired poem: 170 | :: 171 | 172 | A 173 | B 174 | C 175 | D 176 | E 177 | F 178 | G 179 | H 180 | 181 | With the lines in groups of two using the settings described above, 182 | we would get the following cards: 183 | :: 184 | 185 | [Beginning] ==> A B 186 | [Beginning] A B ==> C D 187 | A B C D ==> E F 188 | ...et cetera 189 | 190 | If we instead were to set *Lines in Groups of* to 1, 191 | *Lines of Context* to 4, 192 | and *Lines to Recite* to 2, 193 | we would get: 194 | :: 195 | 196 | [Beginning] ==> A B 197 | [Beginning] A => B C 198 | [Beginning] A B => C D 199 | [Beginning] A B C => D E 200 | A B C D => E F 201 | B C D E => F G 202 | ...et cetera 203 | 204 | *New in LPCG 1.3.* 205 | 206 | 207 | Editing LPCG notes 208 | ================== 209 | 210 | Sooner or later you will probably find 211 | that you made a typo in one of your poems. 212 | To correct the typo completely, 213 | you must *search for the typo in the browser*, 214 | rather than just pressing edit, 215 | since the typo will be included on several generated notes. 216 | -------------------------------------------------------------------------------- /designer/import_dialog.ui: -------------------------------------------------------------------------------- 1 | 2 | 3 | Dialog 4 | 5 | 6 | 7 | 0 8 | 0 9 | 450 10 | 528 11 | 12 | 13 | 14 | LPCG – Import Lyrics/Poetry 15 | 16 | 17 | true 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | &Title 29 | 30 | 31 | titleBox 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | &Author (optional) 46 | 47 | 48 | authorBox 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | Ta&gs (optional) 63 | 64 | 65 | tagsBox 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | Lines of Conte&xt 76 | 77 | 78 | contextLinesSpin 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 70 87 | 0 88 | 89 | 90 | 91 | Number of context lines to show on the question side of the cards. 92 | 93 | 94 | 1 95 | 96 | 97 | 20 98 | 99 | 100 | 2 101 | 102 | 103 | 104 | 105 | 106 | 107 | Lines to &Recite 108 | 109 | 110 | reciteLinesSpin 111 | 112 | 113 | 114 | 115 | 116 | 117 | Number of occluded lines shown on the answer side of each card. 118 | 119 | 120 | 1 121 | 122 | 123 | 10 124 | 125 | 126 | 127 | 128 | 129 | 130 | Lines in Gro&ups of 131 | 132 | 133 | groupLinesSpin 134 | 135 | 136 | 137 | 138 | 139 | 140 | 1 141 | 142 | 143 | 10 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | &Poem: 153 | 154 | 155 | textBox 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | &Help 168 | 169 | 170 | 171 | 172 | 173 | 174 | Replace the contents of the poem editor with a text file on your computer. 175 | 176 | 177 | &Open file 178 | 179 | 180 | false 181 | 182 | 183 | false 184 | 185 | 186 | 187 | 188 | 189 | 190 | Qt::Horizontal 191 | 192 | 193 | 194 | 40 195 | 20 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | Generate notes from the text in the poem editor. 204 | 205 | 206 | A&dd notes 207 | 208 | 209 | Ctrl+Return 210 | 211 | 212 | false 213 | 214 | 215 | true 216 | 217 | 218 | false 219 | 220 | 221 | 222 | 223 | 224 | 225 | &Cancel 226 | 227 | 228 | false 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | titleBox 238 | authorBox 239 | tagsBox 240 | contextLinesSpin 241 | reciteLinesSpin 242 | groupLinesSpin 243 | textBox 244 | addCardsButton 245 | cancelButton 246 | helpButton 247 | openFileButton 248 | 249 | 250 | 251 | 252 | -------------------------------------------------------------------------------- /src/gen_notes.py: -------------------------------------------------------------------------------- 1 | from itertools import zip_longest 2 | import re 3 | from typing import Any, Callable, Dict, Iterable, List, Optional, TYPE_CHECKING 4 | 5 | if TYPE_CHECKING: 6 | from anki.notes import Note 7 | 8 | 9 | class PoemLine: 10 | def __init__(self) -> None: 11 | self.predecessor = self # so it's the right type... 12 | self.successor: Optional['PoemLine'] = None 13 | self.seq = -1 14 | 15 | def populate_note(self, note: 'Note', title: str, author: str, tags: List[str], 16 | context_lines: int, recite_lines: int, deck_id: int) -> None: 17 | """ 18 | Fill the _note_ with content testing on the current line. 19 | """ 20 | note.note_type()['did'] = deck_id # type: ignore 21 | note.tags = tags 22 | note['Title'] = title 23 | note['Author'] = author 24 | note['Sequence'] = str(self.seq) 25 | note['Context'] = self._format_context(context_lines) 26 | note['Line'] = self._format_text(recite_lines) 27 | prompt = self._get_prompt(recite_lines) 28 | if prompt is not None: 29 | note['Prompt'] = prompt 30 | 31 | def _format_context(self, context_lines: int): 32 | return ''.join("

%s

" % i for i in self._get_context(context_lines)) 33 | 34 | def _format_text(self, recitation_lines: int): 35 | return ''.join("

%s

" % i for i in self._get_text(recitation_lines)) 36 | 37 | def _get_context(self, _lines: int, _recursing=False) -> List[str]: 38 | """ 39 | Return a list of context lines, including the current line and 40 | (lines - 1) of its predecessors. 41 | """ 42 | raise NotImplementedError 43 | 44 | def _get_text(self, _lines: int) -> List[str]: 45 | """ 46 | Return a list of recitation lines, including the current line and 47 | (lines - 1) of its successors. 48 | """ 49 | raise NotImplementedError 50 | 51 | def _get_prompt(self, configured_recitation_lines: int) -> Optional[str]: 52 | """ 53 | Return a prompt string to be shown on the question side after the 54 | lines of context, or None to use the template default of [...]. This 55 | is currently used to let the user know how many lines to recite, but 56 | could plausibly be used for other things as well in the future. 57 | """ 58 | raise NotImplementedError 59 | 60 | 61 | class Beginning(PoemLine): 62 | """ 63 | A dummy node indicating the beginning of the poem. It's included only so 64 | it can polymorphically have its context and sequence retrieved. 65 | Attempting to do anything else with the node is an error. 66 | """ 67 | def __init__(self): 68 | super().__init__() 69 | self.seq = 0 70 | self.text = "[Beginning]" 71 | 72 | def _get_context(self, _lines: int, _recursing=False) -> List[str]: 73 | return [self.text] 74 | 75 | def _get_text(self, _lines: int) -> List[str]: 76 | """ 77 | The Beginning node has no defined successors, as it's not a line 78 | we'll ever be asked to recite and thus we never need to know what its 79 | text property is -- the first line we would ever be asked to recite 80 | would be the following line. 81 | """ 82 | raise NotImplementedError 83 | 84 | def populate_note(self, note: 'Note', title: str, author: str, tags: List[str], 85 | context_lines: int, recite_lines: int, deck_id: int) -> None: 86 | raise AssertionError("The Beginning node cannot be used to populate a note.") 87 | 88 | 89 | class SingleLine(PoemLine): 90 | """ 91 | A single line in a typical poem. It has text, a sequence number, a 92 | predecessor (possibly the Beginning node, but never None), and if it's 93 | not the last line of the poem, a successor. 94 | """ 95 | def __init__(self, text: str, predecessor: 'PoemLine') -> None: 96 | super().__init__() 97 | self.text = text 98 | self.predecessor = predecessor 99 | self.seq = self.predecessor.seq + 1 100 | 101 | def _get_context(self, lines: int, recursing=False) -> List[str]: 102 | if lines == 0: 103 | return [self.text] 104 | elif not recursing: 105 | return self.predecessor._get_context(lines - 1, True) 106 | else: 107 | return self.predecessor._get_context(lines - 1, True) + [self.text] 108 | 109 | def _get_text(self, lines: int) -> List[str]: 110 | if lines == 1 or self.successor is None: 111 | return [self.text] 112 | else: 113 | return [self.text] + self.successor._get_text(lines - 1) 114 | 115 | def _get_prompt(self, configured_recitation_lines: int) -> Optional[str]: 116 | # It's important to calculate the lines_to_recite for _this_ instance 117 | # instead of just getting the configuration parameter, as if we're at 118 | # the end it may be fewer. 119 | lines_to_recite = len(self._get_text(configured_recitation_lines)) 120 | if lines_to_recite == 1: 121 | return None 122 | else: 123 | return f"[...{lines_to_recite}]" 124 | 125 | 126 | class GroupedLine(PoemLine): 127 | r""" 128 | A virtual "line" in a poem that has grouping set, so that multiple short 129 | lines can be treated as one line by LPCG. It consists of multiple text lines. 130 | 131 | The difference between grouped lines and ordinary lines with double the 132 | context and recitation values is that there is no overlapping. So this with 133 | default context and recitation values and a group of 2 yields only 3 notes, 134 | whereas a context of 4 and recitation of 2 would result in 6 notes: 135 | 136 | /A 137 | \B 138 | /C 139 | \D 140 | /E 141 | \F 142 | """ 143 | def __init__(self, text: List[str], predecessor: 'PoemLine') -> None: 144 | super().__init__() 145 | self.text_lines = text 146 | self.predecessor = predecessor 147 | self.seq = self.predecessor.seq + 1 148 | 149 | def _get_context(self, lines: int, recursing=False) -> List[str]: 150 | if lines == 0: 151 | return self.text_lines 152 | elif not recursing: 153 | return self.predecessor._get_context(lines - 1, True) 154 | else: 155 | return self.predecessor._get_context(lines - 1, True) + self.text_lines 156 | 157 | def _get_text(self, lines: int) -> List[str]: 158 | if lines == 1 or self.successor is None: 159 | return self.text_lines 160 | else: 161 | return self.text_lines + self.successor._get_text(lines - 1) 162 | 163 | def _get_prompt(self, configured_recitation_lines: int) -> Optional[str]: 164 | lines_to_recite = len(self._get_text(configured_recitation_lines)) 165 | if lines_to_recite == 1: 166 | return None 167 | else: 168 | return f"[...{lines_to_recite}]" 169 | 170 | 171 | def groups_of_n(iterable: Iterable, n: int) -> Iterable: 172 | """ 173 | s -> (s0,s1,s2,...sn-1), (sn,sn+1,sn+2,...s2n-1), (s2n,s2n+1,s2n+2,...s3n-1), ... 174 | 175 | Credit: https://stackoverflow.com/questions/5389507/iterating-over-every-two-elements-in-a-list 176 | """ 177 | return zip_longest(*[iter(iterable)]*n) 178 | 179 | 180 | def _poemlines_from_textlines(text_lines: List[str], group_lines: int) -> List[PoemLine]: 181 | """ 182 | Given a list of cleansed text lines, create a list of PoemLine objects 183 | from it. These are each capable of constructing a correct note testing 184 | themselves when the to_note() method is called on them. 185 | """ 186 | beginning = Beginning() 187 | lines: List[PoemLine] = [] # does not include beginning, as it's not actually a line 188 | pred: PoemLine = beginning 189 | poem_line: PoemLine 190 | 191 | if group_lines == 1: 192 | for text_line in text_lines: 193 | poem_line = SingleLine(text_line, pred) 194 | lines.append(poem_line) 195 | pred.successor = poem_line 196 | pred = poem_line 197 | else: 198 | for line_set in groups_of_n(text_lines, group_lines): 199 | poem_line = GroupedLine([i for i in line_set if i is not None], pred) 200 | lines.append(poem_line) 201 | pred.successor = poem_line 202 | pred = poem_line 203 | return lines 204 | 205 | 206 | def cleanse_text(string: str, config: Dict[str, Any]) -> List[str]: 207 | """ 208 | Munge raw text from the poem editor into a list of lines that can be 209 | directly made into notes. 210 | """ 211 | def _normalize_blank_lines(text_lines): 212 | # remove consecutive lone newlines 213 | new_text = [] 214 | last_line = "" 215 | for i in text_lines: 216 | if last_line.strip() or i.strip(): 217 | new_text.append(i) 218 | last_line = i 219 | # remove lone newlines at beginning and end 220 | for i in (0, -1): 221 | if not new_text[i].strip(): 222 | del new_text[i] 223 | return new_text 224 | 225 | text = string.splitlines() 226 | # record a level of indentation if appropriate 227 | text = [re.sub(r'^[ \t]+', r'', i) for i in text] 228 | # remove comments and normalize blank lines 229 | text = [i.strip() for i in text if not i.startswith("#")] 230 | text = [re.sub(r'\s*\#.*$', '', i) for i in text] 231 | text = _normalize_blank_lines(text) 232 | # add end-of-stanza/poem markers where appropriate 233 | for i in range(len(text)): 234 | if i == len(text) - 1: 235 | text[i] += config['endOfTextMarker'] 236 | elif not text[i+1].strip(): 237 | text[i] += config['endOfStanzaMarker'] 238 | # entirely remove all blank lines 239 | text = [i for i in text if i.strip()] 240 | # replace s with valid CSS 241 | text = [re.sub(r'^(.*)$', r'\1', i) 242 | for i in text] 243 | return text 244 | 245 | 246 | def add_notes(col: Any, note_constructor: Callable, 247 | title: str, author:str, tags: List[str], text: List[str], 248 | deck_id: int, context_lines: int, group_lines: int, 249 | recite_lines: int): 250 | """ 251 | Generate notes from the given title, author, tags, poem text, and number of 252 | lines of context. Return the number of notes added. 253 | 254 | Return the number of notes added. 255 | 256 | Raises KeyError if the note type is missing fields, which I've seen 257 | happen a couple times when users accidentally edited the note type. The 258 | caller should offer an appropriate error message in this case. 259 | """ 260 | added = 0 261 | for line in _poemlines_from_textlines(text, group_lines): 262 | n = note_constructor(col, col.models.by_name("LPCG 1.0")) 263 | line.populate_note(n, title, author, tags, context_lines, recite_lines, deck_id) 264 | col.addNote(n) 265 | added += 1 266 | return added 267 | -------------------------------------------------------------------------------- /src/models.py: -------------------------------------------------------------------------------- 1 | """ 2 | trmodels.py - self-constructing definitions of Anki models (note types) 3 | 4 | Creating a note type in Anki is a procedural operation, which is inconvenient 5 | and difficult to read when note types need to be defined in source code 6 | rather than through the GUI. This module allows note types to be defined 7 | declaratively. 8 | 9 | It first defines TemplateData and ModelData classes which contain the logic 10 | for creating templates and note types, then subclasses which define the 11 | options and templates for each note type our application needs to create and 12 | manage. A framework for checking if note types exist and have the expected 13 | fields, and for changing between note types defined here, is also provided. 14 | 15 | These classes are a bit unusual in that they are never instantiated and have 16 | no instance methods or variables. The class structure is just used as a 17 | convenient way to inherit construction logic and fields and group related 18 | information together. 19 | 20 | This mini-framework was originally created for TiddlyRemember and is 21 | presented in slightly altered form here. The third project should combine the 22 | two versions and create a standardized system! 23 | """ 24 | from abc import ABC 25 | import inspect 26 | import re 27 | from textwrap import dedent 28 | from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Type 29 | import sys 30 | 31 | import aqt 32 | from aqt.utils import askUser, showInfo 33 | from anki.consts import MODEL_CLOZE 34 | from anki.models import TemplateDict as AnkiTemplate 35 | from anki.models import NotetypeDict as AnkiModel 36 | 37 | 38 | class TemplateData(ABC): 39 | """ 40 | Self-constructing definition for templates. 41 | """ 42 | name: str 43 | front: str 44 | back: str 45 | 46 | @classmethod 47 | def to_template(cls) -> AnkiTemplate: 48 | "Create and return an Anki template object for this model definition." 49 | assert aqt.mw is not None, "Tried to use models before Anki is initialized!" 50 | mm = aqt.mw.col.models 51 | t = mm.new(cls.name) 52 | t['qfmt'] = dedent(cls.front).strip() 53 | t['afmt'] = dedent(cls.back).strip() 54 | return t 55 | 56 | 57 | class ModelData(ABC): 58 | """ 59 | Self-constructing definition for models. 60 | """ 61 | name: str 62 | fields: Tuple[str, ...] 63 | templates: Tuple[Type[TemplateData]] 64 | styling: str 65 | sort_field: str 66 | is_cloze: bool 67 | version: str 68 | upgrades: Tuple[Tuple[str, str, Callable[[AnkiModel], None]], ...] 69 | 70 | @classmethod 71 | def to_model(cls) -> Tuple[AnkiModel, str]: 72 | """ 73 | Create and return a pair of (Anki model object, version spec) 74 | for this model definition. 75 | """ 76 | assert aqt.mw is not None, "Tried to use models before Anki is initialized!" 77 | mm = aqt.mw.col.models 78 | model = mm.new(cls.name) 79 | for i in cls.fields: 80 | field = mm.new_field(i) 81 | mm.add_field(model, field) 82 | for template in cls.templates: 83 | t = template.to_template() 84 | mm.addTemplate(model, t) 85 | model['css'] = dedent(cls.styling).strip() 86 | model['sortf'] = cls.fields.index(cls.sort_field) 87 | if cls.is_cloze: 88 | model['type'] = MODEL_CLOZE 89 | return model, cls.version 90 | 91 | @classmethod 92 | def upgrade_from(cls, current_version: str) -> str: 93 | """ 94 | Given that the model is at version current_version (typically stored 95 | in the add-on config), run all functions possible in the updates tuple 96 | of the model. The updates tuple must be presented in chronological order; 97 | each element is itself a 3-element tuple: 98 | 99 | [0] Version number to upgrade from 100 | [1] Version number to upgrade to 101 | [2] Function taking one argument, the model, and mutating it as required; 102 | raises an exception if update failed. 103 | 104 | Returns the new version the model is at. 105 | """ 106 | assert aqt.mw is not None, "Tried to use models before Anki is initialized!" 107 | model = aqt.mw.col.models.by_name(cls.name) 108 | 109 | at_version = current_version 110 | for cur_ver, new_ver, func in cls.upgrades: 111 | if at_version == cur_ver: 112 | func(model) 113 | at_version = new_ver 114 | if at_version != current_version: 115 | aqt.mw.col.models.save(model) 116 | return at_version 117 | 118 | @classmethod 119 | def in_collection(cls) -> bool: 120 | """ 121 | Determine if a model by this name exists already in the current 122 | Anki collection. 123 | """ 124 | assert aqt.mw is not None, "Tried to use models before Anki is initialized!" 125 | mm = aqt.mw.col.models 126 | model = mm.by_name(cls.name) 127 | return model is not None 128 | 129 | @classmethod 130 | def can_upgrade(cls, current_version: str) -> bool: 131 | """ 132 | Return True if we know of a newer version of the model than supplied. 133 | """ 134 | if cls.is_at_version(current_version): 135 | return False 136 | for cur_ver, _, __ in cls.upgrades: 137 | if current_version == cur_ver: 138 | return True 139 | return False 140 | 141 | @classmethod 142 | def is_at_version(cls, current_version: str) -> bool: 143 | "Return True if this model is at the version current_version." 144 | return current_version == cls.version 145 | 146 | 147 | def upgrade_none_to_onethreeoh(mod): 148 | "Upgrade LPCG model from unversioned to version 1.3.0." 149 | mm = aqt.mw.col.models 150 | field = mm.new_field("Prompt") 151 | mm.add_field(mod, field) 152 | 153 | if '.nightMode .cloze' not in mod['css']: 154 | mod['css'] += "\n\n" 155 | mod['css'] += dedent(""" 156 | .nightMode .cloze { 157 | filter: invert(85%); 158 | } 159 | """).strip() 160 | mod['css'] = mod['css'].replace('margin-left: -30px;', '') 161 | 162 | assert len(mod['tmpls']) == 1, "LPCG note type has extra templates!" 163 | mod['tmpls'][0]['qfmt'] = mod['tmpls'][0]['qfmt'].replace( 164 | '[...]', 165 | dedent(''' 166 |
167 | {{#Prompt}}{{Prompt}}{{/Prompt}} 168 | {{^Prompt}}[...]{{/Prompt}} 169 |
170 | ''').strip() 171 | ) 172 | mod['tmpls'][0]['afmt'] = mod['tmpls'][0]['afmt'].replace( 173 | '{{Line}}', 174 | '
{{Line}}
' 175 | ) 176 | 177 | 178 | def upgrade_onethreeoh_to_onefouroh(mod): 179 | "Upgrade LPCG model from 1.3.0 to version 1.4.0." 180 | mm = aqt.mw.col.models 181 | mm.add_field(mod, mm.new_field("Author")) 182 | 183 | mod['css'] = mod['css'].replace('.title {', '.title, .author {') 184 | 185 | assert len(mod['tmpls']) == 1, "LPCG note type has extra templates!" 186 | for side in ['qfmt', 'afmt']: 187 | mod['tmpls'][0][side] = mod['tmpls'][0][side].replace( 188 | '
{{Title}} {{Sequence}}
', 189 | dedent(''' 190 |
{{Title}} {{Sequence}}
191 | {{#Author}}
{{Author}}
{{/Author}} 192 | ''').strip() 193 | ) 194 | 195 | 196 | class LpcgOne(ModelData): 197 | class LpcgOneTemplate(TemplateData): 198 | name = "LPCG1" 199 | front = """ 200 |
{{Title}} {{Sequence}}
201 | {{#Author}}
{{Author}}
{{/Author}} 202 | 203 |
204 | 205 |
206 | {{Context}} 207 |
208 | {{#Prompt}}{{Prompt}}{{/Prompt}} 209 | {{^Prompt}}[...]{{/Prompt}} 210 |
211 |
212 | """ 213 | back = """ 214 |
{{Title}} {{Sequence}}
215 | {{#Author}}
{{Author}}
{{/Author}} 216 | 217 |
218 | 219 |
220 | {{Context}} 221 |
{{Line}}
222 |
223 | """ 224 | 225 | name = "LPCG 1.0" 226 | fields = ("Line", "Context", "Title", "Author", "Sequence", "Prompt") 227 | templates = (LpcgOneTemplate,) 228 | styling = """ 229 | .card { 230 | font-family: arial; 231 | font-size: 20px; 232 | color: black; 233 | background-color: white; 234 | } 235 | 236 | p { 237 | margin-top: 0px; 238 | margin-bottom: 0px; 239 | } 240 | 241 | .lines { 242 | text-align: left; 243 | margin-left: 30px; 244 | text-indent: -30px; 245 | margin-right: 30px; 246 | } 247 | 248 | .cloze { 249 | font-weight: bold; 250 | color: blue; 251 | } 252 | 253 | .nightMode .cloze { 254 | filter: invert(85%); 255 | } 256 | 257 | .title, .author { 258 | text-align: center; 259 | font-size: small; 260 | } 261 | 262 | .indent { 263 | margin-left: 60px; 264 | } 265 | """ 266 | sort_field = "Sequence" 267 | is_cloze = False 268 | version = "1.4.0" 269 | upgrades = ( 270 | ("none", "1.3.0", upgrade_none_to_onethreeoh), 271 | ("1.3.0", "1.4.0", upgrade_onethreeoh_to_onefouroh), 272 | ) 273 | 274 | 275 | def ensure_note_type() -> None: 276 | """ 277 | Create or update the LPCG note type as needed. 278 | """ 279 | assert aqt.mw is not None, "Tried to use models before Anki is initialized!" 280 | mod = LpcgOne 281 | 282 | if not mod.in_collection(): 283 | model_data, new_version = mod.to_model() 284 | aqt.mw.col.models.add(model_data) 285 | aqt.mw.col.set_config('lpcg_model_version', new_version) 286 | return 287 | 288 | # "none": the "version number" pre-versioning 289 | current_version = aqt.mw.col.get_config('lpcg_model_version', default="none") 290 | if mod.can_upgrade(current_version): 291 | r = askUser("In order to import new notes in this version of LPCG, " 292 | "your LPCG note type needs to be upgraded. " 293 | "This may require a full sync of your collection upon completion. " 294 | "Would you like to upgrade the note type now? " 295 | "If you say no, you will be asked again next time you start Anki.") 296 | if r: 297 | new_version = mod.upgrade_from(current_version) 298 | aqt.mw.col.set_config('lpcg_model_version', new_version) 299 | showInfo("Your LPCG note type was upgraded successfully. " 300 | "Please take a moment to ensure your LPCG cards " 301 | "are still displaying as expected so you can restore from a backup " 302 | "in the event something is not working correctly.") 303 | return 304 | 305 | assert mod.is_at_version(aqt.mw.col.get_config('lpcg_model_version')), \ 306 | "Your LPCG model is out of date, but I couldn't find a valid upgrade path. " \ 307 | "You are likely to encounter issues. " \ 308 | "Please contact the developer for assistance resolving this problem." 309 | -------------------------------------------------------------------------------- /test/test_gen_notes.py: -------------------------------------------------------------------------------- 1 | from textwrap import dedent 2 | from typing import Sequence 3 | 4 | import pytest 5 | 6 | # pylint: disable=unused-wildcard-import 7 | from src.gen_notes import * 8 | 9 | 10 | MOCK_CLEANSE_CONFIG = {'endOfTextMarker': 'X', 'endOfStanzaMarker': 'Y'} 11 | INDENT_HTML_START = '' 12 | INDENT_HTML_END = '' 13 | 14 | 15 | @pytest.mark.parametrize("n,expected", [ 16 | (2, ((1, 2), (3, 4), (5, 6))), 17 | (3, ((1, 2, 3), (4, 5, 6))), 18 | (4, ((1, 2, 3, 4), (5, 6, None, None))), 19 | ]) 20 | def test_groups_of_n(n: int, expected: Sequence[int]): 21 | original_iterable = (1, 2, 3, 4, 5, 6) 22 | grouped = groups_of_n(original_iterable, n) 23 | for actual, exp in zip(grouped, expected): 24 | assert actual == exp 25 | 26 | 27 | class TestCleanseText: 28 | def test_cleanse(self): 29 | limerick = dedent(""" 30 | # Ulrich Neisser 31 | You can get a good deal from rehearsal 32 | If it just has the proper dispersal. 33 | 34 | You would just be an ass 35 | To do it en masse, 36 | Your remembering would turn out much worsal. 37 | """).strip() 38 | result = cleanse_text(limerick, MOCK_CLEANSE_CONFIG) 39 | 40 | assert result[0] == "You can get a good deal from rehearsal" 41 | assert result[1] == "If it just has the proper dispersal.Y" 42 | assert result[2] == f"{INDENT_HTML_START}You would just be an ass{INDENT_HTML_END}" 43 | assert result[3] == f"{INDENT_HTML_START}To do it en masse,{INDENT_HTML_END}" 44 | assert result[4] == "Your remembering would turn out much worsal.X" 45 | 46 | 47 | def test_cleanse_multiple_blank_lines(self): 48 | test_case = dedent(""" 49 | # This has lots of blank lines and comments that could mess things up. 50 | Here is a first line 51 | 52 | 53 | And here is a second line. 54 | And a third line. 55 | # Now a comment 56 | 57 | # And another comment 58 | 59 | And here, at last, is the end of the poem. 60 | """).strip() + "\n\n" 61 | result = cleanse_text(test_case, MOCK_CLEANSE_CONFIG) 62 | 63 | assert result[0] == "Here is a first lineY" 64 | assert result[1] == "And here is a second line." 65 | assert result[2] == "And a third line.Y" 66 | assert result[3] == "And here, at last, is the end of the poem.X" 67 | 68 | 69 | def test_unequal_indentation(self): 70 | limerick = dedent(""" 71 | # Ulrich Neisser 72 | You can get a good deal from rehearsal 73 | If it just has the proper dispersal. 74 | 75 | You would just be an ass 76 | To do it en masse, 77 | Your remembering would turn out much worsal. 78 | """).strip() 79 | result = cleanse_text(limerick, MOCK_CLEANSE_CONFIG) 80 | 81 | assert result[0] == "You can get a good deal from rehearsal" 82 | assert result[1] == "If it just has the proper dispersal.Y" 83 | assert result[2] == f"{INDENT_HTML_START}You would just be an ass{INDENT_HTML_END}" 84 | assert result[3] == f"{INDENT_HTML_START}To do it en masse,{INDENT_HTML_END}" 85 | assert result[4] == "Your remembering would turn out much worsal.X" 86 | 87 | 88 | def test_line_comment(self): 89 | limerick = dedent(""" 90 | Here is a line # with a comment 91 | And a second line. 92 | """).strip() 93 | result = cleanse_text(limerick, MOCK_CLEANSE_CONFIG) 94 | 95 | assert result[0] == "Here is a line" 96 | assert result[1] == "And a second line.X" 97 | 98 | 99 | test_poem = dedent(""" 100 | # Samuel Longfellow 101 | 'Tis winter now; the fallen snow 102 | Has left the heavens all coldly clear; 103 | Through leafless boughs the sharp winds blow, 104 | And all the earth lies dead and drear. 105 | 106 | And yet God's love is not withdrawn; 107 | His life within the keen air breathes; 108 | God's beauty paints the crimson dawn, 109 | And clothes the boughs with glittering wreaths. 110 | 111 | And though abroad the sharp winds blow, 112 | And skies are chill, and frosts are keen, 113 | Home closer draws her circle now, 114 | And warmer glows her light within. 115 | 116 | O God! Who gives the winter's cold 117 | As well as summer's joyous rays, 118 | Us warmly in Thy love enfold, 119 | And keep us through life's wintry days. 120 | """).strip() 121 | 122 | 123 | class MockModel: 124 | def __init__(self): 125 | self.properties = {} 126 | 127 | def __call__(self): 128 | return self.properties 129 | 130 | def by_name(self, name): 131 | return self 132 | 133 | 134 | class MockCollection: 135 | def __init__(self): 136 | self.notes = [] 137 | 138 | def addNote(self, note): 139 | self.notes.append(note) 140 | 141 | @property 142 | def models(self): 143 | return MockModel() 144 | 145 | 146 | class MockNote: 147 | def __init__(self, collection, ntype): 148 | self.collection = collection 149 | self.note_type = ntype 150 | self.tags = [] 151 | self.properties = {} 152 | 153 | def __getitem__(self, item): 154 | return self.properties[item] 155 | 156 | def __setitem__(self, item, value): 157 | self.properties[item] = value 158 | 159 | def __delitem__(self, item): 160 | del self.properties[item] 161 | 162 | def __contains__(self, item): 163 | return item in self.properties 164 | 165 | 166 | @pytest.fixture 167 | def mock_note(): 168 | col = MockCollection() 169 | note_constructor = MockNote 170 | title = "'Tis Winter" 171 | author = "Samuel Longfellow" 172 | tags = ["poem", "test"] 173 | deck_id = 1 174 | context_lines = 2 175 | recite_lines = 1 176 | group_lines = 1 177 | text = cleanse_text(test_poem, MOCK_CLEANSE_CONFIG) 178 | return dict(locals()) 179 | 180 | 181 | def test_render_default_settings(mock_note): 182 | col = mock_note['col'] 183 | num_added = add_notes(**mock_note) 184 | 185 | assert num_added == 16 186 | assert len(col.notes) == 16 187 | 188 | assert col.notes[0]['Title'] == mock_note['title'] 189 | assert col.notes[0]['Author'] == mock_note['author'] 190 | assert col.notes[0].tags == mock_note['tags'] 191 | assert col.notes[0]['Sequence'] == "1" 192 | assert col.notes[0]['Context'] == "

[Beginning]

" 193 | assert col.notes[0]['Line'] == "

'Tis winter now; the fallen snow

" 194 | assert 'Prompt' not in col.notes[0] 195 | 196 | assert col.notes[3]['Title'] == mock_note['title'] 197 | assert col.notes[3]['Author'] == mock_note['author'] 198 | assert col.notes[3].tags == mock_note['tags'] 199 | assert col.notes[3]['Sequence'] == "4" 200 | assert col.notes[3]['Context'] == ( 201 | "

Has left the heavens all coldly clear;

" 202 | "

Through leafless boughs the sharp winds blow,

" 203 | ) 204 | assert col.notes[3]['Line'] == "

And all the earth lies dead and drear.Y

" 205 | assert 'Prompt' not in col.notes[3] 206 | 207 | 208 | ### GROUPS ### 209 | def test_render_groups_of_two(mock_note): 210 | col = mock_note['col'] 211 | mock_note['group_lines'] = 2 212 | num_added = add_notes(**mock_note) 213 | 214 | assert num_added == 8 215 | assert len(col.notes) == 8 216 | 217 | # We won't bother testing title and tags for further items. 218 | assert col.notes[0]['Sequence'] == "1" 219 | assert col.notes[0]['Context'] == "

[Beginning]

" 220 | assert col.notes[0]['Line'] == ( 221 | "

'Tis winter now; the fallen snow

" 222 | "

Has left the heavens all coldly clear;

" 223 | ) 224 | assert col.notes[0]['Prompt'] == "[...2]" 225 | 226 | assert col.notes[1]['Sequence'] == "2" 227 | assert col.notes[1]['Context'] == ( 228 | "

[Beginning]

" 229 | "

'Tis winter now; the fallen snow

" 230 | "

Has left the heavens all coldly clear;

" 231 | ) 232 | assert col.notes[1]['Line'] == ( 233 | "

Through leafless boughs the sharp winds blow,

" 234 | "

And all the earth lies dead and drear.Y

" 235 | ) 236 | assert col.notes[1]['Prompt'] == "[...2]" 237 | 238 | 239 | def test_render_groups_of_three(mock_note): 240 | col = mock_note['col'] 241 | mock_note['group_lines'] = 3 242 | num_added = add_notes(**mock_note) 243 | 244 | assert num_added == 6 245 | assert len(col.notes) == 6 246 | 247 | assert col.notes[0]['Title'] == mock_note['title'] 248 | assert col.notes[0]['Author'] == mock_note['author'] 249 | assert col.notes[0].tags == mock_note['tags'] 250 | assert col.notes[0]['Sequence'] == "1" 251 | assert col.notes[0]['Context'] == "

[Beginning]

" 252 | assert col.notes[0]['Line'] == ( 253 | "

'Tis winter now; the fallen snow

" 254 | "

Has left the heavens all coldly clear;

" 255 | "

Through leafless boughs the sharp winds blow,

" 256 | ) 257 | assert col.notes[0]['Prompt'] == "[...3]" 258 | 259 | # Last item has six lines of context but only one recitation line, with no prompt 260 | # (as 16 % 3 = 1). 261 | assert col.notes[5]['Sequence'] == "6" 262 | assert col.notes[5]['Context'] == ( 263 | "

And skies are chill, and frosts are keen,

" 264 | "

Home closer draws her circle now,

" 265 | "

And warmer glows her light within.Y

" 266 | "

O God! Who gives the winter's cold

" 267 | "

As well as summer's joyous rays,

" 268 | "

Us warmly in Thy love enfold,

" 269 | ) 270 | assert col.notes[5]['Line'] == "

And keep us through life's wintry days.X

" 271 | assert 'Prompt' not in col.notes[5], col.notes[5]['Prompt'] 272 | 273 | 274 | ### CONTEXT LINES ### 275 | def test_render_three_context_lines(mock_note): 276 | col = mock_note['col'] 277 | mock_note['context_lines'] = 3 278 | num_added = add_notes(**mock_note) 279 | 280 | assert num_added == 16 281 | assert len(col.notes) == 16 282 | 283 | assert col.notes[0]['Sequence'] == "1" 284 | assert col.notes[0]['Context'] == "

[Beginning]

" 285 | assert col.notes[0]['Line'] == "

'Tis winter now; the fallen snow

" 286 | assert 'Prompt' not in col.notes[0] 287 | 288 | assert col.notes[1]['Context'] == ( 289 | "

[Beginning]

" 290 | "

'Tis winter now; the fallen snow

" 291 | ) 292 | assert col.notes[1]['Line'] == "

Has left the heavens all coldly clear;

" 293 | 294 | assert col.notes[2]['Context'] == ( 295 | "

[Beginning]

" 296 | "

'Tis winter now; the fallen snow

" 297 | "

Has left the heavens all coldly clear;

" 298 | ) 299 | assert col.notes[2]['Line'] == "

Through leafless boughs the sharp winds blow,

" 300 | 301 | assert col.notes[3]['Context'] == ( 302 | "

'Tis winter now; the fallen snow

" 303 | "

Has left the heavens all coldly clear;

" 304 | "

Through leafless boughs the sharp winds blow,

" 305 | ) 306 | assert col.notes[3]['Line'] == "

And all the earth lies dead and drear.Y

" 307 | 308 | assert col.notes[4]['Context'] == ( 309 | "

Has left the heavens all coldly clear;

" 310 | "

Through leafless boughs the sharp winds blow,

" 311 | "

And all the earth lies dead and drear.Y

" 312 | ) 313 | assert col.notes[4]['Line'] == "

And yet God's love is not withdrawn;

" 314 | 315 | 316 | ### RECITATION LINES ### 317 | def test_render_two_recitation_lines(mock_note): 318 | col = mock_note['col'] 319 | mock_note['recite_lines'] = 2 320 | num_added = add_notes(**mock_note) 321 | 322 | # Unlike grouping, having more recitation lines involves overlap, 323 | # so there are still 16 notes. 324 | assert num_added == 16 325 | assert len(col.notes) == 16 326 | 327 | assert col.notes[0]['Context'] == "

[Beginning]

" 328 | assert col.notes[0]['Line'] == ( 329 | "

'Tis winter now; the fallen snow

" 330 | "

Has left the heavens all coldly clear;

" 331 | ) 332 | assert col.notes[0]['Prompt'] == "[...2]" 333 | 334 | assert col.notes[1]['Context'] == ( 335 | "

[Beginning]

" 336 | "

'Tis winter now; the fallen snow

" 337 | ) 338 | assert col.notes[1]['Line'] == ( 339 | "

Has left the heavens all coldly clear;

" 340 | "

Through leafless boughs the sharp winds blow,

" 341 | ) 342 | 343 | assert col.notes[2]['Context'] == ( 344 | "

'Tis winter now; the fallen snow

" 345 | "

Has left the heavens all coldly clear;

" 346 | ) 347 | assert col.notes[2]['Line'] == ( 348 | "

Through leafless boughs the sharp winds blow,

" 349 | "

And all the earth lies dead and drear.Y

" 350 | ) 351 | 352 | # The very last line will request a single recitation. 353 | assert col.notes[-1]['Context'] == ( 354 | "

As well as summer's joyous rays,

" 355 | "

Us warmly in Thy love enfold,

" 356 | ) 357 | assert col.notes[-1]['Line'] == "

And keep us through life's wintry days.X

" 358 | assert 'Prompt' not in col.notes[-1] 359 | 360 | 361 | ### TRIPLE PLAY ### 362 | def test_render_increase_all_options(mock_note): 363 | """ 364 | In this configuration, we have lines grouped into sets of 2 -- so 8 365 | virtual lines -- and then we show 3 virtual lines as context (6 physical 366 | lines) and request 2 virtual lines for recitation (4 physical lines). 367 | """ 368 | col = mock_note['col'] 369 | mock_note['context_lines'] = 3 370 | mock_note['recite_lines'] = 2 371 | mock_note['group_lines'] = 2 372 | num_added = add_notes(**mock_note) 373 | 374 | # Only grouping reduces the number; the other parameters cause only 375 | # additional overlap. 376 | assert num_added == 8 377 | assert len(col.notes) == 8 378 | 379 | assert col.notes[0]['Context'] == "

[Beginning]

" 380 | assert col.notes[0]['Line'] == ( 381 | "

'Tis winter now; the fallen snow

" 382 | "

Has left the heavens all coldly clear;

" 383 | "

Through leafless boughs the sharp winds blow,

" 384 | "

And all the earth lies dead and drear.Y

" 385 | ) 386 | assert col.notes[0]['Prompt'] == "[...4]" 387 | 388 | assert col.notes[1]['Context'] == ( 389 | "

[Beginning]

" 390 | "

'Tis winter now; the fallen snow

" 391 | "

Has left the heavens all coldly clear;

" 392 | ) 393 | assert col.notes[1]['Line'] == ( 394 | "

Through leafless boughs the sharp winds blow,

" 395 | "

And all the earth lies dead and drear.Y

" 396 | "

And yet God's love is not withdrawn;

" 397 | "

His life within the keen air breathes;

" 398 | ) 399 | assert col.notes[1]['Prompt'] == "[...4]" 400 | 401 | assert col.notes[2]['Context'] == ( 402 | "

[Beginning]

" 403 | "

'Tis winter now; the fallen snow

" 404 | "

Has left the heavens all coldly clear;

" 405 | "

Through leafless boughs the sharp winds blow,

" 406 | "

And all the earth lies dead and drear.Y

" 407 | ) 408 | assert col.notes[2]['Line'] == ( 409 | "

And yet God's love is not withdrawn;

" 410 | "

His life within the keen air breathes;

" 411 | "

God's beauty paints the crimson dawn,

" 412 | "

And clothes the boughs with glittering wreaths.Y

" 413 | ) 414 | assert col.notes[2]['Prompt'] == "[...4]" 415 | 416 | assert col.notes[3]['Context'] == ( 417 | "

'Tis winter now; the fallen snow

" 418 | "

Has left the heavens all coldly clear;

" 419 | "

Through leafless boughs the sharp winds blow,

" 420 | "

And all the earth lies dead and drear.Y

" 421 | "

And yet God's love is not withdrawn;

" 422 | "

His life within the keen air breathes;

" 423 | ) 424 | assert col.notes[3]['Line'] == ( 425 | "

God's beauty paints the crimson dawn,

" 426 | "

And clothes the boughs with glittering wreaths.Y

" 427 | "

And though abroad the sharp winds blow,

" 428 | "

And skies are chill, and frosts are keen,

" 429 | ) 430 | assert col.notes[3]['Prompt'] == "[...4]" 431 | 432 | assert col.notes[6]['Context'] == ( 433 | "

God's beauty paints the crimson dawn,

" 434 | "

And clothes the boughs with glittering wreaths.Y

" 435 | "

And though abroad the sharp winds blow,

" 436 | "

And skies are chill, and frosts are keen,

" 437 | "

Home closer draws her circle now,

" 438 | "

And warmer glows her light within.Y

" 439 | ) 440 | assert col.notes[6]['Line'] == ( 441 | "

O God! Who gives the winter's cold

" 442 | "

As well as summer's joyous rays,

" 443 | "

Us warmly in Thy love enfold,

" 444 | "

And keep us through life's wintry days.X

" 445 | ) 446 | assert col.notes[6]['Prompt'] == "[...4]" 447 | 448 | assert col.notes[7]['Context'] == ( 449 | "

And though abroad the sharp winds blow,

" 450 | "

And skies are chill, and frosts are keen,

" 451 | "

Home closer draws her circle now,

" 452 | "

And warmer glows her light within.Y

" 453 | "

O God! Who gives the winter's cold

" 454 | "

As well as summer's joyous rays,

" 455 | ) 456 | assert col.notes[7]['Line'] == ( 457 | "

Us warmly in Thy love enfold,

" 458 | "

And keep us through life's wintry days.X

" 459 | ) 460 | assert col.notes[7]['Prompt'] == "[...2]" 461 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------