Implement adding of Pokemon chapter to epub including images

main
Felix Martin 2022-10-22 13:20:12 -04:00
parent 10884ce073
commit 951649bd9e
4 changed files with 52 additions and 3 deletions

3
.gitignore vendored
View File

@ -5,6 +5,9 @@ __pycache__/
*$py.class
.vscode
pokemon
tmp
poos.epub
test.epub
# C extensions
*.so

43
src/epub.py Normal file
View File

@ -0,0 +1,43 @@
import ebooklib
import logging
from ebooklib import epub
from src.pokemon import Pokemon
from typing import List
POKEMON_ID_PREFIX = "pokemon-id-"
def create_pokedex_chapter(pokemon: List[Pokemon]) -> epub.EpubHtml:
POKEDEX_TITLE = "Pokedex"
POKEDEX_FILE = "content/np_pokedex.xhtml"
POKEDEX_UID = "np_pokedex"
chapter = epub.EpubHtml(title=POKEDEX_TITLE, file_name=POKEDEX_FILE, uid=POKEDEX_UID)
content = ['<h1>Pokedex</h1>']
for p in pokemon:
content.append(f'<h2 id="{POKEMON_ID_PREFIX}{p.name.lower()}">{p.name}</h2>')
content.append(f' <p><img alt="[Pokemon {p.name}]" src="../{p.img_filepath}"/><br/></p>')
content.append(f' <p>{p.description}</p>')
content.append('')
chapter.content = "\n".join(content)
return chapter
def patch(epub_filepath: str, pokemon: List[Pokemon]):
book = epub.read_epub(epub_filepath)
chapter = create_pokedex_chapter(pokemon)
book.add_item(chapter)
link = epub.Link(chapter.file_name, chapter.title, chapter.id)
book.toc.append(link)
book.spine.append((chapter.id, 'yes'))
for p in pokemon:
image_content = open(p.img_filepath, 'rb').read()
img = epub.EpubItem(uid=p.name, file_name=p.img_filepath, media_type='image/png', content=image_content)
book.add_item(img)
# Link to Pokemon looks like this:
# <a href="np_pokedex.xhtml#pokemon-id-bulbasaur">Bulbasaur!</a>
epub.write_epub('tmp/test.epub', book, {})
logging.info("Written")

View File

@ -1,11 +1,13 @@
import logging
import src.pokemon
import src.epub
def init_logging():
logging.basicConfig(level=logging.DEBUG)
logging.basicConfig(level=logging.INFO)
def main():
init_logging()
p = src.pokemon.get_pokemon()
pokemon = src.pokemon.get_pokemon()
src.epub.patch("poos.epub", pokemon)

View File

@ -73,7 +73,7 @@ def get_pokemon() -> List[Pokemon]:
if os.path.isfile(json_filepath):
p = Pokemon.parse_file(json_filepath)
pokemon.append(p)
logging.info(f"Loaded {p.json_filepath}.")
logging.debug(f"Loaded {p.json_filepath}.")
continue
index = table_row_soup.find_next("td").next_sibling.next_sibling.text.strip()
@ -97,6 +97,7 @@ def get_pokemon() -> List[Pokemon]:
# Filter out speculative Pokemon
pokemon = [p for p in pokemon if not p.description.startswith("This article's contents will change")]
logging.info("Loaded Pokemon.")
return pokemon