Brettapps's picture
Upload ebook_pipeline.py with huggingface_hub
4da081b verified
Raw
History Blame
2.5 kB
import os
from ebooklib import epub
from fpdf import FPDF
class BookBuilder:
def __init__(self, title, author, description=""):
self.title = title
self.author = author
self.description = description
self.chapters = []
def add_chapter(self, title, content):
self.chapters.append({"title": title, "content": content})
def generate_epub(self, output_path):
book = epub.EpubBook()
book.set_identifier("id123456")
book.set_title(self.title)
book.set_language("en")
book.add_author(self.author)
book.add_metadata("DC", "description", self.description)
spine = ["nav"]
for i, ch in enumerate(self.chapters):
chapter = epub.EpubHtml(title=ch["title"], file_name=f"chap_{i+1}.xhtml", lang="en")
content_html = ch["content"].replace("\n", "</p><p>")
chapter.content = f"<h1>{ch['title']}</h1><p>{content_html}</p>"
book.add_item(chapter)
spine.append(chapter)
book.add_item(epub.EpubNav())
book.add_item(epub.EpubNcx())
book.spine = spine
epub.write_epub(output_path, book, {})
return output_path
def generate_pdf(self, output_path):
pdf = FPDF()
pdf.set_auto_page_break(auto=True, margin=15)
pdf.add_page()
# Title Page
pdf.set_font("Arial", "B", 24)
pdf.cell(200, 40, self.title, ln=True, align="C")
pdf.set_font("Arial", "I", 16)
pdf.cell(200, 10, f"By {self.author}", ln=True, align="C")
pdf.ln(20)
# Chapters
for ch in self.chapters:
pdf.add_page()
pdf.set_font("Arial", "B", 18)
pdf.cell(0, 10, ch["title"], ln=True)
pdf.ln(10)
pdf.set_font("Arial", "", 12)
pdf.multi_cell(0, 10, ch["content"])
pdf.output(output_path)
return output_path
def create_ebook_files(title, author, content_list, base_name="ebook"):
"""
Helper to create both formats.
content_list: List of dicts with 'title' and 'content'.
"""
builder = BookBuilder(title, author)
for item in content_list:
builder.add_chapter(item["title"], item["content"])
os.makedirs("exports", exist_ok=True)
epub_file = builder.generate_epub(f"exports/{base_name}.epub")
pdf_file = builder.generate_pdf(f"exports/{base_name}.pdf")
return epub_file, pdf_file