#!/usr/bin/env python # -*- coding: utf-8 -*- import os import re lily_template = """ \chapter {[[title]]} \lilypondfile{[[scorefile]]} ~\\ ~\\ \input{[[lyricfile]]} """ def find_ly_files(path='./scores'): lilyfiles = [] for found_file in os.listdir(path): if found_file.endswith(".ly"): filepath = os.path.join(path, found_file) lilyfiles.append(filepath) return lilyfiles def build_songmap(lilyfiles, lyric_folder='./lyrics'): songmap = [] for scorefile in lilyfiles: filename_with_ext = os.path.basename(scorefile) filename = os.path.splitext(filename_with_ext)[0] lyricfile = os.path.join(lyric_folder, "{0}.tex".format(filename)) title = find_title(scorefile) songmap.append({'scorefile': scorefile, 'lyricfile': lyricfile, 'title': title }) return songmap def find_title(scorefile): with open(scorefile) as opened_file: score = opened_file.read() title = re.findall('title = "(.*)"', score) return title[0] def build_lytex(base_template, songmap): lilychapters = [] for song in sorted(songmap, key=lambda k: k['scorefile']): lilychapter = lily_template.replace('[[title]]', song['title']) lilychapter = lilychapter.replace('[[scorefile]]', song['scorefile']) lilychapter = lilychapter.replace('[[lyricfile]]', song['lyricfile']) lilychapters.append(lilychapter) lilychapters_string = create_lilychapter_string(lilychapters) with open(base_template) as opened_file: template = opened_file.read() template = template.replace('\\musicbooklet', lilychapters_string) return template def create_lilychapter_string(lilychapters): lilychapter_string = '' for lilychapter in lilychapters: lilychapter_string += '{0}\n'.format(lilychapter) return lilychapter_string lilyfiles = find_ly_files() songmap = build_songmap(lilyfiles) lytex_source = build_lytex('singalongs.tex', songmap) print(lytex_source)