コード例 #1
0
ファイル: formatter.py プロジェクト: dmzkrsk/fb2merge
    def format(self, author):
        ao = {
            'first-name': '',
            'last-name': '',
            'middle-name': '',
            'nickname': '',
            }
        for t in author:
            for k in ao:
                if t.tag == fb2tag(k):
                    ao[k] = (t.text or '').strip()
                    break

        if self._reverse:
            nname = '%(last-name)s %(first-name)s %(middle-name)s' % ao
        else:
            nname = '%(first-name)s %(middle-name)s %(last-name)s' % ao
        nname = re.sub('\s{2,}', ' ', nname.strip())
        if not ao['nickname']:
            return nname

        if nname:
            return nname + ' (%(nickname)s)' % ao
        else:
            return ao['nickname']
コード例 #2
0
ファイル: book.py プロジェクト: dmzkrsk/fb2merge
    def getImageData(self, ref):
        if ref is None or X_REF not in ref.attrib:
            return None

        href = ref.attrib[X_REF][1:]
        binaries = [
            x for x in
            self._tree.getiterator(fb2tag('binary'))
            if x.attrib.get('id') == href and x.attrib.get('content-type', '').lower().startswith('image/')
        ]

        if not binaries:
            raise ImageLoadException('No binaries found for #%s' % href)
        elif len(binaries) > 1:
            raise ImageLoadException('Multiple binaries found for #%s' % href)

        bin = binaries[0]
        rawImage = base64.b64decode(bin.text)
        return rawImage
コード例 #3
0
ファイル: book.py プロジェクト: dmzkrsk/fb2merge
    def setYearAggressive(self, year):
        year_str = str(year)

        tree_changed = False
        for info in _DS_INFO(self._tree):
            dt = dropwhile(lambda x: x.tag in _TAGS_BEFORE_DATE, info).next()
            if dt.tag == fb2tag('date'):
                if dt.text == year_str and dt.attrib.get('value') is None:
                    continue

                if 'value' in dt.attrib:
                    del dt.attrib['value']

                dt.text = year_str
                tree_changed = True
            else:
                dt.addprevious(_e('date', year_str))
                tree_changed = True

        return tree_changed
コード例 #4
0
ファイル: book.py プロジェクト: dmzkrsk/fb2merge
    def getYearAggressive(self):
        dates = []
        for ti in [TITLE_INFO, SRC_TITLE_INFO]:
            ti_item = ti(self._tree)
            if not ti_item:
                continue

            dates.extend(
                filter(None, (x.attrib.get('value', x.text) for x in ti_item[0] if x.tag == fb2tag('date')))
            )

        xy = lambda x: max(map(int, re.split('\D+', x)))
        dv = filter(None, map(xy, dates))
        return min(dv) if dv else None
コード例 #5
0
ファイル: fb2merge.py プロジェクト: dmzkrsk/fb2merge
def main(sys_argv):
    options, args = parser.parse_args(sys_argv[1:])
    logger.setLevel(logging.DEBUG if options.debug else logging.INFO)

    if not options.output:
        raise ArgumentsException('No output specified')
    if not options.title:
        raise ArgumentsException('No book title')

    books_combined = BookCreator(options.title.decode('utf-8'))
    bookstats = BookStat()

    for bookID, file in enumerate(chain(*imap(glob.iglob, args))):
        if not os.path.isfile(file):
            logger.info('Skipping %s: not a file' % file)
            continue

        try:
            book = Book.fromFile(file, True)
        except NotAFBZException:
            logger.warning('Not a valid fbz file: ' + file)
            continue

        bodies = book.getBodies()

        if len(bodies) > 2 or len(bodies) == 0:
            logger.error("Book %s has %d bodies" % (file, len(bodies)))
            continue

        if len(bodies) == 2 and bodies[1].attrib.get('name') != 'notes':
            logger.error("Book %s second body bodies is not [notes]" % file)
            continue

        ## #############################

        bookinfo = bookstats.process(book, bookID)

        ##################

        sp = Section(bodies[0])
        new_section = sp.rebuild_section(
            annotation=book.getAnnotation(),
            cover=book.getCover(),
            epigraphs=book.getEpigraphs(),
            title=book.getTitle(),
        )

        booknotes = []
        if len(bodies) > 1:
            for _pos, noteSection in enumerate(bodies[1]):
                if not noteSection.tag == fb2tag('section'):
                    if _pos or not noteSection.tag == fb2tag('title') :
                        logger.warn("Wrong note: %s in %s" % (noteSection.tag, file))
                    continue

                booknotes.append(noteSection)

        books_combined.insertBook(bookinfo.key, new_section, booknotes)

        for binary in book.getBinaries():
            bID = binary.attrib['id']
            if not bookinfo.referes(bID):
                logger.info('Skipping binary %s' % bID)
                continue

            books_combined.addBinary(binary)

    try:
        book_output = books_combined.finish(bookstats)
        book_output.saveAs(options.output, options.zip)
    except DocumentInvalid, e:
        logger.critical('Not a valid book: %s' % e)