Example #1
0
def generate_songbook(songbook, layout):
    """Generate a PDF file by combining a songbook and a layout"""

    content = {}
    content.update(songbook.get_as_json())
    content.update(layout.get_as_json())

    content["datadir"] = settings.SONGS_LIBRARY_DIR

    tmpfile = str(songbook.id) + '-' + str(layout.id) + '-' + hashlib.sha1(str(content).encode()).hexdigest()[0:20]

    try:
        os.chdir(SONGBOOKS_PDFS)
    except OSError:
        os.makedirs(SONGBOOKS_PDFS)
        os.chdir(SONGBOOKS_PDFS)

    builder = SongbookBuilder(content, tmpfile)

    for step in ["tex", "pdf", "sbx", "pdf", "clean"]:
        try:
            builder.build_steps([step])
        except SongbookError as e:
            raise GeneratorError("Error during the step '{0}': {1}".format(step, e))

    return tmpfile + ".pdf"
Example #2
0
def generate():
    """ POST route, generate pdf """

    songs = request.forms.getall('songs')
    subtitle = request.forms.get('subtitle')

    # Generate yaml and parse it
    songbook_yaml = template('songbook_yaml',
                             songs=songs,
                             PATADATA=PATADATA,
                             subtitle=subtitle)
    songbook_raw = yaml.load(songbook_yaml)

    # Create temp directory and operate patacrep magic
    outputdir = tempfile.mkdtemp()
    outputname = 'songbook'
    with cd(outputdir):
        songbook = prepare_songbook(songbook_raw,
                                    outputdir=outputdir,
                                    outputname=outputname,
                                    datadir_prefix=PATADATA)
        songbook['_cache'] = False
        songbook['_error'] = "failonbook"
        builder = SongbookBuilder(songbook)
        builder.unsafe = True
        builder.build_steps(DEFAULT_STEPS)

    # Read outputed PDF and delete temp directory
    with open(os.path.join(outputdir, outputname + '.pdf'), 'rb') as f:
        pdf = f.read()
    shutil.rmtree(outputdir)

    # Send pdf
    response.content_type = 'application/pdf'
    return pdf
Example #3
0
    def compile_songbook_onthefly(base, steps=None):
        """Compile songbook "on the fly": without a physical songbook file."""

        with open(base + ".yaml", mode="r", encoding="utf8") as sbfile:
            sbyaml = yaml.safe_load(sbfile)

        outputdir = os.path.dirname(base)
        outputname = os.path.basename(base)
        datadir_prefix = os.path.join(outputdir, '..')
        songbook = prepare_songbook(sbyaml,
                                    outputdir,
                                    outputname,
                                    datadir_prefix=datadir_prefix)
        songbook['_error'] = "fix"
        songbook['_cache'] = True

        sb_builder = SongbookBuilder(songbook)
        sb_builder.unsafe = True

        with chdir(outputdir):
            # Continuous Integration will be verbose
            if 'CI' in os.environ:
                with logging_reduced(level=logging.DEBUG):
                    sb_builder.build_steps(steps)
            else:
                sb_builder.build_steps(steps)
Example #4
0
def main(args=None):
    """Main function:"""
    if args is None:
        args = sys.argv

    # set script locale to match user's
    try:
        locale.setlocale(locale.LC_ALL, '')
    except locale.Error as error:
        # Locale is not installed on user's system, or wrongly configured.
        LOGGER.error("Locale error: {}\n".format(str(error)))

    options = argument_parser(args[1:])

    songbook_path = options.book[-1]

    # Load the user songbook config
    try:
        songbook = open_songbook(songbook_path)

        # Command line options
        if options.datadir:
            for datadir in reversed(options.datadir):
                songbook['datadir'].insert(0, datadir)
        songbook['_cache'] = options.cache[0]
        songbook['_error'] = options.error[0]

        sb_builder = SongbookBuilder(songbook)
        sb_builder.unsafe = True

        sb_builder.build_steps(options.steps)
    except errors.SongbookError as error:
        LOGGER.error(error)
        if LOGGER.level >= logging.INFO:
            LOGGER.error(
                "Running again with option '-v' may give more information."
                )
        sys.exit(1)
    except KeyboardInterrupt:
        LOGGER.warning("Aborted by user.")
        sys.exit(1)

    sys.exit(0)
Example #5
0
def main(args=None):
    """Main function:"""
    if args is None:
        args = sys.argv

    # set script locale to match user's
    try:
        locale.setlocale(locale.LC_ALL, '')
    except locale.Error as error:
        # Locale is not installed on user's system, or wrongly configured.
        LOGGER.error("Locale error: {}\n".format(str(error)))

    options = argument_parser(args[1:])

    songbook_path = options.book[-1]

    # Load the user songbook config
    try:
        songbook = open_songbook(songbook_path)

        # Command line options
        if options.datadir:
            for datadir in reversed(options.datadir):
                songbook['datadir'].insert(0, datadir)
        songbook['_cache'] = options.cache[0]
        songbook['_error'] = options.error[0]

        sb_builder = SongbookBuilder(songbook)
        sb_builder.unsafe = True

        sb_builder.build_steps(options.steps)
    except errors.SongbookError as error:
        LOGGER.error(error)
        if LOGGER.level >= logging.INFO:
            LOGGER.error(
                "Running again with option '-v' may give more information.")
        sys.exit(1)
    except KeyboardInterrupt:
        LOGGER.warning("Aborted by user.")
        sys.exit(1)

    sys.exit(0)
Example #6
0
def setupSongbook(songbook_path,datadir):
    setLocale()
    global sb_builder
    basename = os.path.basename(songbook_path)[:-3]
    # Load songbook from sb file.
    try:
        with patacrep.encoding.open_read(songbook_path) as songbook_file:
            songbook = json.load(songbook_file)
        if 'encoding' in songbook:
            with patacrep.encoding.open_read(
                songbook_path,
                encoding=songbook['encoding']
                ) as songbook_file:
                songbook = json.load(songbook_file)
    except Exception as error: # pylint: disable=broad-except
        print("Error while loading file '{}'".format(songbook_path))
        print(error)
        # Throw Exception
        return

    # Gathering datadirs
    datadirs = []
    if 'datadir' in songbook:
        # .sg file
        if isinstance(songbook['datadir'], str):
            songbook['datadir'] = [songbook['datadir']]
        datadirs += [
            os.path.join(
                os.path.dirname(os.path.abspath(songbook_path)),
                path
                )
            for path in songbook['datadir']
            ]
    # Default value
    datadirs.append(os.path.dirname(os.path.abspath(songbook_path)))
    songbook['datadir'] = datadirs
    try:
        sb_builder = SongbookBuilder(songbook, basename)
        sb_builder.unsafe = True
    except errors.SongbookError as error:
        print("Error in formation of Songbook Builder")
Example #7
0
    def compile_songbook_onthefly(base, steps=None):
        """Compile songbook "on the fly": without a physical songbook file."""

        with open(base + ".yaml", mode="r", encoding="utf8") as sbfile:
            sbyaml = yaml.load(sbfile)

        outputdir = os.path.dirname(base)
        outputname = os.path.basename(base)
        datadir_prefix = os.path.join(outputdir, '..')
        songbook = prepare_songbook(sbyaml, outputdir, outputname, datadir_prefix=datadir_prefix)
        songbook['_error'] = "fix"
        songbook['_cache'] = True

        sb_builder = SongbookBuilder(songbook)
        sb_builder.unsafe = True

        with chdir(outputdir):
            # Continuous Integration will be verbose
            if 'CI' in os.environ:
                with logging_reduced(level=logging.DEBUG):
                    sb_builder.build_steps(steps)
            else:
                sb_builder.build_steps(steps)