Data for #3396: picture style, full creation date.
[librarian.git] / scripts / genslugs
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
5 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
6 #
7 import os
8 import optparse
9
10 from lxml import etree
11 from librarian import html
12 from slughifi import slughifi
13
14
15 BOOK_URL = 'http://wolnelektury.pl/katalog/lektura/'
16
17
18 if __name__ == '__main__':
19     # Parse commandline arguments
20     usage = """Usage: %prog [options] SOURCE [SOURCE...]
21     Generate slugs for SOURCE."""
22
23     parser = optparse.OptionParser(usage=usage)
24
25     parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False,
26         help='print status messages to stdout')
27     parser.add_option('-f', '--force', action='store_true', dest='force', default=False,
28         help='overwrite current identifiers')
29
30     options, input_filenames = parser.parse_args()
31
32     if len(input_filenames) < 1:
33         parser.print_help()
34         exit(1)
35
36     # Do some real work
37     for input_filename in input_filenames:
38         if options.verbose:
39             print input_filename
40
41         doc = etree.parse(input_filename)
42         try:
43             title = doc.find('//{http://purl.org/dc/elements/1.1/}title').text
44         except AttributeError:
45             print '%s:error:Book title not found. Skipping.' % input_filename
46             continue
47
48         parent = ''
49         try:
50             parent_url = doc.find('//{http://purl.org/dc/elements/1.1/}relation.isPartOf').text
51             parent = parent_url.rsplit('/', 1)[1] + ' '
52         except AttributeError:
53             pass
54         except IndexError:
55             print '%s:error:Invalid parent URL "%s". Skipping.' % (input_filename, parent_url)
56
57         book_url = doc.find('//{http://purl.org/dc/elements/1.1/}identifier.url')
58         if book_url is None:
59             book_description = doc.find('//{http://www.w3.org/1999/02/22-rdf-syntax-ns#}Description')
60             book_url = etree.SubElement(book_description, '{http://purl.org/dc/elements/1.1/}identifier.url')
61         if not options.force and book_url.text.startswith('http://'):
62             print '%s:Notice:Book already has identifier URL "%s". Skipping.' % (input_filename, book_url.text)
63             continue
64
65         book_url.text = BOOK_URL + slughifi(parent + title)[:60]
66
67         doc.write(input_filename, xml_declaration=True, pretty_print=True, encoding='utf-8')
68