-
Notifications
You must be signed in to change notification settings - Fork 0
/
metadata.py
459 lines (332 loc) · 12.5 KB
/
metadata.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
"""Classes implimenting the simple filesystem syntax.
"""
import copy
import datetime
import os
import settings
class Metadata():
"""Provide services for dealing with metadata.
This class knows all about the metadata files. Give it the
pathname to a file and it will determine where the metafile is,
read it and return a list of key/value pairs.
It can also create a metafile for a new page, and guess the
contents of certain fields, like title, author, etc.
A metafile record looks like this:
# Dublin Core metadata record
DC.Title: Webnote
DC.Creator: Malcolm Hutchinson
DC.Subject: Filesystem syntax, information systems, Django, Python
DC.Description: Filesystem services implimenting the simple syntax.
DC.Contributor:
DC.Coverage: New Zealand
DC.Date: 2015-04-03
DC.Type:
DC.Format: text/html
DC.Source:
DC.Language: en
DC.Identifier:
DC.Publisher: Malcolm Hutchinson
DC.Relation:
DC.Rights: cc-by
# END DC metadata
# Page command options
sort: forward | reverse
type: gallery | page
deny: all
allow: staff
status: draft
# END page command
This class takes a page address, which is the address generated by
a Webnote object, pointing to a page (text or HTML file).
This class can read a file containing a record like this, and
parse it into a metadata structure.
The metafile is represented by a list stored at
self.filemodel, containing (key, value) tuples. These are
obtained by splitting each line at the colon, and returning the
first element as key, and a re-stitched list of the rest as value.
"""
ELEMENTS = (
"dc_title",
"dc_creator",
"dc_subject",
"dc_description",
"dc_contributor",
"dc_coverage",
"dc_date",
"dc_type",
"dc_format",
"dc_source",
"dc_language",
"dc_relation",
"dc_identifier",
"dc_publisher",
"dc_rights",
)
# This should be in a view or something, abstracted from here.
COMMANDS = (
'allow',
'deny',
'embargo',
'liststyle',
'sort',
'status',
'stylesheet',
'type',
)
warnings = []
data = None
filemodel = None
metadata = None
metafilename = None
pagefile = None
def __init__(self, pagefile=None, data=None):
"""Operations on metadata records.
Instantiation creates a dictionary structure called
`metadata`, holding lists of Dublin core elements, and
commands.
Initialise with an optional pathname to a page (without
extension). Will search for a metafile under simple syntax
rules, and read this file into the metadata structure.
Initialise with data = a dictionary with those Dublin core and
command keys, and it will load those values into the metadata
structure.
"""
metadata = self.build_empty_metadata()
if pagefile:
self.pagefile = pagefile
self.metafilename = self.locate_metafile()
else:
self.pagefile = ''
if self.metafilename:
self.filemodel = self.read_metafile()
else:
self.metadata = metadata
if self.filemodel:
self.metadata = self.process_filemodel(self.filemodel)
if data:
self.data = data
self.metadata = self.process_data(data)
def build_empty_metadata(self):
"""Return an empty metadata structure dictionary.
This is a dictionary of lists, keyed by ELEMENTS and COMMANDS."""
metadata = {}
for element in self.ELEMENTS:
metadata[element] = []
for element in self.COMMANDS:
metadata[element] = []
return metadata
def dublincore(self):
"""Return a list of DC metadata attribute names and values.
List of (key, value) tuples taken from the metafile, with
order and duplicated elements preserved.
"""
dc = []
for item in self.metadata.keys():
if item[:3].lower() == 'dc_':
dc.append(
(item.replace('dc_', 'DC.'),
'; '.join(self.metadata[item])))
return dc
def find_title(self):
"""Find the title from page content etc."""
(path, fname) = os.path.split(self.pagefile)
(basename, ext) = os.path.splitext(fname)
title = basename.replace('_', ' ')
return title
def liststyle(self):
"""Determine the style of list from metafile.
At the moment, this is fragile and will break if there is no
template matching the value in the liststyle variable.
"""
if 'liststyle' not in self.metadata.keys():
return None
if len(self.metadata['liststyle']) == 0:
return None
style = 'liststyles/simple.html'
dir = 'liststyles/'
ext = '.html'
# This needs to test for a template at this address. If
# there is none, it returns 'default.html'.
return dir + self.metadata['liststyle'][0] + ext
def locate_metafile(self):
"""Locate the metafile for the given address.
This follows this process:
- metafile in the parent directory.
- metafile in the meta directory.
- metafile in the paired directory.
Return None if not file found.
"""
(basename, ext) = os.path.splitext(self.pagefile)
filename = basename + '.meta'
if os.path.isfile(filename):
return filename
steps = basename.split('/')
last = steps.pop()
path = '/'.join(steps)
metaname = last + '.meta'
filename = os.path.join(path, 'meta', last + '.meta')
if os.path.isfile(filename):
return filename
filename = os.path.join(basename, metaname)
if os.path.isfile(filename):
return filename
return None
def formdata(self):
"""Return a dictionary suitable for populating forms."""
formdata = {}
for element in self.ELEMENTS:
formdata[element] = '; '.join(self.metadata[element])
for element in self.COMMANDS:
formdata[element] = '; '.join(self.metadata[element])
return formdata
def metafile_record(self, data=None):
"""Return a string containing a metadata record in text format.
This produces a string containing a record suitable for filing
with pages in the document archive. It is intended to be
written to a text file with a .meta suffix.
If the metadata structure is empty, as at init, the result
will be a file record with a list of keys, but no values.
"""
record = '# Dublin core metadata.\n'
metadata = self.metadata
for element in self.ELEMENTS:
if element in metadata.keys():
key = element.replace('dc_', 'DC.')
record += key + ": "
record += '; '.join(metadata[element]) + '\n'
record += "# end Dublin core elements.\n\n"
record += "# Page commands.\n"
for element in self.COMMANDS:
if element in metadata.keys():
record += element + ": "
record += '; '.join(metadata[element]) + '\n'
record += "# End page commands.\n"
record += "# Record written by webnote.metadata at "
record += str(datetime.datetime.now()) + '\n'
return record
def preferred_filename(self, fname=None):
"""Return the preferred filename for a new metadata file.
"""
filename = ''
(path, pagefile) = os.path.split(self.pagefile)
if fname:
filename = os.path.join(
path, settings.META[0], fname.replace(' ', '_') + '.meta')
else:
(basename, ext) = os.path.splitext(pagefile)
filename = os.path.join(
path, settings.META[0], basename + '.meta')
return filename
def process_data(self, data):
metadata = self.build_empty_metadata()
for element in metadata.keys():
if element in data.keys():
metadata[element].append(data[element])
return metadata
def process_filemodel(self, filemodel):
"""Convert a filemodel into metadata structure.
"""
metadata = self.build_empty_metadata()
for line in self.filemodel:
key = line[0].lower().replace('.', '_')
if line[0].lower() == 'comment':
pass
# Is the first element of the line a metadata key?
elif key in metadata.keys():
if len(key):
metadata[key].append(line[1])
# Is it a command?
elif line[0].lower() in self.COMMANDS:
metadata[line[0]] = line[1]
# Include one which isn't either a metadata element or a command.
else:
metadata[line[0]] = line[1]
return metadata
def read_metafile(self):
"""Return a metafile model structure from the metafile filename.
Open and read the file, parse the contents into a filemodel
structure.
Key and value are separated by colon ':'.
"""
metafilename = None
record = [('filename:', self.metafilename)]
with open(self.metafilename) as f:
contents = f.readlines()
for line in contents:
if line[0] == '#':
key = 'comment'
value = line[1:]
record.append((key, value))
else:
bits = line.split(":")
key = bits.pop(0)
key = key.strip()
value = ':'.join(bits)
value = value.strip()
record.append((key, value))
return record
def save(self, data=None):
"""Save a metarecord to file."""
metafilename = None
if data:
self.metadata = self.process_data(data)
if 'newfilename' in data.keys():
fname = data['newfilename']
metafilename = self.preferred_filename(fname)
else:
if self.metafilename:
metafilename = self.metafilename
if not metafilename:
metafilename = self.preferred_filename()
(path, fname) = os.path.split(metafilename)
if not os.path.isdir(path):
print "MAKING META DIRECTORY", path
os.mkdir(path)
record = self.metafile_record()
f = open(metafilename, 'w')
f.write(record)
f.close()
# Methods to return individual field values.
def title(self):
return '\n'. join(self.metadata['dc_title'])
def author(self):
return '; '.join(self.metadata['dc_creator'])
def contributors(self):
return '; '.join(self.metadata['dc_contributor'])
def description(self):
return '\n'.join(self.metadata['dc_description'])
def doctype(self):
return '; '.join(self.metadata['dc_type'])
def fileformat(self):
return '; '.join(self.metadata['dc_format'])
def language(self):
return ', '.join(self.metadata['dc_language'])
def location(self):
return ', '.join(self.metadata['dc_coverage'])
def pubdate(self):
if len(self.metadata['dc_date']) > 0:
return self.metadata['dc_date'][0]
else:
return ""
def publisher(self):
return '; '.join(self.metadata['dc_publisher'])
def rights(self):
return '; '.join(self.metadata['dc_rights'])
def rights_markup(self):
"""Return marked-up code for rights. """
rights = None
right = '; '.join(self.metadata['dc_rights'])
if right in settings.LICENSES.keys():
rights = "<a href='" + settings.LICENSES[right][0] + "'>"
rights += settings.LICENSES[right][1] + "</a>"
return rights
def source(self):
return '; '.join(self.metadata['dc_source'])
def sort(self):
return self.metadata['sort'][0]
def subject(self):
return ', '.join(self.metadata['dc_subject'])
def pagetype(self):
if 'type' in self.metadata.keys():
return self.metadata['type']
return None