37 lines
1000 B
Python
Raw Normal View History

2023-02-03 20:12:03 -08:00
"""Epub Reader.
A parser for epub files.
"""
from pathlib import Path
2023-02-03 23:38:12 -08:00
from typing import Dict, List, Optional
2023-02-03 20:12:03 -08:00
from llama_index.readers.base import BaseReader
from llama_index.readers.schema.base import Document
2023-02-03 20:12:03 -08:00
class EpubReader(BaseReader):
"""Epub Parser."""
def load_data(
self, file: Path, extra_info: Optional[Dict] = None
) -> List[Document]:
"""Parse file."""
2023-02-03 20:41:20 -08:00
import ebooklib
import html2text
2023-02-03 23:38:12 -08:00
from ebooklib import epub
2023-02-03 20:12:03 -08:00
text_list = []
book = epub.read_epub(file, options={"ignore_ncx": True})
# Iterate through all chapters.
for item in book.get_items():
# Chapters are typically located in epub documents items.
if item.get_type() == ebooklib.ITEM_DOCUMENT:
text_list.append(
html2text.html2text(item.get_content().decode("utf-8"))
)
text = "\n".join(text_list)
return [Document(text, extra_info=extra_info)]