예제 #1
0
def makeDepend(sb, library, output):
    name = output[:-2]

    indexPattern = re.compile(r"^[^%]*\\(?:newauthor|new)index\{.*\}\{(.*?)\}")
    lilypondPattern = re.compile(r"^[^%]*\\(?:lilypond)\{(.*?)\}")

    # check for deps (in sb data)
    deps = []
    if sb["songs"] == "all":
        deps += recursiveFind(os.path.join(library, 'songs'), '*.sg')
    else:
        deps += map(lambda x: library + "songs/" + x, sb["songs"])

    # check for lilypond deps (in songs data) if necessary
    lilypond = []
    if "bookoptions" in sb and "lilypond" in sb["bookoptions"]:
        for filename in deps:
            tmpl = open(filename)
            lilypond += matchRegexp(lilypondPattern, tmpl)
            tmpl.close()

    # check for index (in template file)
    if "template" in sb:
        filename = sb["template"]
    else:
        filename = "patacrep.tmpl"
    tmpl = open("templates/" + filename)
    idx = map(lambda x: x.replace("\getname", name),
              matchRegexp(indexPattern, tmpl))
    tmpl.close()

    # write .d file
    out = open(output, 'w')
    out.write('{0} {1} : {2}\n'.format(output, name + ".tex", ' '.join(deps)))
    out.write('{0} : {1}\n'.format(
        name + ".pdf", ' '.join(
            map(lambda x: x + ".sbx", idx) +
            map(lambda x: library + "lilypond/" + x + ".pdf", lilypond))))
    out.write('\t$(LATEX) {0}\n'.format(name + ".tex"))
    out.write('{0} : {1}\n'.format(' '.join(map(lambda x: x + ".sxd", idx)),
                                   name + ".aux"))
    out.close()
예제 #2
0
파일: rules.py 프로젝트: ugleiton/songbook
def main():
    locale.setlocale(locale.LC_ALL, '')
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hf:l:",
                                   ["help", "files=", "log="])
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    songfiles = recursiveFind(os.path.join(library, 'songs'), '*.sg')
    loglevel = "warning"

    for option, arg in opts:
        if option in ("-h", "--help"):
            usage()
            sys.exit()
        elif option in ("-f", "--files"):
            songfiles = glob.glob(arg)
        elif option in ("-l", "--log"):
            loglevel = arg
            numeric_level = getattr(logging, loglevel.upper(), None)
            if not isinstance(numeric_level, int):
                raise ValueError('Invalid log level: %s' % loglevel)
            logging.basicConfig(level=numeric_level,
                                filename='rules.log',
                                filemode='w')
        else:
            assert False, "unhandled option"

    for filename in songfiles:
        with open(filename, 'r+') as songfile:
            logging.info("checking file: " + filename)
            data = songfile.read()
            #no dots for acronyms
            #data = re.sub("(?P<capital_letter>[A-Z])\.","\g<capital_letter>", data)
            data = replace_words(data)
            data = language_rules(data)
            lines = process_lines(data.split('\n'))
            data = "\n".join(lines)
            songfile.seek(0)
            songfile.write(data)
            songfile.truncate()
예제 #3
0
def main():
   locale.setlocale(locale.LC_ALL, '')
   try:
      opts, args = getopt.getopt(sys.argv[1:],
                                 "hf:l:",
                                 ["help", "files=", "log="])
   except getopt.GetoptError:
      usage()
      sys.exit(2)

   songfiles = recursiveFind(os.path.join(library, 'songs'), '*.sg')
   loglevel  = "warning"

   for option, arg in opts:
      if option in ("-h", "--help"):
         usage()
         sys.exit()
      elif option in ("-f", "--files"):
         songfiles = glob.glob(arg)
      elif option in ("-l", "--log"):
         loglevel = arg
         numeric_level = getattr(logging, loglevel.upper(), None)
         if not isinstance(numeric_level, int):
            raise ValueError('Invalid log level: %s' % loglevel)
         logging.basicConfig(level=numeric_level, filename='rules.log', filemode='w')
      else:
         assert False, "unhandled option"

   for filename in songfiles:
      with open(filename, 'r+') as songfile:
         logging.info("checking file: "+filename)
         data = songfile.read()
         #no dots for acronyms
         #data = re.sub("(?P<capital_letter>[A-Z])\.","\g<capital_letter>", data)
         data = replace_words(data)
         data = language_rules(data)
         lines = process_lines(data.split('\n'))
         data = "\n".join(lines)
         songfile.seek(0)
         songfile.write(data)
         songfile.truncate()
예제 #4
0
def makeDepend(sb, library, output):
    name = output[:-2]

    indexPattern = re.compile(r"^[^%]*\\(?:newauthor|new)index\{.*\}\{(.*?)\}")
    lilypondPattern = re.compile(r"^[^%]*\\(?:lilypond)\{(.*?)\}")

    # check for deps (in sb data)
    deps = [];
    if sb["songs"] == "all":
        deps += recursiveFind(os.path.join(library, 'songs'), '*.sg')
    else:
        deps += map(lambda x: library + "songs/" + x, sb["songs"])

    # check for lilypond deps (in songs data) if necessary
    lilypond = []
    if "bookoptions" in sb and "lilypond" in sb["bookoptions"]:
        for filename in deps:
            tmpl = open(filename)
            lilypond += matchRegexp(lilypondPattern, tmpl)
            tmpl.close()

    # check for index (in template file)
    if "template" in sb:
        filename = sb["template"]
    else:
        filename = "patacrep.tmpl"
    tmpl = open("templates/"+filename)
    idx = map(lambda x: x.replace("\getname", name), matchRegexp(indexPattern, tmpl))
    tmpl.close()

    # write .d file
    out = open(output, 'w')
    out.write('{0} {1} : {2}\n'.format(output, name+".tex", ' '.join(deps)))
    out.write('{0} : {1}\n'.format(name+".pdf", ' '.join(map(lambda x: x+".sbx",idx)+map(lambda x: library+"lilypond/"+x+".pdf", lilypond))))
    out.write('\t$(LATEX) {0}\n'.format(name+".tex"))
    out.write('{0} : {1}\n'.format(' '.join(map(lambda x: x+".sxd",idx)), name+".aux"))
    out.close()
예제 #5
0
def makeTexFile(sb, library, output):
    name = output[:-4]

    # default value
    template = "patacrep.tmpl"
    songs = []
    titleprefixwords = ""
    prefixes = []

    # parse the songbook data
    if "template" in sb:
        template = sb["template"]
        del sb["template"]
    if "songs" in sb:
        songs = sb["songs"]
        del sb["songs"]
    if "titleprefixwords" in sb:
        prefixes = sb["titleprefixwords"]
        for prefix in sb["titleprefixwords"]:
            titleprefixwords += "\\titleprefixword{%s}\n" % prefix
        sb["titleprefixwords"] = titleprefixwords

    parameters = parseTemplate("templates/" + template)

    # output relevant fields
    out = open(output, 'w')
    out.write('%% This file has been automatically generated, do not edit!\n')
    out.write('\\makeatletter\n')
    # output automatic parameters
    out.write(formatDeclaration("name", {"default": name}))
    out.write(formatDeclaration("songslist", {"type": "stringlist"}))
    # output template parameter command
    for name, parameter in parameters.iteritems():
        out.write(formatDeclaration(name, parameter))
    # output template parameter values
    for name, value in sb.iteritems():
        if name in parameters:
            out.write(formatDefinition(name, toValue(parameters[name], value)))
    # output songslist
    if songs == "all":
        songs = map(lambda x: x[len(library) + 6:],
                    recursiveFind(os.path.join(library, 'songs'), '*.sg'))

    if len(songs) > 0:
        out.write(
            formatDefinition('songslist', songslist(library, songs, prefixes)))
    out.write('\\makeatother\n')

    # output template
    commentPattern = re.compile(r"^\s*%")
    f = open("templates/" + template)
    content = [line for line in f if not commentPattern.match(line)]

    for index, line in enumerate(content):
        if re.compile("getLibraryImgDirectory").search(line):
            line = line.replace("\\getLibraryImgDirectory", library + "img/")
            content[index] = line
        if re.compile("getLibraryLilypondDirectory").search(line):
            line = line.replace("\\getLibraryLilypondDirectory",
                                library + "lilypond/")
            content[index] = line

    f.close()
    out.write(''.join(content))

    out.close()
예제 #6
0
def main():
    usage = "usage: %prog [options]"
    parser = OptionParser(usage)
    parser.add_option("-o",
                      "--output",
                      dest="filename",
                      help="write result into FILE",
                      metavar="FILE")
    (options, args) = parser.parse_args()

    # Options processing
    if options.filename:
        output = open(options.filename, "w")
    else:
        output = sys.stdout

    # Actual processing
    chords = dict()
    positions = dict()

    songfiles = recursiveFind(os.path.join(library, 'songs'), '*.sg')

    for file in songfiles:
        for line in open(file):
            result = gtabPattern.match(line)
            if result:
                (chord, position) = result.groups()
                if not chords.has_key(chord):
                    chords[chord] = set()
                chords[chord].add(position)
                if not positions.has_key(position):
                    positions[position] = set()
                positions[position].add(chord)

    document = [
        '\\documentclass{article}',
        '\\usepackage[chorded]{songs}',
        '\\usepackage[utf8]{inputenc}',
        '\\title{Accords}',
        '\\author{Romain Goffe \\and Alexandre Dupas}',
        '\\date{}',
        '\\begin{document}',
        '\\maketitle',
        '\\begin{songs}{}',
    ]

    document.append('\\section{Chords names}')

    chordskeys = chords.keys()
    chordskeys.sort()

    for k in chordskeys:
        document.append('\\subsection{' +
                        k.replace('#', '\\#').replace('&', '\\&') + '}')
        for p in chords[k]:
            document.append('\\gtab{' + k + '}{' + p + '}')

    document.append('\\section{Chords names}')

    positionskeys = positions.keys()
    positionskeys.sort()

    for k in positionskeys:
        document.append('\\subsection{' + k + '}')
        for p in positions[k]:
            document.append('\\gtab{' + p + '}{' + k + '}')

    document.extend([
        '\\end{songs}',
        '\\end{document}',
    ])

    output.write('\n'.join(document))
예제 #7
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

#Author: Romain Goffe
#Date: 28/12/2011
#Description: Resize all covers to 128,128 thumbnails

import Image

from utils.utils import recursiveFind

# Process song files
covers = recursiveFind(os.path.join(library, 'songs'), '*.jpg')
for filename in covers:

    source = Image.open(filename)

    src_width = source.size[0]
    src_height = source.size[1]
    ratio = float(src_height) / float(src_width)

    width  = 128
    height = 128
    error  = 0.2 #0: always preserve ratio; 1: always square images 

    #tolerate almost square images
    if ratio < 1 - error  or ratio > 1 + error:
        #print "preserve ratio = ", ratio
        #preserve important ratio
        if src_width < src_height:
            height = int(width * ratio)
예제 #8
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

#Author: Romain Goffe
#Date: 28/12/2011
#Description: Resize all covers to 128,128 thumbnails

import Image

from utils.utils import recursiveFind

# Process song files
covers = recursiveFind(os.path.join(library, 'songs'), '*.jpg')
for filename in covers:

    source = Image.open(filename)

    src_width = source.size[0]
    src_height = source.size[1]
    ratio = float(src_height) / float(src_width)

    width = 128
    height = 128
    error = 0.2  #0: always preserve ratio; 1: always square images

    #tolerate almost square images
    if ratio < 1 - error or ratio > 1 + error:
        #print "preserve ratio = ", ratio
        #preserve important ratio
        if src_width < src_height:
            height = int(width * ratio)
예제 #9
0
def main():
    usage = "usage: %prog [options]"
    parser = OptionParser(usage)
    parser.add_option("-o", "--output", dest="filename",
                      help="write result into FILE", metavar="FILE")
    (options, args) = parser.parse_args()

    # Options processing
    if options.filename:
        output = open(options.filename,"w")
    else:
        output = sys.stdout

    # Actual processing
    chords = dict()
    positions = dict()

    songfiles = recursiveFind(os.path.join(library, 'songs'), '*.sg')
    
    for file in songfiles:
        for line in open(file):
            result = gtabPattern.match(line)
            if result:
                (chord,position) = result.groups()
                if not chords.has_key(chord):
                    chords[chord] = set()
                chords[chord].add(position)
                if not positions.has_key(position):
                    positions[position] = set()
                positions[position].add(chord)

    document = [
        '\\documentclass{article}',        
        '\\usepackage[chorded]{songs}',
        '\\usepackage[utf8]{inputenc}',
        '\\title{Accords}',
        '\\author{Romain Goffe \\and Alexandre Dupas}',
        '\\date{}',
        '\\begin{document}',
        '\\maketitle',
        '\\begin{songs}{}', 
        ]

    document.append('\\section{Chords names}')

    chordskeys = chords.keys()
    chordskeys.sort()

    for k in chordskeys:
        document.append('\\subsection{'+k.replace('#','\\#').replace('&','\\&')+'}')
        for p in chords[k]:
            document.append('\\gtab{'+k+'}{'+p+'}')

    document.append('\\section{Chords names}')

    positionskeys = positions.keys()
    positionskeys.sort()

    for k in positionskeys:
        document.append('\\subsection{'+k+'}')
        for p in positions[k]:
            document.append('\\gtab{'+p+'}{'+k+'}')

    document.extend([
            '\\end{songs}',
            '\\end{document}',
            ])

    output.write('\n'.join(document))
예제 #10
0
def makeTexFile(sb, library, output):
    name = output[:-4]

    # default value
    template = "patacrep.tmpl"
    songs = []
    titleprefixwords = ""
    prefixes = []

    # parse the songbook data
    if "template" in sb:
        template = sb["template"]
        del sb["template"]
    if "songs" in sb:
        songs = sb["songs"]
        del sb["songs"]
    if "titleprefixwords" in sb:
        prefixes = sb["titleprefixwords"]
        for prefix in sb["titleprefixwords"]:
            titleprefixwords += "\\titleprefixword{%s}\n" % prefix
        sb["titleprefixwords"] = titleprefixwords

    parameters = parseTemplate("templates/"+template)

    # output relevant fields
    out = open(output, 'w')
    out.write('%% This file has been automatically generated, do not edit!\n')
    out.write('\\makeatletter\n')
    # output automatic parameters
    out.write(formatDeclaration("name", {"default":name}))
    out.write(formatDeclaration("songslist", {"type":"stringlist"}))
    # output template parameter command
    for name, parameter in parameters.iteritems():
        out.write(formatDeclaration(name, parameter))
    # output template parameter values
    for name, value in sb.iteritems():
        if name in parameters:
            out.write(formatDefinition(name, toValue(parameters[name],value)))
    # output songslist
    if songs == "all":
        songs = map(lambda x: x[len(library) + 6:], recursiveFind(os.path.join(library, 'songs'), '*.sg'))

    if len(songs) > 0:
        out.write(formatDefinition('songslist', songslist(library, songs, prefixes)))
    out.write('\\makeatother\n')

    # output template
    commentPattern = re.compile(r"^\s*%")
    f = open("templates/"+template)
    content = [ line for line in f if not commentPattern.match(line) ]

    for index, line in enumerate(content):
        if re.compile("getLibraryImgDirectory").search(line):
            line = line.replace("\\getLibraryImgDirectory", library + "img/")
            content[index] = line
        if re.compile("getLibraryLilypondDirectory").search(line):
            line = line.replace("\\getLibraryLilypondDirectory", library + "lilypond/")
            content[index] = line

    f.close()
    out.write(''.join(content))

    out.close()