예제 #1
1
def to_epub(parser):
    """
    God this function is ugly.
    """
    author = parser.author
    title = parser.title

    book = epub.EpubBook()
    book.set_title(title)
    book.set_language('en')
    book.add_author(author)
    chapters_info = []
    chapters_obj = []
    for chapter in parser.get_chapters_content():
        file_name = 'chapter_%d.xhtml' % chapter['order']
        c = epub.EpubHtml(title=chapter['name'], file_name=file_name)
        c.content = chapter['soup'].prettify()
        chapters_info.append((file_name, title, ''))
        book.add_item(c)
        chapters_obj.append(c)
    for image in parser.processed_images.values():
        img = epub.EpubImage()
        img.file_name = 'images/%s' % image.name
        img.content = open(image.path, 'rb').read()
        book.add_item(img)
    book.toc = (chapters_obj)
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())
    book.spine = ['nav']
    book.spine += chapters_obj
    epub.write_epub(title.replace(' ', '_') + '.epub', book, {})
예제 #2
0
    def bindEpubBook(self):
        intro_page = self.makeIntroPage()
        self.book.add_item(intro_page)

        try:
            self.book.set_cover(
                'cover.jpeg',
                requests.get(self.volume.cover_img,
                             headers=HEADERS,
                             stream=True,
                             timeout=10).content)
        except:
            print('Error: Can not set cover image!')

        self.book.spine = ['cover', intro_page, 'nav']

        self.makeChapter()
        self.book.add_item(epub.EpubNcx())
        self.book.add_item(epub.EpubNav())

        epub_name = self.volume.name + '-' + self.ln.name + '.epub'
        epub_name = epub_name.replace(' ', '-')
        self.setMetadata(epub_name, self.ln.author)

        epub_folder = self.ln.name.replace(' ', '-')
        if not isdir(epub_folder):
            mkdir(epub_folder)

        epub_path = epub_folder + '/' + epub_name
        try:
            epub.write_epub(epub_path, self.book, {})
        except:
            print('Error: Can not write epub file!')
예제 #3
0
    def create_book(self, feed):
        """
        add news on epub format
        :param feed: feed news
        :return: book of news
        """
        logging.debug("Starting format html for epub file")
        self.book.spine = ['nav']
        self.book.toc = []
        for title, date, link, img in zip(feed["Title"], feed["Date"],
                                          feed['Link'], feed["img"]):
            chapter = epub.EpubHtml(title=title, file_name=title + '.xhtml')
            content = f"<h4>{title}</h4><br>Date:{date}<br><a href='{link}'>Link<br><img src='{img}'" \
                      f"alt='NoPhoto' ></a>"
            chapter.set_content(str(content))
            self.book.add_item(chapter)
            self.book.toc.append(chapter)

        self.book.add_item(epub.EpubNcx())
        self.book.add_item(epub.EpubNav())

        style = 'BODY {color: white;}'
        nav_css = epub.EpubItem(uid="style_nav",
                                file_name="style/nav.css",
                                media_type="text/css",
                                content=style)
        self.book.add_item(nav_css)
        logging.debug("Structure for epub file created")
        return self.book
예제 #4
0
def write_epub():
    article_content_list = get_all_article_content()
    book = epub.EpubBook()
    book.set_identifier('id310626')
    book.set_language('en')
    book.add_author('Mark Manson')

    chapter_list = []
    for i, article in enumerate(article_content_list):
        chapter_title = article[0]
        chapter_content = article[1]

        chapter = epub.EpubHtml(title=chapter_title,
                                file_name=str(i),
                                lang='en')
        chapter_list.append(chapter)
        chapter.content = chapter_content
        book.add_item(chapter)

    book.spine = ['nav'] + chapter_list
    book.toc = tuple(chapter_list)
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())
    style = 'BODY {color:white;}'
    nav_css = epub.EpubItem(uid='style_nav',
                            file_name='style/nav.css',
                            media_type='text/css',
                            content=style)
    book.add_item(nav_css)
    epub.write_epub('Manson.epub', book, {})
예제 #5
0
def build_book(articles, filename):
    book = epub.EpubBook()
    book.set_identifier("pinkindbook")
    book.set_title('Pinkind Article Collection')
    book.set_language('en')
    book.add_author('pinkind.dbalan.in')

    style = 'body { font-family: Times, Times New Roman, serif; }'
    nav_css = epub.EpubItem(uid="style_nav",
                            file_name="style/nav.css",
                            media_type="text/css",
                            content=style)

    nav_css = epub.EpubItem(uid="style_nav",
                            file_name="style/nav.css",
                            media_type="text/css",
                            content=style)
    book.add_item(nav_css)

    spine = []
    for art in articles:
        book.add_item(art)
        spine.append(art)

    book.toc = spine

    book.spine = ['nav'] + spine
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())
    epub.write_epub(filename, book)
예제 #6
0
def process_output_to_epub(feed: FeedParserDict, limit: int) -> epub.EpubBook:
    """Form epub structure for epub file"""
    logging.debug("Starting format html for epub file")
    book = epub.EpubBook()
    book.set_identifier('rss news')
    book.set_title(feed.get("feed", {}).get("title"))
    book.set_language('en')

    book.spine = ['nav']
    book.toc = []
    for news in feed.get("entries")[:limit]:
        chapter = epub.EpubHtml(title=news.get("title"),
                                file_name=str(hash(news.get("title"))) +
                                '.xhtml')
        content = BeautifulSoup(
            create_title(news.get("title")) + news.get("summary") +
            create_link(news.get("link")), "lxml")
        images = content.find_all('img')
        process_images(images, book)
        chapter.set_content(str(content))
        book.add_item(chapter)
        book.spine.append(chapter)
        book.toc.append(chapter)

    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())

    style = 'BODY {color: white;}'
    nav_css = epub.EpubItem(uid="style_nav",
                            file_name="style/nav.css",
                            media_type="text/css",
                            content=style)
    book.add_item(nav_css)
    logging.debug("Structure for epub file created")
    return book
def generate_epub(task_id, epub_path):
    """
        Generates a ePub with contents from the chapters_walk()
        :return:
    """
    toc_chapters = (Chapter.query.filter(Chapter.task == task_id)).order_by(
        Chapter.chapter_number)
    novel = NovelInfo.query.get(task_id)
    toc = OrderedDict()
    for chapter in toc_chapters:
        toc[chapter.chapter_number] = chapter.content
    title = novel.title
    book = epub.EpubBook()
    book.set_title(title)
    chapters = []
    for chapter_number, content in toc.items():
        chapter = epub.EpubHtml(title='Chapter ' + str(chapter_number),
                                file_name=str(chapter_number) + '.xhtml',
                                content=simplejson.loads(content))
        book.add_item(chapter)
        chapters.append(chapter)

    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())
    book.spine = ['nav']
    for chapter in chapters:
        book.spine.append(chapter)

    epub.write_epub(os.path.join(epub_path, task_id + '.epub'), book, {})
    return 'Success, chapters collected: ' + str(len(toc.keys()))
예제 #8
0
def output_epub(logger, all_news, about_website=None, file_name=None):
    """Function which create or overwrites EPUB-file with selected fresh or cached news"""
    logger.info('Convert to EPUB-format')
    book = epub.EpubBook()
    if about_website is not None:
        book.set_title(f'RSS news from {about_website["Feed"]}')
    else:
        book.set_title('RSS news')
    book.set_language('en')
    chapters = []
    for news in all_news:
        chapter = epub.EpubHtml(title=f'Chapter of {news["Date"]}', file_name=f'chap {news["Title"]}.xhtml')
        title = f'<h1>{news["Title"]}</h1>'
        if news["Source of image"] == "No image":
            image = ''
        else:
            image = f'<img src="{news["Source of image"]}">'
        string_of_epub_content = f'Date: {news["Date"]}<br/>'
        string_of_epub_content += f'Link: {news["Link"]}<br/>'
        string_of_epub_content += f'Summary: {news["Summary"]}<br/>'
        string_of_epub_content += f'Source of image: {news["Source of image"]}<br/>'
        chapter.content = f'{title}{image}<p align="left">{string_of_epub_content}</p>'
        book.add_item(chapter)
        chapters.append(chapter)
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())
    book.spine = chapters
    logger.info('Creating of PDF-file')
    try:
        epub.write_epub(file_name, book, {})
        logger.info('Converted successfully!')
    except Exception as ex:
        logger.error("Error finding image: {}, {}.".format(type(ex), ex))
예제 #9
0
def create_epub(headers, path):
    """Generate .epub file with news.

    1. Sets the file's metadata.
    2. Creates chapters using values of all tags for each individual news.
    3. Creates navigation.
    4. Write all data to the file in .epub format.
    This file is saved to the directory specified in "output-path" or to
    the directory of executable file if the argument "output-path" wasn't
    provided.
    """
    feed, titles, dates, links, texts = headers[:5]
    book = epub.EpubBook()
    book.set_identifier('Breaking_news')
    book.set_title(feed)
    book.set_language('en')
    book.add_author('User')
    spine = ['nav']
    news_limit = len(titles)
    for i in range(news_limit):
        news = epub.EpubHtml(title=titles[i], file_name='{}.xhtml'.format(i))
        tags = u'<h1>{}</h1><p>{}</p><p>{}</p><p>{}</p>'
        news.content = tags.format(titles[i], dates[i], links[i], texts[i])
        book.add_item(news)
        book.toc.append(epub.Link('{}.xhtml'.format(i), titles[i], titles[i]))
        spine.append(news)
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())
    book.spine = spine
    script_dir = os.path.dirname(__file__)
    if path:
        file_path = os.path.join(path, 'news.epub')
    else:
        file_path = os.path.join(script_dir, 'news.epub')
    epub.write_epub(file_path, book, {})
예제 #10
0
    def export_epub(self, book_name):
        # set metadata

        # add default NCX and Nav file
        self.book.add_item(epub.EpubNcx())
        self.book.add_item(epub.EpubNav())

        # define CSS style
        style = 'BODY {color: white;}'
        nav_css = epub.EpubItem(uid="style_nav",
                                file_name="style/nav.css",
                                media_type="text/css",
                                content=style)

        # add CSS file
        self.book.add_item(nav_css)

        # basic spine
        self.book.spine = ['nav'] + self.chapterinfo

        # write to the file
        output_folder = os.path.join(os.path.dirname(__file__), "output")
        output_file = os.path.join(output_folder, book_name + '.epub')
        try:
            os.mkdir(output_folder)
        except:
            pass
        epub.write_epub(output_file, self.book, {})
        print('輸出路徑: ' + output_file)
        print('Done')
예제 #11
0
def create_book(name, session):
    URL = 'http://volarenovels.com/transmigrator-meets-reincarnator/tmr-chapter-'
    book = epub.EpubBook()

    # set metadata
    book.set_identifier("123456")
    book.set_title(name)
    book.set_language('en')

    chap_list = []
    for chapter in range(1, 361):
        html = get_html(session, URL + str(chapter))
        chap = parse_html(html)
        # create chapter
        c = epub.EpubHtml(title=chap["name"],
                          file_name='chap_' + str(chapter) + '.xhtml',
                          lang='en')
        c.content = "<h1>" + chap["name"] + "</h1>\n" + chap["content"]
        # add chapter
        book.add_item(c)
        chap_list.append(c)

    # define Table Of Contents
    book.toc = tuple(chap_list)

    # add default NCX and Nav file
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())

    # basic spine
    book.spine = ['nav']
    book.spine.extend(chap_list)

    # write to the file
    epub.write_epub('ebooks/' + name + '.epub', book, {})
예제 #12
0
    def union(self, name, size):
        file_name = self._get_valid_name(name)
        book = epub.EpubBook()
        book.set_identifier(file_name)
        book.set_title(file_name)
        book.set_language('zh')
        spine_list = ['nav']
        toc_list = []
        for index in range(1, size + 1):
            content = self.__read_content(index)
            lines_of_content = content.split('\n')
            title = lines_of_content[0]
            ch = epub.EpubHtml(title=title,
                               file_name='ch_{}.xhtml'.format(index),
                               lang='zh')
            ch.content = '<h4>{}</h4>{}'.format(
                title, self.__create_content(lines_of_content[1:]))
            book.add_item(ch)
            spine_list.append(ch)
            toc_list.append(ch)

        book.add_item(epub.EpubNcx())
        book.add_item(epub.EpubNav())
        style = 'BODY {color: white;}'
        nav_css = epub.EpubItem(uid="style_nav",
                                file_name="style/nav.css",
                                media_type="text/css",
                                content=style)
        book.add_item(nav_css)
        book.toc = toc_list
        book.spine = spine_list
        epub.write_epub(self._base_path + file_name + '.epub', book, {})
예제 #13
0
파일: core.py 프로젝트: Ramblurr/hn2ebook
def build_epub(cfg, stories, metadata, out_path):
    comments_css = read_comments_css()
    book = epub.EpubBook()
    book.set_identifier(metadata["identifier"])
    book.set_title(metadata["longtitle"])
    for author in metadata["authors"]:
        book.add_author(author)
    book.set_language(metadata["language"])

    for k, v in metadata["DC"].items():
        book.add_metadata("DC", k, v)

    book.add_metadata("DC", "description", epub_description(metadata))

    book.add_item(comments_css)
    book.set_cover("cover.png", epub_cover(metadata))

    chapters = []
    for idx, story in enumerate(stories):
        chapters.append(build_chapter(cfg, book, idx, len(stories), story))
    toc = []
    for chapter in chapters:
        chapter.add_item(comments_css)
        book.add_item(chapter)
        toc.append(chapter)

    book.toc = toc

    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())

    book.spine = ["nav"] + chapters
    return book
예제 #14
0
def make_epub(id, title, lang, author, cover_path, subtitle):
    book = epub.EpubBook()

    # add metadata
    book.set_identifier('ted_' + id)
    book.set_title(title)
    book.set_language(lang)
    book.add_author(author)

    # add cover image
    book.set_cover("cover.jpg", open(cover_path, 'rb').read())

    chpt = epub.EpubHtml(title='subtitle',
                         file_name='subtitle.xhtml',
                         lang=lang)
    chpt.content = '<html><head></head><body>' + subtitle + '</body></html>'
    book.add_item(chpt)

    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())
    style = 'BODY {color: while;}'
    nav_css = epub.EpubItem(uid="style_nav",
                            file_name="style/nav.css",
                            media_type="text/css",
                            content=style)
    book.add_item(nav_css)
    book.spine = ['nav', chpt]

    epub_path = './epub/' + id + '.epub'
    epub.write_epub(epub_path, book, {})

    return
예제 #15
0
    def build_epub(self):
        logger.info(f"build epub for {self}...")
        self.epub = epub.EpubBook()
        self.epub.set_title(f"{self.novel.title} - {self.title}")
        self.epub.set_identifier(uuid.uuid4().hex)
        self.epub.set_language('en')

        self.epub.add_item(epub.EpubNcx())
        self.epub.add_item(epub.EpubNav())
        self.epub.spine = ['Nav'] + self.build_chapters()

        st = 'p { margin-top: 1em; text-indent: 0em; } ' \
             'h1 {margin-top: 1em; text-align: center} ' \
             'h2 {margin: 2em 0 1em; text-align: center; font-size: 2.5em;} ' \
             'h3 {margin: 0 0 2em; font-weight: normal; text-align:center; font-size: 1.5em; font-style: italic;} ' \
             '.center { text-align: center; } ' \
             '.pagebreak { page-break-before: always; } '
        nav_css = epub.EpubItem(uid="style_nav",
                                file_name="style/nav.css",
                                media_type="text/css",
                                content=st)
        self.epub.add_item(nav_css)

        novel_cache_path = self.novel.get_cache_path()
        epub_file_path = os.path.join(novel_cache_path,
                                      f'{self.epub.title}.epub')

        epub.write_epub(epub_file_path, self.epub, {})
        logger.info(f"Epub for volume {self} done!")
예제 #16
0
def create_book(title=None, volume=None):
    book = epub.EpubBook()
    if title is not None:
        global TITLE
        TITLE = title

    if volume is not None:
        file_name = f'{TITLE[0:15]}{volume}'
    else:
        volume = str(TITLE.split('_')[2])
        file_name = TITLE

    # Epub Metadata
    book.set_title(f'Kyoukai Senjou no Horizon {volume}')
    book.add_author('Minoru Kawakami', 'author', 'aut', 'author')
    book.add_author('Satoyasu', 'illustrator', 'ill', 'illustrator')
    book.set_language('en')
    book.set_identifier(TITLE)

    # Populate Epub with content
    populate_epub(book)
    copy_static_files(book)

    # Add navigation details to Epub
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())

    # Create Epub
    epub.write_epub(f'output/{file_name}.epub', book)
예제 #17
0
파일: download.py 프로젝트: nhanb/mmmdl
def generate_epub(posts):
    book = epub.EpubBook()
    book.set_title('Mr. Money Mustache Blog')
    book.set_language('en')
    book.add_author('Mr. Money Mustache')

    spine_list = ['nav']
    toc = []

    for index, post in enumerate(posts):

        # create chapter
        file_name = '%04d.xhtml' % index
        chapter = epub.EpubHtml(title=post.title, file_name=file_name)
        chapter.content = post.content

        # add chapter
        book.add_item(chapter)

        spine_list.append(chapter)
        toc.append(epub.Link(file_name, post.title, file_name))

    # create table of contents
    book.toc = toc

    # add default NCX and Nav file
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())

    book.spine = spine_list

    # write to the file
    epub.write_epub(os.path.join(DIST_DIR, 'mmm.epub'), book, {})
예제 #18
0
def create_ebook(chapters, author = "Author Authorowski", book_id = "unknown_id", title = "Title unknown"):
    book = epub.EpubBook()
    book.set_identifier(book_id)
    book.set_title(title)
    book.set_language("ru")
    book.add_author(author)

    spine = []
    for chapter in chapters:
        file_name = "chapter_{}.xhtml".format(chapter["id"])
        c = epub.EpubHtml(title=chapter["title"], file_name=file_name, lang="ru")
        c.content = chapter["content"]
        book.add_item(c)
        spine.append(c)
        # toc.append(c)

    book.toc = (epub.Link('intro.xhtml', 'Introduction', 'intro'),
                    (
                        epub.Section('Chapters'),
                        spine,
                    )
                )
    book.spine = spine
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())

    epub.write_epub('test.epub', book, {})

    return
예제 #19
0
    async def run(self):

        book = epub.EpubBook()

        book.set_identifier('tieba_post_%s' % self.opts.post_id)
        book.set_language('zh-cn')

        # remove duplicate file
        book._images = {}

        env = self.jinja_env
        tmpl = env.get_template('chapter.html')

        chapter_list = []
        async for page in self.iter_pages():
            page = await self._trans_page(page, book)

            chapter = await self._make_chapter(page, tmpl)

            book.add_item(chapter)
            chapter_list.append(chapter)

        book.set_title(self.title)

        book.toc = ((
            epub.Section('Languages'),
            chapter_list,
        ), )
        book.add_item(epub.EpubNcx())
        book.add_item(epub.EpubNav())

        book.spine = chapter_list

        epub.write_epub(self.opts.output, book, {})
예제 #20
0
    def run(self):
        """
        Run export process.
        Write epub file.

        :Args:
          - self (:class:`ExportBook`): current class instance
        """
        self.epub_book = ExportEpubBook()

        self._set_metadata()
        self._add_prefix()
        self._create_toc()
        self._create_epub_images()
        self._set_sections_settings()

        self.epub_book.toc = self.toc.values()
        self.epub_book.spine = self.spine
        self.epub_book.add_item(epub.EpubNcx())
        self.epub_book.add_item(epub.EpubNav())

        standard.ATTRIBUTES_GLOBAL = self.ATTRIBUTES_GLOBAL

        epub.write_epub(self.filename, self.epub_book,
                        {'plugins': self.DEFAULT_PLUGINS})
예제 #21
0
파일: digest.py 프로젝트: punchagan/r2k
def _add_navigation(book, chapters):
    book.toc = chapters

    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())

    book.spine += ['nav'] + chapters
예제 #22
0
def html2epub(part_list, dst, **kwargs):

    book = epub.EpubBook()
    book = add_bookinfo(book, **kwargs)

    c_list = []
    toc = []
    for i in range(len(part_list)):
        with io.open(part_list[i], 'r', encoding='utf-8') as f:
            c_soup = BeautifulSoup(f.read(), 'html5lib')
        c = epub.EpubHtml(
            title=u'{0}-part{1}'.format(kwargs['bookname'], i + 1),
            file_name='Text/part{0}.xhtml'.format(i + 1),
        )
        c.content = unicode(c_soup)
        book.add_item(c)
        c_list.append(c)
        toc.append(
            epub.Link(
                'Text/part{0}.xhtml'.format(i + 1),
                'part{0}'.format(i + 1),
                'part{0}'.format(i + 1),
            ))

    book.toc = toc

    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav(file_name='Text/nav.xhtml'))
    book.spine = ['nav'] + c_list

    epub.write_epub(dst, book, {})

    return book
예제 #23
0
def main():
    link = 'https://ranobes.com/ranobe/39855-the-book-eating-magician.html'

    info = getRanobesInfo(get_html(link))
    start_link = info['first_chapter']
    book = epub.EpubBook()
    cover = downloadCover(info['poster_url'])
    book.set_cover("image.jpg", open(cover, 'rb').read())
    book.set_identifier('sample123456')
    book.set_title(info['title'])
    book.set_language(lang)
    book.add_author(info['author'])
    num_chapter = 1
    lstChapter = ['nav']
    navMap = list()
    while start_link:
        html = get_html(start_link)
        chapter, start_link = generateChapter(html, num_chapter, lng=lang)
        book.add_item(chapter)
        lstChapter.append(chapter)
        navMap.append(
            epub.Link('{}.html'.format(num_chapter), chapter.title, 'intro'))
        num_chapter += 1
        print('\rgenerate chapter {} is done!'.format(num_chapter), end='\r')

    print()
    book.toc = navMap
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())
    book.spine = lstChapter
    epub.write_epub('/tmp/{}.epub'.format(info['title']), book, {})
예제 #24
0
    def generate_epub(self):
        """
        Generates a ePub with contents from the chapters_walk()
        :return:
        """
        book = epub.EpubBook()
        book.set_title(self.title)
        chapters = []
        if len(self.toc) < 1:
            self.chapters_walk()
        for chapter in self.toc.keys():
            chapter = str(chapter)
            with open(os.path.join(self.title, chapter + '.html')) as f:
                content = f.read()
            chapter = epub.EpubHtml(title='Chapter ' + chapter,
                                    file_name=chapter + '.xhtml',
                                    content=content)
            book.add_item(chapter)
            chapters.append(chapter)

        book.add_item(epub.EpubNcx())
        book.add_item(epub.EpubNav())
        book.spine = ['nav']
        for chapter in chapters:
            book.spine.append(chapter)

        epub.write_epub(os.path.join(self.title, self.title + '.epub'), book, {})
예제 #25
0
def work(project, _vars):
    book = epub.EpubBook()
    book.set_identifier(_vars.nid)
    book.set_title(_vars.title)
    book.set_language('zh')
    book.add_author(_vars.author)
    book.add_item(epub.EpubNav())
    book.add_item(epub.EpubNcx())
    book.add_item(
        epub.EpubItem(uid="style_nav",
                      file_name="style/style.css",
                      media_type="text/css",
                      content=css))
    book.spine = ['nav']
    book.add_metadata('DC', 'description', _vars.description)
    book.toc = tuple(
        (epub.Section(title),
         tuple(
             build_page(book, f'./{project}/{file}', file.replace(".tex", ""))
             for file in files)) for title, files in _vars.menu.items())
    epub.write_epub(f"./artifacts/{project}/epub/{project}_latest.epub", book,
                    {'epub3_pages': False})
    shutil.copy(
        f"./artifacts/{project}/epub/{project}_latest.epub",
        f"./artifacts/{project}/epub/history/{project}_{datetime.datetime.now().strftime('%y%m%d')}.epub"
    )
    _abspath = os.path.abspath(
        f"./artifacts/{project}/epub/{project}_latest.epub")
    print(f'[{now}] Epub file saved at {_abspath}.')
예제 #26
0
    async def download_book(self,
                      bid: int,
                      fetch_image: bool = False):
        self.book = epub.EpubBook()
        self.sumi = 0
        book_info = self.info(bid)
        if book_info is None:
            return None
        title = book_info['name']
        author = book_info['authors']
        cover_url = book_info['cover']
        self.logger.info('#' * 15 + '开始下载' + '#' * 15)
        self.logger.info('标题: ' + title + " 作者: " + author)
        self.book.set_identifier("%s, %s" % (title, author))
        self.book.set_title(title)
        self.book.add_author(author)
        data_cover = requests.get(cover_url).content
        self.book.set_cover('cover.jpg', data_cover)

        toc = []
        spine = []

        volume_chapters = self.get_volumes_chapters(bid)
        for volume in volume_chapters:
            self.logger.info('volume: ' + volume['volume_name'])
            # 先增加卷
            toc.append((epub.Section(volume['volume_name']), []))
            page_volume = epub.EpubHtml(title=volume['volume_name'], file_name='%s.html' % self.sumi)
            self.sumi = self.sumi + 1
            page_volume.set_content(("<h1>%s</h1><br>" % volume['volume_name']).encode())
            self.book.add_item(page_volume)
            tasks_chapters = []
            sem = asyncio.Semaphore(self.limit_sem_chapter)
            for chapter in volume['chapters']:
                tasks_chapters.append(self.download_chapter(bid, volume['volume_id'], chapter['chapter_id'], sem, fetch_image=fetch_image))
            result_chapters = []
            result_tasks = list((await asyncio.wait(tasks_chapters))[0])
            for task in result_tasks:
                result_chapters.append(task.result())
            result_chapters.sort(key=lambda x: x['chapter_id'], reverse=False)
            # print(result_chapters)
            for i in range(len(result_chapters)):
                chapter = volume['chapters'][i]
                self.logger.info('  chapter: ' + chapter['chapter_name'])
                chapter_content = result_chapters[i]['content']
                page = epub.EpubHtml(title=chapter['chapter_name'], file_name='%s.xhtml' % self.sumi)
                self.sumi = self.sumi + 1
                page.set_content(chapter_content)
                self.book.add_item(page)
                toc[-1][1].append(page)
                spine.append(page)

        self.book.toc = toc
        self.book.spine = spine
        self.book.add_item(epub.EpubNcx())
        self.book.add_item(epub.EpubNav())

        stream = io.BytesIO()
        epub.write_epub(stream, self.book)
        return stream.getvalue()
def create_epub():
    # a bit of epub magic
    book = epub.EpubBook()
    book.set_identifier(f'{start_chapter}-{end_chapter}')
    book.set_title(f'{novel_name}. Chapters {start_chapter}-{end_chapter}')
    book.set_language('en')
    book.spine = ['nav']
    for (dirpath, dirnames, filenames) in os.walk('.\\files_for_epub'):
        for filename in filenames:
            filename_short = filename.split('.')[0]
            f = open('.\\files_for_epub\\' + filename_short + '.xhtml',
                     encoding='utf-8')
            text = f.read()
            f.close()
            c1 = epub.EpubHtml(title=filename_short,
                               file_name=filename,
                               lang='en')
            c1.content = text
            book.add_item(c1)
            book.toc.append(c1)
            book.spine.append(c1)
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())
    epub.write_epub(
        f'{novel_name}. Chapters {start_chapter}-{end_chapter}.epub', book, {})
예제 #28
0
    def bind_and_save_epub(self):
        """
        Finalizes binding of the ebook and saves it to the filesystem.
        """
        print("=== Binding and saving EPUB. ===")
        self.book.toc = (self.weather_link,
                         (epub.Section("Articles"), tuple(self.article_toc_list))
                         )

        # add navigation files
        self.book.add_item(epub.EpubNcx())
        self.book.add_item(epub.EpubNav())

        # define css style
        with open('tmpl/book_style.css', 'r') as css_file:
            style = css_file.read()

        # add css file
        nav_css = epub.EpubItem(uid="style_nav", file_name="style/nav.css", media_type="text/css", content=style)
        self.book.add_item(nav_css)

        self.chaps.insert(0, 'nav')
        self.book.spine = self.chaps

        self.book_filename = 'news_update_{}.epub'.format(self.target_time)
        epub.write_epub(self.book_filename, self.book, {})
        print("Saved as {}.".format(self.book_filename))
예제 #29
0
 def post_process(self):
     self.book.add_item(epub.EpubNcx())
     self.book.add_item(epub.EpubNav())
     self.book.add_item(
         epub.EpubItem(uid="style_nav",
                       file_name="style/nav.css",
                       media_type="text/css",
                       content=css))
예제 #30
0
    def to_epub(self, style=None):
        """Generate `EpubBook` from result of `get_articles`"""
        if not style:
            style = STYLE

        logging.info('Creating book using %s style' % style)
        articles = self.get_articles()

        book = epub.EpubBook()
        book.set_title(self.__class__.name)

        # Create HTML file for each article
        chapters = []
        for i, article in enumerate(articles):
            chapter = epub.EpubHtml(uid=str(i),
                                    title=article.title,
                                    file_name=('%d.xhtml' % i))
            chapter.content = '<html><head>' + \
                '<link rel="stylesheet" href="style/default.css" />' + \
                '</head><body>' + \
                ('<h1>%s</h1>' % article.title) + \
                article.content + '</body></html>'
            chapters.append(chapter)
            book.add_item(chapter)

        # Add generic book metadata
        book.toc = map(
            lambda c: epub.Link(c.get_name(), c.title, str(c.get_id())),
            chapters)
        book.add_item(epub.EpubNcx())
        book.add_item(epub.EpubNav())

        # Add stylesheet
        # Use path if file exists
        if os.path.exists(style):
            style_path = style
            logging.debug('Using custom style %s' % style)
        # Otherwise use preset style
        else:
            style_name = style if style.endswith('.css') else style + '.css'
            style_path = os.path.join(STYLES_PATH, style_name)

            if not os.path.exists(style_path):
                raise Exception('%s is not a preset style' % style)

            logging.debug('Using preset style %s' % style)

        with open(style_path) as f:
            nav_css = epub.EpubItem(uid="style_nav",
                                    file_name="style/default.css",
                                    media_type="text/css",
                                    content=f.read())

        book.add_item(nav_css)

        book.spine = ['nav'] + chapters

        return book