Browse Source

Make it an installable package.

feature/create-config
gabriel becker 2 years ago
parent
commit
93259f9aed
  1. 160
      .gitignore
  2. 8
      LICENCE
  3. 0
      ankimaker/commands/from_epub.py
  4. 62
      ankimaker/tasks/basic_csv_to_anki.py
  5. 3
      pyproject.toml
  6. 3
      requirements.txt
  7. 32
      setup.py
  8. 1
      src/ankimaker/__init__.py
  9. 3
      src/ankimaker/cli.py
  10. 3
      src/ankimaker/commands/__init__.py
  11. 6
      src/ankimaker/commands/from_csv.py
  12. 2
      src/ankimaker/config/__init__.py
  13. 23
      src/ankimaker/config/configuration.py
  14. 19
      src/ankimaker/config/load_config.py
  15. 5
      src/ankimaker/generator/__init__.py
  16. 19
      src/ankimaker/generator/deck.py
  17. 0
      src/ankimaker/tasks/__init__.py
  18. 69
      src/ankimaker/tasks/basic_csv_to_anki.py

160
.gitignore vendored

@ -0,0 +1,160 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

8
LICENCE

@ -0,0 +1,8 @@
Copyright 2014 Pallets
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

0
ankimaker/commands/from_epub.py

62
ankimaker/tasks/basic_csv_to_anki.py

@ -1,62 +0,0 @@
import genanki
import pandas as pd
def create_model():
my_model = genanki.Model(
1607392319,
'Simple Model',
fields=[
{'name': 'Question'},
{'name': 'Answer'},
],
templates=[
{
'name': 'Card 1',
'qfmt': '{{Question}}',
'afmt': '{{FrontSide}}<hr id="answer">{{Answer}}',
},
])
return my_model
def create_note(model, fields):
note = genanki.Note(
model=model,
fields=fields
)
return note
def create_deck(name):
deck = genanki.Deck(
2059400110,
name
)
return deck
def save_deck(deck, destination):
my_package = genanki.Package(deck)
# my_package.media_files = ['sound.mp3', 'images/image.jpg']
my_package.write_to_file(destination)
def load_csv(path):
df = pd.read_csv(path, header=None)
return df
def add_df_to_deck(df: pd.DataFrame, deck: genanki.Deck):
model = create_model()
for x in df.to_dict('records'):
note = create_note(model, fields=(x[2], x[3]))
deck.add_note(note)
return deck
def basic_pandas_to_anki(csv_path, output_path, name):
df = load_csv(csv_path)
deck = create_deck(name)
add_df_to_deck(df, deck)
save_deck(deck, output_path)

3
pyproject.toml

@ -0,0 +1,3 @@
[build-system]
requires = ["setuptools"]
build-backend = "setuptools.build_meta"

3
requirements.txt

@ -1,3 +1,4 @@
click click
genanki genanki
pandas pandas
pyyaml

32
setup.py

@ -0,0 +1,32 @@
from setuptools import setup, find_packages
def readme():
with open("README.md") as f:
return f.read()
setup(
name='ankimaker',
version='0.0.4',
description='Makes anki with files',
url="https://git.lgoon.xyz/gabriel/ankimaker",
license="BSD-3-Clause",
license_files='LICENSE',
packages=find_packages('src', include=['ankimaker*']),
package_dir={"": "src"},
entry_points={
'console_scripts': [
'ankimaker=ankimaker.cli:main',
]
},
include_package_data=True,
long_description=readme(),
install_requirements=[
"click",
"genanki",
"pandas",
"pyyaml",
],
long_description_content_type='text/markdown',
)

1
src/ankimaker/__init__.py

@ -0,0 +1 @@
from .cli import main

3
ankimaker/__main__.py → src/ankimaker/cli.py

@ -4,6 +4,3 @@ from ankimaker.commands import cli
def main(): def main():
cli(prog_name='ankimaker') cli(prog_name='ankimaker')
if __name__ == '__main__':
main()

3
ankimaker/commands/__init__.py → src/ankimaker/commands/__init__.py

@ -4,4 +4,5 @@ import click
def cli(): def cli():
pass pass
from ankimaker.commands.from_csv import generate_anki
from ..commands.from_csv import generate_anki

6
ankimaker/commands/from_csv.py → src/ankimaker/commands/from_csv.py

@ -5,8 +5,8 @@ from ankimaker.tasks import basic_pandas_to_anki
@cli.command('csv') @cli.command('csv')
@click.option('-i', '--input', 'input_file', type=click.Path(exists=True)) @click.argument('-i', '--input', 'input_file', type=click.Path(exists=True))
@click.option('-o', '--output', 'output_file', type=click.Path(exists=False)) @click.argument('-o', '--output', 'output_file', type=click.Path(exists=False))
@click.option('-c', '--conf', 'config_file', default=None, type=click.STRING) @click.option('-c', '--conf', 'config_file', default=None, type=click.STRING)
@click.option('-n', '--name', 'name', default=None, type=click.STRING) @click.option('-n', '--name', 'name', default=None, type=click.STRING)
def generate_anki( def generate_anki(
@ -18,7 +18,7 @@ def generate_anki(
output_file = parse_output(output_file) output_file = parse_output(output_file)
if name is None: if name is None:
name = get_name_from_output(output_file) name = get_name_from_output(output_file)
basic_pandas_to_anki(input_file, output_file, name) basic_pandas_to_anki(input_file, output_file, name, config_file)
def parse_output(filename): def parse_output(filename):

2
src/ankimaker/config/__init__.py

@ -0,0 +1,2 @@
from .load_config import load_config_file
from .configuration import AnkimakerConfig as Config

23
src/ankimaker/config/configuration.py

@ -0,0 +1,23 @@
import yaml
class AnkimakerConfig(yaml.YAMLObject):
yaml_tag = '!ankimakerconfig'
header = None
question_column = None
answer_column = None
separators = ','
def __init__(self, header=None, answer_column=None, question_column=None):
AnkimakerConfig.answer_column = answer_column
AnkimakerConfig.question_column = question_column
AnkimakerConfig.header = header
AnkimakerConfig.AnkimakerConfig = AnkimakerConfig
@staticmethod
def loader(configuration_content):
content = configuration_content['AnkimakerConfig']
AnkimakerConfig.header = content.header
AnkimakerConfig.question_column = content.question_column
AnkimakerConfig.answer_column = content.answer_column
AnkimakerConfig.separators = content.separators

19
src/ankimaker/config/load_config.py

@ -0,0 +1,19 @@
from pathlib import Path
import yaml
from .configuration import AnkimakerConfig
def load_config_file(file_path: str):
"""
Load yaml configuration file.
:param file_path: Path to yaml file with configuration
:return: Dict config
"""
file_path = Path(file_path)
assert file_path.exists()
assert file_path.is_file()
with open(file_path, 'r') as file:
yaml.add_path_resolver('!ankimakerconfig', ['AnkimakerConfig'], dict)
configuration = yaml.load(file.read(), Loader=yaml.Loader)
AnkimakerConfig.loader(configuration)

5
src/ankimaker/generator/__init__.py

@ -0,0 +1,5 @@
from . import (
deck,
# models,
# card
)

19
src/ankimaker/generator/deck.py

@ -0,0 +1,19 @@
import uuid
import genanki
def create_deck(name, deck_id=None):
if deck_id is None:
deck_id = int(int(uuid.uuid4())//1e20)
deck = genanki.Deck(
deck_id,
name
)
return deck
def save_deck(deck, destination, media_files=None):
my_package = genanki.Package(deck)
if media_files is not None:
my_package.media_files = ['sound.mp3', 'images/image.jpg']
my_package.write_to_file(destination)

0
ankimaker/tasks/__init__.py → src/ankimaker/tasks/__init__.py

69
src/ankimaker/tasks/basic_csv_to_anki.py

@ -0,0 +1,69 @@
import genanki
import pandas as pd
from ankimaker.config import Config
from ankimaker import generator, config
def create_model():
my_model = genanki.Model(
1607392319,
'Simple Model',
fields=[
{'name': 'Question'},
{'name': 'Answer'},
],
templates=[
{
'name': 'Card 1',
'qfmt': '<div style="text-align: center;">{{Question}}</div>',
'afmt': '{{FrontSide}}<hr id="answer"><div style="text-align: center;">{{Answer}}</div>',
},
])
return my_model
def create_note(model, fields):
note = genanki.Note(
model=model,
fields=fields
)
return note
def load_csv(path):
df = pd.read_csv(path, header=Config.header, sep=Config.separators)
df_columns_are_unnamed = all(map(lambda x: str(x).isnumeric(), df.columns))
if df_columns_are_unnamed:
Config.answer_column = int(Config.answer_column)
Config.question_column = int(Config.question_column)
return df
def add_df_to_deck(df: pd.DataFrame, deck: genanki.Deck):
model = create_model()
for entry in df.to_dict('records'):
question = entry[Config.question_column]
answer = entry[Config.answer_column]
content_fields = (question, answer)
note = create_note(model, fields=content_fields)
deck.add_note(note)
return deck
def handle_config(config_file_path):
if config_file_path is None:
Config.header = None
Config.question_column = 0
Config.answer_column = 1
else:
config.load_config_file(config_file_path)
def basic_pandas_to_anki(csv_path, output_path, name, config_file_path):
handle_config(config_file_path)
df = load_csv(csv_path)
deck = generator.deck.create_deck(name)
add_df_to_deck(df, deck)
generator.deck.save_deck(deck, output_path)
Loading…
Cancel
Save