Beispiel #1
0
def collect_epubs(url_list, username='******', password='******'):
    # Get list
    list = []
    url = url_list[0]
    novel = LightNovel(url, username='******', password='******')
    title, content, images = novel.get_content()
    list.append((title, content, images))
    # open urls in the same driver
    for url in url_list[1:]:
        novel.drive_get(url)
        title, content, images = novel.get_content()
        list.append((title, content, images))
    novel.driver_quit()

    # Make Epub
    print('Making epub...')
    book_name = '{} All.epub'.format(list[0][0])
    if os.path.isfile('downloads/' + book_name):
        os.remove('downloads/' + book_name)
    book = mkepub.Book(book_name)
    # get chapters
    chapters = []
    for title, content, images in list:
        chapters = split_chapters('(?<=>).{0,5}?(章|尾声|后记|目录).*?(?=<)', content)
        if chapters:
            first = book.add_page(title, '<h1>{}</h1>'.format(title))
            for title2, content2 in chapters:
                book.add_page(title=title2, content='<h2>{}</h2>'.format(title2) + content2, parent=first)
        else:
            first = book.add_page(title, '<h1>{}</h1>'.format(title) + content)
        setImages(book, images)
    print(list[0][2][0])
    setCover(book, list[0][2][0])
    book.save('downloads/' + book_name)
    print('{} file complete.'.format(book_name))
Beispiel #2
0
    def makeBookEpub(self):
        book_id = self.content_id
        book_obj = Book.normal.filter(id=book_id).first()
        self.title = book_obj.title

        # 初始化epub
        epub = mkepub.Book(title=book_obj.title, author=str(book_obj.author))

        # 设置封面
        book_cover_path_list = CommonImageSerializer.to_representation(
            book_id=book_id,
            img_type="book_cover",
            only_url=False,
            only_path=True)
        if book_cover_path_list:
            with open(book_cover_path_list[0], 'rb') as file:
                epub.set_cover(file.read())

        # 设置章节
        chapters = BookChapter.normal.filter(book_id=book_id)
        for chapter in chapters:
            epub.add_page(chapter.title, chapter.content)

        filename = os.path.join(settings.UPLOAD_SAVE_PATH,
                                book_obj.title + '.epub')
        self.filename = filename
        epub.save(filename)
        book_obj.is_download = True
        book_obj.save()
Beispiel #3
0
def test_book_simple():
    book = mkepub.Book(title='Simple')
    with open('mkepub/tests/cover.jpg', 'rb') as coverfile:
        book.set_cover(coverfile.read())
    book.add_page('Page 1', 'Content of the first page.')
    book.add_page('Page 2', 'Content of the second page.')
    save_and_check(book)
Beispiel #4
0
def test_book_nested():
    book = mkepub.Book('Nested')
    parent = book.add_page('Parent Page', '0000-0000')
    book.add_page('First Child', 'ヽ(。_°)ノ', parent)
    second_child = book.add_page('Second Child', 'blop', parent)
    book.add_page('Grandkid', 'ooOOoo', second_child)
    save_and_check(book)
Beispiel #5
0
def main():
    # checking the arguments to make sure
    if len(sys.argv) != 2:
        print('wrong number of argument, should only contain the index url')
        exit(-1)

    # first argument - the index page
    index = IndexParser(sys.argv[1])
    index.parse()
    for chapter in index.chapters:
        book_name = f'{index.title} - {chapter}'
        print('-----------')
        print(f'download book: {book_name}')
        print(f'in total {len(index.chapters[chapter])}')

        book = mkepub.Book(title=book_name)

        sub_chapters = index.chapters[chapter]

        for sub_chapter, link in sub_chapters:
            print(f'download chapter: {sub_chapter}')
            page = PageParser(link)
            page.parse()
            book.add_page(title=sub_chapter,
                          content=f'<h1>{sub_chapter}</h1><br/>{page.text}')

        book.save(f'{book_name}.epub')
        print(f'file generated for {book_name}')
Beispiel #6
0
def test_book_with_font():
    book = mkepub.Book('Font')
    book.add_page('Page 1', 'Content')
    with open('mkepub/tests/LinBiolinum_K.woff', 'rb') as file:
        book.add_font('LinBiolinum_K.woff', file.read())
    book.set_stylesheet("""@font-face {
        font-family: "biolinum";
        src: url(../fonts/LinBiolinum_K.woff);}""")
    save_and_check(book)
Beispiel #7
0
    def start(self, title, author, cover=None, style=None):
        self.book = mkepub.Book(title=title, author=author)
        if cover:
            with open(cover, 'rb') as f:
                self.book.set_cover(f.read())
        if style:
            with open(style) as f:
                self.book.set_stylesheet(f.read())

        self.walk_tree("", self.root, None)
Beispiel #8
0
    def makeComicEpub(self):
        comic_id = self.content_id
        comic_obj = Comic.normal.filter(id=comic_id).first()
        self.title = comic_obj.title

        # 初始化epub
        epub = mkepub.Book(title=comic_obj.title, author=str(comic_obj.author))
        logging.info("epub 已经初始化")

        # 设置封面
        comic_cover_path_list = CommonImageSerializer.to_representation(
            comic_id=comic_id,
            img_type="comic_cover",
            quality="title",
            only_url=False,
            only_path=True)
        logging.info(comic_cover_path_list)
        if comic_cover_path_list:
            with open(comic_cover_path_list[0], 'rb') as file:
                epub.set_cover(file.read())
        logging.info("epub 设置封面完成")

        # 设置章节
        chapters = ComicChapter.normal.filter(comic_id=comic_id)
        for chapter in chapters:
            html = ""
            img_lab = '<img src="images/{}" width="100%" alt="You can use images as well">'
            chapter_img_path_list = CommonImageSerializer.to_representation(
                chapter_id=chapter.id,
                img_type="chapter_content",
                quality="thumb",
                only_url=False,
                only_path=True)
            if chapter_img_path_list:
                for img_idx, img_path in enumerate(chapter_img_path_list):
                    file_name = "{}_{}_{}.jpg".format(comic_id, chapter.id,
                                                      img_idx)
                    html += img_lab.format(file_name)
                    with open(img_path, 'rb') as file:
                        epub.add_image(file_name, file.read())
            epub.add_page(chapter.title, html)

        logging.info("epub 完成")
        filename = os.path.join(settings.UPLOAD_SAVE_PATH,
                                comic_obj.title + '.epub')
        if os.path.exists(filename):
            os.remove(filename)
        self.filename = filename
        epub.save(filename)
        comic_obj.is_download = True
        comic_obj.save()
Beispiel #9
0
def test_book_with_dcterms():
    book = mkepub.Book('DCTerms',
                       dcterms={
                           'available': '5',
                           'audience': 'everyone'
                       })
    book.add_page('Page 1', 'Content')
    save_and_check(book)

    expected_strings = [
        '<meta property="dcterms:available">5</meta>\n',
        '<meta property="dcterms:audience">everyone</meta>\n'
    ]
    assert_has_contents(book, 'EPUB/package.opf', expected_strings)
Beispiel #10
0
 def __init__(self, story):
     self.story = story
     self.book = mkepub.Book(
         title=self.story.title,
         author=self.story.author,
         published=datetime.utcfromtimestamp(
             self.story.date_end  # dc:date
         ).isoformat(),
         dcterms={
             "available": datetime.utcfromtimestamp(
                 self.story.date_start
             ).isoformat()
         },
     )
Beispiel #11
0
def test_book_with_anchors():
    text = '''
    <h1 id="anchor-1">Anchor 1</h1> 
    <p> Text for anchor 1 </p>
    <h1 id="anchor-2">Anchor 2</h1>
    <p> Text for anchor 1 </p>
    '''
    book = mkepub.Book('Anchors')
    parent = book.add_page('Parent Page', '0000-0000')
    book.add_page('First Child',
                  text,
                  parent,
                  anchors=[('anchor-1', 'Anchor 1'), ('anchor-2', 'Anchor 2')])
    book.add_page('Third Child',
                  text,
                  parent,
                  anchors={
                      'anchor-1': 'Anchor 1',
                      'anchor-2': 'Anchor 2'
                  })
    save_and_check(book)
Beispiel #12
0
    def convert(self, book: Book) -> str:
        epub = mkepub.Book(title=book.title, author=book.author)
        epub.add_page(
            'Cover',
            self.h1(book.title) + '\n' + self.h2(book.subtitle) + '\n' +
            book.author + '\n')
        epub.add_page(
            self.get_about_the_book_title(book.language),
            self.get_chapter_text(self.get_about_the_book_title(book.language),
                                  book.about_the_book))
        epub.add_page(
            self.get_who_should_read_title(book.language),
            self.get_chapter_text(
                self.get_who_should_read_title(book.language),
                book.who_should_read))
        epub.add_page(
            self.get_about_the_author_title(book.language),
            self.get_chapter_text(
                self.get_about_the_author_title(book.language),
                book.about_the_author))

        for chapter in book.chapters:
            title = str(chapter.order_number) + '. ' + chapter.title
            epub.add_page(title, self.get_chapter_text(title, chapter.text))
        logging.info('Converted book "' + book.author + ' - ' + book.title +
                     '" to EPUB')

        if not os.path.exists(self.foldername):
            os.makedirs(self.foldername)
        complete_filename = self.get_filename(book) + '.' + self.file_suffix
        try:
            epub.save(complete_filename)
            logging.info('Saved book "' + book.author + ' - ' + book.title +
                         '" to "' + complete_filename + '"')
        except FileExistsError:
            logging.warning('Could not save book "' + book.author + ' - ' +
                            book.title + '". File "' + complete_filename +
                            '" exists already.')
        return complete_filename
Beispiel #13
0
def make_epub(title, content, images=[]):
    check_make_dir('downloads/' + title)
    print('Making Epub...')
    # Make Epub File
    if os.path.isfile('downloads/' + title + '.epub'):
        os.remove('downloads/' + title + '.epub')
    book = mkepub.Book(title=title)
    # Split Chapters
    chapters = double_split(title, content)
    # Add Chapters
    addChapter(book, title, chapters)
    # Add Images
    if images != []:
        try:
            setCover(book, images[0])
            setImages(book, images)
        except Exception as e:
            print(e)
            pass

    # Save Book
    book.save('downloads/' + title + '.epub')
    print(title + '.epub file complete.')
Beispiel #14
0
# -*- coding: utf-8 -*-
import mkepub

book = mkepub.Book(title='Advanced Example', author='The Author', subjects=['Văn học', 'Công nghệ'])
# multiple authors can be specified as a list:
# mkepub.Book(title='Advanced Example', authors=['The First Author', 'The Second Author'])
with open('cover.jpg', 'rb') as file:
    book.set_cover(file.read())
with open('style.css') as file:
    book.set_stylesheet(file.read())

first = book.add_page('Chapter 1', 'And so the book begins.')

child = book.add_page('Chapter 1.1', 'Nested TOC is supported.', parent=first)
book.add_page('Chapter 1.1.1', 'Infinite nesting levels', parent=child)
book.add_page('Chapter 1.2', 'In any order you wish.', parent=first)

book.add_page('Chapter 2', 'Use <b>html</b> to make your text <span class="pink">prettier</span>')

book.add_page('Chapter 3: Images', '<p>Chúng ta vẫn biết rằng, làm việc với một đoạn văn bản dễ đọc và rõ nghĩa dễ gây rối trí và cản trở việc tập trung vào yếu tố trình bày văn bản. Lorem Ipsum có ưu điểm hơn so với đoạn văn bản chỉ gồm nội dung kiểu "Nội dung, nội dung, nội dung" là nó khiến văn bản giống thật hơn, bình thường hơn. Nhiều phần mềm thiết kế giao diện web và dàn trang ngày nay đã sử dụng Lorem Ipsum làm đoạn văn bản giả, và nếu bạn thử tìm các đoạn "Lorem ipsum" trên mạng thì sẽ khám phá ra nhiều trang web hiện vẫn đang trong quá trình xây dựng. Có nhiều phiên bản khác nhau đã xuất hiện, đôi khi do vô tình, nhiều khi do cố ý (xen thêm vào những câu hài hước hay thông tục).</p><img src="images/chapter3.jpg" alt="You can use images as well" /><p>Lorem Ipsum chỉ đơn giản là một đoạn văn bản giả, được dùng vào việc trình bày và dàn trang phục vụ cho in ấn. Lorem Ipsum đã được sử dụng như một văn bản chuẩn cho ngành công nghiệp in ấn từ những năm 1500, khi một họa sĩ vô danh ghép nhiều đoạn văn bản với nhau để tạo thành một bản mẫu văn bản. Đoạn văn bản này không những đã tồn tại năm thế kỉ, mà khi được áp dụng vào tin học văn phòng, nội dung của nó vẫn không hề bị thay đổi. Nó đã được phổ biến trong những năm 1960 nhờ việc bán những bản giấy Letraset in những đoạn Lorem Ipsum, và gần đây hơn, được sử dụng trong các ứng dụng dàn trang, như Aldus PageMaker.</p>')
# as long as you add them to the book:
with open('chapter3.jpg', 'rb') as file:
    book.add_image('chapter3.jpg', file.read())

book.save('advanced.epub')
Beispiel #15
0
def test_exception_file_exists():
    book = mkepub.Book('Simple')
    with pytest.raises(FileExistsError):
        book.save('mkepub/tests/simple.epub')
Beispiel #16
0
def test_add_file():
    book = mkepub.Book('File')
    assert not (book.path / 'files').exists()
    with open('mkepub/tests/cover.jpg', 'rb') as file:
        book._add_file('files/cover_1.jpg', file.read())
    assert (book.path / 'EPUB/files/cover_1.jpg').exists()
Beispiel #17
0
 def create_book(self):
     print(">> Creating the book.. ")
     book = mkepub.Book(title=self.title, author=self.author)
     book.add_page(self.title, self.book_content)
     return book
Beispiel #18
0
def test_unsupported_image_format():
    book = mkepub.Book('Untitled')
    book.add_image('bad_image.bmp', b'')
    with pytest.raises(ValueError):
        save_and_check(book)
Beispiel #19
0
def test_book_with_images():
    book = mkepub.Book('Images')
    book.add_page('Cover Page', '<img src="images/cover.jpg"></img>')
    with open('mkepub/tests/cover.jpg', 'rb') as file:
        book.add_image('cover.jpg', file.read())
    save_and_check(book)
Beispiel #20
0
def test_book_no_cover():
    book = mkepub.Book(title='No Cover')
    book.add_page('Page Only', 'This is all the text.')
    save_and_check(book)
Beispiel #21
0
def test_book_multiple_authors():
    book = mkepub.Book(title='Multiple Authors',
                       authors=['This Guy', 'Some Other Guy'])
    book.add_page('Page 1', 'text text. text.')
    save_and_check(book)
Beispiel #22
0
def test_book_one_author():
    book = mkepub.Book(title='One Author', author='This Guy')
    book.add_page('Page 1', 'text text. text.')
    save_and_check(book)