Added script to generate correct identifier urls for books.
[wolnelektury.git] / lib / librarian / bin / genslugs.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 import os
4 import optparse
5
6 from lxml import etree
7 from librarian import html
8 from slughifi import slughifi
9
10
11 BOOK_URL = 'http://wolnelektury.pl/katalog/lektura/'
12
13
14 if __name__ == '__main__':
15     # Parse commandline arguments
16     usage = """Usage: %prog [options] SOURCE [SOURCE...]
17     Generate slugs for SOURCE."""
18
19     parser = optparse.OptionParser(usage=usage)
20
21     parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False,
22         help='print status messages to stdout')
23
24     options, input_filenames = parser.parse_args()
25
26     if len(input_filenames) < 1:
27         parser.print_help()
28         exit(1)
29
30     # Do some real work
31     for input_filename in input_filenames:
32         if options.verbose:
33             print input_filename
34         
35         doc = etree.parse(input_filename)
36         try:
37             title = doc.find('//{http://purl.org/dc/elements/1.1/}title').text
38         except AttributeError:
39             print '%s:error:book title not found, skipping' % input_filename
40             continue
41         
42         parent = ''
43         try:
44             parent_url = doc.find('//{http://purl.org/dc/elements/1.1/}relation.isPartOf').text
45             parent = parent_url.rsplit('/', 1)[1] + ' '
46         except AttributeError:
47             pass
48         
49         book_url = doc.find('//{http://purl.org/dc/elements/1.1/}identifier.url')
50         if book_url is None:
51             book_description = doc.find('//{http://www.w3.org/1999/02/22-rdf-syntax-ns#}Description')
52             book_url = etree.SubElement(book_description, '{http://purl.org/dc/elements/1.1/}identifier.url')
53         elif book_url.text.startswith('http://'):
54             print '%s:notice:book already has identifier starting with http://, skipping' % input_filename
55             continue
56         book_url.text = BOOK_URL + slughifi(parent + title)
57
58         doc.write(input_filename, xml_declaration=True, pretty_print=True, encoding='utf-8')
59