Version 1.2.1.
[librarian.git] / scripts / genslugs
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     parser.add_option('-f', '--force', action='store_true', dest='force', default=False,
24         help='overwrite current identifiers')
25     
26     options, input_filenames = parser.parse_args()
27
28     if len(input_filenames) < 1:
29         parser.print_help()
30         exit(1)
31
32     # Do some real work
33     for input_filename in input_filenames:
34         if options.verbose:
35             print input_filename
36         
37         doc = etree.parse(input_filename)
38         try:
39             title = doc.find('//{http://purl.org/dc/elements/1.1/}title').text
40         except AttributeError:
41             print '%s:error:Book title not found. Skipping.' % input_filename
42             continue
43         
44         parent = ''
45         try:
46             parent_url = doc.find('//{http://purl.org/dc/elements/1.1/}relation.isPartOf').text
47             parent = parent_url.rsplit('/', 1)[1] + ' '
48         except AttributeError:
49             pass
50         except IndexError:
51             print '%s:error:Invalid parent URL "%s". Skipping.' % (input_filename, parent_url)
52             
53         book_url = doc.find('//{http://purl.org/dc/elements/1.1/}identifier.url')
54         if book_url is None:
55             book_description = doc.find('//{http://www.w3.org/1999/02/22-rdf-syntax-ns#}Description')
56             book_url = etree.SubElement(book_description, '{http://purl.org/dc/elements/1.1/}identifier.url')
57         if not options.force and book_url.text.startswith('http://'):
58             print '%s:Notice:Book already has identifier URL "%s". Skipping.' % (input_filename, book_url.text)
59             continue
60         
61         book_url.text = BOOK_URL + slughifi(parent + title)[:60]
62
63         doc.write(input_filename, xml_declaration=True, pretty_print=True, encoding='utf-8')
64