{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "from bs4 import BeautifulSoup, NavigableString, Tag\n", "import ebooklib\n", "from ebooklib import epub\n", "import os\n", "import re\n", "from typing import Generator, List\n", "\n", "def parse_ebook_html(ebook_path: str, try_chapter : bool = False) -> Generator[tuple, None, None]:\n", " \"\"\"\n", " Parses the HTML content of an EPUB file, yielding only text content from each
block,\n", " while skipping specific elements with class 'calibre3' but considering valid text that follows.\n", "\n", " Parameters:\n", " - ebook_path (str): The path to the EPUB file.\n", " - try_chapter (bool): If True, the first paragraph of each chapter will be used to determine the chapter title.\n", "\n", " Returns:\n", " - text_generator (Generator[tuple, None, None]): A generator yielding text content.\n", " \"\"\"\n", " book = epub.read_epub(ebook_path)\n", " basename = os.path.basename(ebook_path)\n", " noext = os.path.splitext(basename)[0]\n", " chapter_idx = 0\n", " paragraph_idx = 0\n", " cumsum_char_count = 0\n", " for item in book.get_items_of_type(ebooklib.ITEM_DOCUMENT):\n", " content = item.get_content().decode('utf-8')\n", " results = list(html_tokenizer(content, try_chapter))\n", " if len(results) == 0:\n", " continue\n", " chapter_idx += 1\n", " for row in results:\n", " if len(row[1]) == 0:\n", " continue\n", " paragraph_idx += 1\n", " char_count = len((row[1]))\n", " cumsum_char_count += char_count\n", " row = [noext, paragraph_idx, chapter_idx] + list(row[:]) + [char_count, cumsum_char_count]\n", " yield tuple(row)\n", "\n", "def html_tokenizer(html_content: str, try_chapter) -> Generator[tuple, None, None]:\n", " \"\"\"\n", " Generator function to tokenize HTML content, yielding text content from each