lum2olp.py

This is a quick, simple and easy script to convert a Luminous database to openlp.org version 1.0

#!/usr/bin/env python
 
"""
lum2olp 0.1 for openlp.org 1.0
----------------------------------
This is a quick, simple and easy script to convert a Luminous database to
openlp.org version 1.0
 
Written by Raoul Snyman [raoul.snyman AT saturnlaboratories DOT co DOT za]
 
License:
--------
Copyright (c) 2009 Raoul Snyman. All rights reserved.
 
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
 
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
 
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
"""
 
import os
import sys
import codecs
import sqlite
import sqlite3
from exceptions import Exception
from optparse import OptionParser
 
def split_authors(author_list):
    """
    This takes a string list of authors and splits them up:
        "Marty Sampson, Matt Crocker & Scott Ligertwood"
    becomes:
        ['Marty Sampson', 'Matt Crocker', 'Scott Ligertwood']
    """
    temp_authors = []
    comma_authors = author_list.split(',')
    temp_authors.extend(comma_authors[:-1])
    temp_authors.extend(comma_authors[-1].split('&'))
    all_authors = []
    for author in temp_authors:
        all_authors.append(author.strip())
    return all_authors
 
def sort_sections(section_list):
    """
    This pulls the sections out of the tuples from the DB, and returns a list
    of verses in one string, the way openlp.org expects it.
    """
    sections = []
    for sect in section_list:
        sections.append(sect[0])
    lyrics = u'\n\n'.join(sections)
    return lyrics.replace(u'"', u'""').replace(u'\u2019', u'\'').replace(u'\u2018', u'\'')
 
def main():
    """
    This is the main function.
    """
    sys.stdout = codecs.getwriter('utf8')(sys.stdout)
    version = u'lum2olp 0.1 for openlp.org 1.0\nCopyright (c) 2009 Raoul Snyman\nThis program is licensed under the GNU General Public License'
    usage = u'%prog [options]'
    parser = OptionParser(version=version, usage=usage)
    parser.add_option('-s', '--source', dest='source', metavar='SOURCE',
        default='database.lued',
        help='Specify the Luminous source file to be used. If no file is specified, "database.lued" in the current directory will be used.')
    parser.add_option('-d', '--destination', dest='destination', metavar='DESTINATION',
        default='songs.olp',
        help='Specify the openlp.org songs database to be used. If no database is specified, "songs.olp" in the current directory will be used.')
    (options, args) = parser.parse_args()
    lum_connection = sqlite3.connect(os.path.abspath(options.source))
    olp_connection = sqlite.connect(os.path.abspath(options.destination))
    lum_cursor = lum_connection.cursor()
    olp_cursor = olp_connection.cursor()
    try:
        lum_cursor.execute(u'SELECT SongId, Title, Author, CopyrightNotice FROM SongInfo')
    except Exception, e:
        print u'An error occurred: %s' % e.message
        return 1
    lum_songs = lum_cursor.fetchall()
    if len(lum_songs) == 0:
        print u'No songs found! Exiting...'
        return 1
    for lum_song in lum_songs:
        print u'Processing: "%s"...' % lum_song[1]
        lum_authors = split_authors(lum_song[2])
        author_ids = []
        for lum_author in lum_authors:
            olp_cursor.execute(u'SELECT authorid FROM authors WHERE authorname LIKE "%s"' % lum_author)
            olp_author = olp_cursor.fetchone()
            if olp_author is not None:
                author_ids.append(olp_author)
            else:
                olp_cursor.execute(u'INSERT INTO authors (authorname) VALUES ("%s")', lum_author)
                olp_cursor.execute(u'SELECT MAX(authorid) FROM authors')
                author_ids.append(olp_cursor.fetchone())
        lum_cursor.execute(u'SELECT Section FROM SongLyricSection WHERE SongId = ? ORDER BY SectionIndex',
            (lum_song[0],))
        lum_sections = lum_cursor.fetchall()
        insert_sql = u'INSERT INTO songs (songtitle, lyrics, copyrightinfo, settingsid) VALUES ("%s", "%s", "%s", 1)' % \
            (lum_song[1], sort_sections(lum_sections), lum_song[3])
        olp_cursor.execute(insert_sql)
        song_id = olp_connection.insert_id()
        for author_id in author_ids:
            insert_sql = u'INSERT INTO songauthors (songid, authorid) VALUES (%s, %s)' % (str(song_id), str(int(author_id[0])))
            olp_cursor.execute(insert_sql)
        olp_connection.commit()
    print 'Done.'
 
if __name__ == u'__main__':
    main()