/
cts.py
331 lines (265 loc) · 11 KB
/
cts.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
# -*- coding: utf-8 -*-
"""
.. module:: MyCapytain.resources.xml
:synopsis: XML based CtsTextMetadata and repository
.. moduleauthor:: Thibault Clérice <leponteineptique@gmail.com>
"""
from __future__ import unicode_literals
from rdflib import URIRef, Literal
from rdflib.namespace import XSD
from lxml.objectify import IntElement, FloatElement
from MyCapytain.resources.prototypes.cts import inventory as cts
from MyCapytain.common.reference import Citation as CitationPrototype
from MyCapytain.common.utils import xmlparser, expand_namespace
from MyCapytain.common.constants import XPATH_NAMESPACES, Mimetypes, RDF_NAMESPACES
_CLASSES_DICT = {}
class XmlCtsCitation(CitationPrototype):
""" XmlCtsCitation XML implementation for CtsTextInventoryMetadata
"""
@classmethod
def ingest(cls, resource, element=None, xpath="ti:citation"):
""" Ingest xml to create a citation
:param resource: XML on which to do xpath
:param element: Element where the citation should be stored
:param xpath: XPath to use to retrieve citation
:return: XmlCtsCitation
"""
# Reuse of of find citation
results = resource.xpath(xpath, namespaces=XPATH_NAMESPACES)
if len(results) > 0:
citation = cls(
name=results[0].get("label"),
xpath=results[0].get("xpath"),
scope=results[0].get("scope")
)
if isinstance(element, cls):
element.child = citation
cls.ingest(
resource=results[0],
element=element.child
)
else:
element = citation
cls.ingest(
resource=results[0],
element=element
)
return citation
return None
def xpathDict(xml, xpath, cls, parent, **kwargs):
""" Returns a default Dict given certain information
:param xml: An xml tree
:type xml: etree
:param xpath: XPath to find children
:type xpath: str
:param cls: Class identifying children
:type cls: inventory.Resource
:param parent: Parent of object
:type parent: CtsCollection
:rtype: collections.defaultdict.<basestring, inventory.Resource>
:returns: Dictionary of children
"""
children = []
for child in xml.xpath(xpath, namespaces=XPATH_NAMESPACES):
children.append(cls.parse(
resource=child,
parent=parent,
**kwargs
))
return children
def __parse_structured_metadata__(obj, xml):
""" Parse an XML object for structured metadata
:param obj: Object whose metadata are parsed
:param xml: XML that needs to be parsed
"""
for metadata in xml.xpath("cpt:structured-metadata/*", namespaces=XPATH_NAMESPACES):
tag = metadata.tag
if "{" in tag:
ns, tag = tuple(tag.split("}"))
tag = URIRef(ns[1:]+tag)
s_m = str(metadata)
if s_m.startswith("urn:") or s_m.startswith("http:") or s_m.startswith("https:") or s_m.startswith("hdl:"):
obj.metadata.add(
tag,
URIRef(metadata)
)
elif '{http://www.w3.org/XML/1998/namespace}lang' in metadata.attrib:
obj.metadata.add(
tag,
s_m,
lang=metadata.attrib['{http://www.w3.org/XML/1998/namespace}lang']
)
else:
if "{http://www.w3.org/1999/02/22-rdf-syntax-ns#}datatype" in metadata.attrib:
datatype = metadata.attrib["{http://www.w3.org/1999/02/22-rdf-syntax-ns#}datatype"]
if not datatype.startswith("http") and ":" in datatype:
datatype = expand_namespace(metadata.nsmap, datatype)
obj.metadata.add(tag, Literal(s_m, datatype=URIRef(datatype)))
elif isinstance(metadata, IntElement):
obj.metadata.add(tag, Literal(int(metadata), datatype=XSD.integer))
elif isinstance(metadata, FloatElement):
obj.metadata.add(tag, Literal(float(metadata), datatype=XSD.float))
else:
obj.metadata.add(tag, s_m)
class XmlCtsTextMetadata(cts.CtsTextMetadata):
""" Represents a CTS CtsTextMetadata
"""
DEFAULT_EXPORT = Mimetypes.PYTHON.ETREE
CLASS_CITATION = XmlCtsCitation
@staticmethod
def __findCitations(obj, xml, xpath="ti:citation"):
""" Find citation in current xml. Used as a loop for xmlparser()
:param xml: Xml resource to be parsed
:param xpath: Xpath to use to retrieve the xml node
"""
@classmethod
def parse_metadata(cls, obj, xml):
""" Parse a resource to feed the object
:param obj: Obj to set metadata of
:type obj: XmlCtsTextMetadata
:param xml: An xml representation object
:type xml: lxml.etree._Element
"""
for child in xml.xpath("ti:description", namespaces=XPATH_NAMESPACES):
lg = child.get("{http://www.w3.org/XML/1998/namespace}lang")
if lg is not None:
obj.set_cts_property("description", child.text, lg)
for child in xml.xpath("ti:label", namespaces=XPATH_NAMESPACES):
lg = child.get("{http://www.w3.org/XML/1998/namespace}lang")
if lg is not None:
obj.set_cts_property("label", child.text, lg)
obj.citation = cls.CLASS_CITATION.ingest(xml, obj.citation, "ti:online/ti:citationMapping/ti:citation")
# Added for commentary
for child in xml.xpath("ti:about", namespaces=XPATH_NAMESPACES):
obj.set_link(RDF_NAMESPACES.CTS.term("about"), child.get('urn'))
__parse_structured_metadata__(obj, xml)
"""
online = xml.xpath("ti:online", namespaces=NS)
if len(online) > 0:
online = online[0]
obj.docname = online.get("docname")
for validate in online.xpath("ti:validate", namespaces=NS):
obj.validate = validate.get("schema")
for namespaceMapping in online.xpath("ti:namespaceMapping", namespaces=NS):
obj.metadata["namespaceMapping"][namespaceMapping.get("abbreviation")] = namespaceMapping.get("nsURI")
"""
def __init__(self, *args, **kwargs):
super(XmlCtsTextMetadata, self).__init__(*args, **kwargs)
self._path = None
@property
def path(self):
return self._path
@path.setter
def path(self, value):
self._path = value
class XmlCtsEditionMetadata(cts.CtsEditionMetadata, XmlCtsTextMetadata):
""" Create an edition subtyped CtsTextMetadata object
"""
@classmethod
def parse(cls, resource, parent=None):
xml = xmlparser(resource)
o = cls(urn=xml.get("urn"), parent=parent)
cls.parse_metadata(o, xml)
return o
class XmlCtsTranslationMetadata(cts.CtsTranslationMetadata, XmlCtsTextMetadata):
""" Create a translation subtyped CtsTextMetadata object
"""
@classmethod
def parse(cls, resource, parent=None):
xml = xmlparser(resource)
lang = xml.get("{http://www.w3.org/XML/1998/namespace}lang")
o = cls(urn=xml.get("urn"), parent=parent)
if lang is not None:
o.lang = lang
cls.parse_metadata(o, xml)
return o
class XmlCtsCommentaryMetadata(cts.CtsCommentaryMetadata, XmlCtsTextMetadata):
""" Create a commentary subtyped PrototypeText object
"""
@classmethod
def parse(cls, resource, parent=None):
xml = xmlparser(resource)
lang = xml.get("{http://www.w3.org/XML/1998/namespace}lang")
o = cls(urn=xml.get("urn"), parent=parent)
if lang is not None:
o.lang = lang
cls.parse_metadata(o, xml)
return o
class XmlCtsWorkMetadata(cts.CtsWorkMetadata):
""" Represents a CTS Textgroup in XML
"""
CLASS_EDITION = XmlCtsEditionMetadata
CLASS_TRANSLATION = XmlCtsTranslationMetadata
CLASS_COMMENTARY = XmlCtsCommentaryMetadata
@classmethod
def parse(cls, resource, parent=None, _with_children=False):
""" Parse a resource
:param resource: Element rerpresenting a work
:param type: basestring, etree._Element
:param parent: Parent of the object
:type parent: XmlCtsTextgroupMetadata
:param _cls_dict: Dictionary of classes to generate subclasses
"""
xml = xmlparser(resource)
o = cls(urn=xml.get("urn"), parent=parent)
lang = xml.get("{http://www.w3.org/XML/1998/namespace}lang")
if lang is not None:
o.lang = lang
for child in xml.xpath("ti:title", namespaces=XPATH_NAMESPACES):
lg = child.get("{http://www.w3.org/XML/1998/namespace}lang")
if lg is not None:
o.set_cts_property("title", child.text, lg)
# Parse children
children = []
children.extend(xpathDict(
xml=xml, xpath='ti:edition',
cls=cls.CLASS_EDITION, parent=o
))
children.extend(xpathDict(
xml=xml, xpath='ti:translation',
cls=cls.CLASS_TRANSLATION, parent=o
))
children.extend(xpathDict(
xml=xml, xpath='ti:commentary',
cls=cls.CLASS_COMMENTARY, parent=o
))
__parse_structured_metadata__(o, xml)
if _with_children:
return o, children
return o
class XmlCtsTextgroupMetadata(cts.CtsTextgroupMetadata):
""" Represents a CTS Textgroup in XML
"""
CLASS_WORK = XmlCtsWorkMetadata
@classmethod
def parse(cls, resource, parent=None):
""" Parse a textgroup resource
:param resource: Element representing the textgroup
:param parent: Parent of the textgroup
:param _cls_dict: Dictionary of classes to generate subclasses
"""
xml = xmlparser(resource)
o = cls(urn=xml.get("urn"), parent=parent)
for child in xml.xpath("ti:groupname", namespaces=XPATH_NAMESPACES):
lg = child.get("{http://www.w3.org/XML/1998/namespace}lang")
if lg is not None:
o.set_cts_property("groupname", child.text, lg)
# Parse Works
xpathDict(xml=xml, xpath='ti:work', cls=cls.CLASS_WORK, parent=o)
__parse_structured_metadata__(o, xml)
return o
class XmlCtsTextInventoryMetadata(cts.CtsTextInventoryMetadata):
""" Represents a CTS Inventory file
"""
CLASS_TEXTGROUP = XmlCtsTextgroupMetadata
@classmethod
def parse(cls, resource):
""" Parse a resource
:param resource: Element representing the text inventory
:param _cls_dict: Dictionary of classes to generate subclasses
"""
xml = xmlparser(resource)
o = cls(name=xml.xpath("//ti:TextInventory", namespaces=XPATH_NAMESPACES)[0].get("tiid") or "")
# Parse textgroups
xpathDict(xml=xml, xpath='//ti:textgroup', cls=cls.CLASS_TEXTGROUP, parent=o)
return o