Passed
Pull Request — master (#875)
by Konstantin
02:59
created

ocrd_models.ocrd_mets   F

Complexity

Total Complexity 176

Size/Duplication

Total Lines 746
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 176
eloc 421
dl 0
loc 746
rs 2
c 0
b 0
f 0

25 Methods

Rating   Name   Duplication   Size   Complexity  
A OcrdMets.__exit__() 0 6 2
A OcrdMets.__str__() 0 5 1
A OcrdMets.add_file_group() 0 21 5
A OcrdMets.agents() 0 6 1
A OcrdMets.empty_mets() 0 11 2
A OcrdMets.__init__() 0 30 2
B OcrdMets._fill_caches() 0 44 7
F OcrdMets.find_files() 0 106 49
A OcrdMets.add_agent() 0 12 2
A OcrdMets.file_groups() 0 11 2
A OcrdMets.unique_identifier() 0 10 4
A OcrdMets._clear_caches() 0 8 1
A OcrdMets.rename_file_group() 0 11 3
A OcrdMets.find_all_files() 0 6 1
A OcrdMets.physical_pages() 0 11 2
C OcrdMets.get_physical_pages() 0 22 9
A OcrdMets.get_physical_page_for_file() 0 18 5
D OcrdMets.add_file() 0 49 12
A OcrdMets.remove_physical_page() 0 17 5
B OcrdMets.merge() 0 29 6
B OcrdMets.remove_physical_page_fptr() 0 28 6
B OcrdMets.remove_file() 0 17 6
D OcrdMets.remove_file_group() 0 51 13
C OcrdMets.remove_one_file() 0 59 11
F OcrdMets.set_physical_page_for_file() 0 67 16

How to fix   Complexity   

Complexity

Complex classes like ocrd_models.ocrd_mets often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
"""
2
API to METS
3
"""
4
from datetime import datetime
5
import re
6
import typing
7
from lxml import etree as ET
8
from copy import deepcopy
9
10
from ocrd_utils import (
11
    is_local_filename,
12
    getLogger,
13
    generate_range,
14
    VERSION,
15
    REGEX_PREFIX,
16
    REGEX_FILE_ID
17
)
18
19
from .constants import (
20
    NAMESPACES as NS,
21
    TAG_METS_AGENT,
22
    TAG_METS_DIV,
23
    TAG_METS_FILE,
24
    TAG_METS_FILEGRP,
25
    TAG_METS_FILESEC,
26
    TAG_METS_FPTR,
27
    TAG_METS_METSHDR,
28
    TAG_METS_STRUCTMAP,
29
    IDENTIFIER_PRIORITY,
30
    TAG_MODS_IDENTIFIER,
31
    METS_XML_EMPTY,
32
)
33
34
from .ocrd_xml_base import OcrdXmlDocument, ET
35
from .ocrd_file import OcrdFile
36
from .ocrd_agent import OcrdAgent
37
38
REGEX_PREFIX_LEN = len(REGEX_PREFIX)
39
40
class OcrdMets(OcrdXmlDocument):
41
    """
42
    API to a single METS file
43
    """
44
45
    @staticmethod
46
    def empty_mets(now=None, cache_flag=False):
47
        """
48
        Create an empty METS file from bundled template.
49
        """
50
        if not now:
51
            now = datetime.now().isoformat()
52
        tpl = METS_XML_EMPTY.decode('utf-8')
53
        tpl = tpl.replace('{{ VERSION }}', VERSION)
54
        tpl = tpl.replace('{{ NOW }}', '%s' % now)
55
        return OcrdMets(content=tpl.encode('utf-8'), cache_flag=cache_flag)
56
57
    def __init__(self, **kwargs):
58
        """
59
        """
60
        super(OcrdMets, self).__init__(**kwargs)
61
        
62
        # If cache is enabled
63
        if self._cache_flag:
64
65
            # Cache for the files (mets:file) - two nested dictionaries
66
            # The outer dictionary's Key: 'fileGrp.USE'
67
            # The outer dictionary's Value: Inner dictionary
68
            # The inner dictionary's Key: 'file.ID'
69
            # The inner dictionary's Value: a 'file' object at some memory location
70
            self._file_cache = {}
71
72
            # Cache for the pages (mets:div)
73
            # The dictionary's Key: 'div.ID'
74
            # The dictionary's Value: a 'div' object at some memory location
75
            self._page_cache = {}
76
77
            # Cache for the file pointers (mets:fptr) - two nested dictionaries
78
            # The outer dictionary's Key: 'div.ID'
79
            # The outer dictionary's Value: Inner dictionary
80
            # The inner dictionary's Key: 'fptr.FILEID'
81
            # The inner dictionary's Value: a 'fptr' object at some memory location
82
            self._fptr_cache = {}
83
84
            # Note, if the empty_mets() function is used to instantiate OcrdMets
85
            # Then the cache is empty even after this operation
86
            self._fill_caches()
87
88
    def __exit__(self):
89
        """
90
91
        """
92
        if self._cache_flag:
93
            self._clear_caches()
94
95
    def __str__(self):
96
        """
97
        String representation
98
        """
99
        return 'OcrdMets[cached=%s,fileGrps=%s,files=%s]' % (self._cache_flag, self.file_groups, list(self.find_files()))
100
101
    def _fill_caches(self):
102
        """
103
        Fills the caches with fileGrps and FileIDs
104
        """
105
106
        tree_root = self._tree.getroot()
107
108
        # Fill with files
109
        el_fileSec = tree_root.find("mets:fileSec", NS)
110
        if el_fileSec is None:
111
            return
112
113
        log = getLogger('ocrd_models.ocrd_mets._fill_caches-files')
114
115
        for el_fileGrp in el_fileSec.findall('mets:fileGrp', NS):
116
            fileGrp_use = el_fileGrp.get('USE')
117
118
            # Assign an empty dictionary that will hold the files of the added fileGrp
119
            self._file_cache[fileGrp_use] = {}
120
121
            for el_file in el_fileGrp:
122
                file_id = el_file.get('ID')
123
                self._file_cache[fileGrp_use].update({file_id : el_file})
124
                # log.info("File added to the cache: %s" % file_id)
125
126
        # Fill with pages
127
        el_div_list = tree_root.findall(".//mets:div[@TYPE='page']", NS)
128
        if len(el_div_list) == 0:
129
            return
130
        log = getLogger('ocrd_models.ocrd_mets._fill_caches-pages')
131
132
        for el_div in el_div_list:
133
            div_id = el_div.get('ID')
134
            log.debug("DIV_ID: %s" % el_div.get('ID'))
135
136
            self._page_cache[div_id] = el_div
137
138
            # Assign an empty dictionary that will hold the fptr of the added page (div)
139
            self._fptr_cache[div_id] = {}
140
141
            # log.info("Page_id added to the cache: %s" % div_id)
142
143
            for el_fptr in el_div:
144
                self._fptr_cache[div_id].update({el_fptr.get('FILEID') : el_fptr})
145
                # log.info("Fptr added to the cache: %s" % el_fptr.get('FILEID'))
146
147
        # log.info("Len of page_cache: %s" % len(self._page_cache))
148
        # log.info("Len of fptr_cache: %s" % len(self._fptr_cache))
149
150
    def _clear_caches(self):
151
        """
152
        Deallocates the caches
153
        """
154
155
        self._file_cache = None
156
        self._page_cache = None
157
        self._fptr_cache = None
158
159
    @property
160
    def unique_identifier(self):
161
        """
162
        Get the unique identifier by looking through ``mods:identifier``
163
        See `specs <https://ocr-d.de/en/spec/mets#unique-id-for-the-document-processed>`_ for details.
164
        """
165
        for t in IDENTIFIER_PRIORITY:
166
            found = self._tree.getroot().find('.//mods:identifier[@type="%s"]' % t, NS)
167
            if found is not None:
168
                return found.text
169
        
170
    @unique_identifier.setter
171
    def unique_identifier(self, purl):
172
        """
173
        Set the unique identifier by looking through ``mods:identifier``
174
        See `specs <https://ocr-d.de/en/spec/mets#unique-id-for-the-document-processed>`_ for details.
175
        """
176
        id_el = None
177
        for t in IDENTIFIER_PRIORITY:
178
            id_el = self._tree.getroot().find('.//mods:identifier[@type="%s"]' % t, NS)
179
            if id_el is not None:
180
                break
181
        if id_el is None:
182
            mods = self._tree.getroot().find('.//mods:mods', NS)
183
            id_el = ET.SubElement(mods, TAG_MODS_IDENTIFIER)
184
            id_el.set('type', 'purl')
185
        id_el.text = purl
186
187
    @property
188
    def agents(self):
189
        """
190
        List all :py:class:`ocrd_models.ocrd_agent.OcrdAgent`s
191
        """
192
        return [OcrdAgent(el_agent) for el_agent in self._tree.getroot().findall('mets:metsHdr/mets:agent', NS)]
193
194
    def add_agent(self, *args, **kwargs):
195
        """
196
        Add an :py:class:`ocrd_models.ocrd_agent.OcrdAgent` to the list of agents in the ``metsHdr``.
197
        """
198
        el_metsHdr = self._tree.getroot().find('.//mets:metsHdr', NS)
199
        if el_metsHdr is None:
200
            el_metsHdr = ET.Element(TAG_METS_METSHDR)
201
            self._tree.getroot().insert(0, el_metsHdr)
202
        #  assert(el_metsHdr is not None)
203
        el_agent = ET.SubElement(el_metsHdr, TAG_METS_AGENT)
204
        #  print(ET.tostring(el_metsHdr))
205
        return OcrdAgent(el_agent, *args, **kwargs)
206
207
    @property
208
    def file_groups(self):
209
        """
210
        List the `@USE` of all `mets:fileGrp` entries.
211
        """
212
213
        # WARNING: Actually we cannot return strings in place of elements!
214
        if self._cache_flag:
215
           return list(self._file_cache.keys())
216
217
        return [el.get('USE') for el in self._tree.getroot().findall('.//mets:fileGrp', NS)]
218
219
    def find_all_files(self, *args, **kwargs):
220
        """
221
        Like :py:meth:`find_files` but return a list of all results.
222
        Equivalent to ``list(self.find_files(...))``
223
        """
224
        return list(self.find_files(*args, **kwargs))
225
226
    # pylint: disable=multiple-statements
227
    def find_files(self, ID=None, fileGrp=None, pageId=None, mimetype=None, url=None, local_only=False):
228
        """
229
        Search ``mets:file`` entries in this METS document and yield results.
230
        The :py:attr:`ID`, :py:attr:`pageId`, :py:attr:`fileGrp`,
231
        :py:attr:`url` and :py:attr:`mimetype` parameters can each be either a
232
        literal string, or a regular expression if the string starts with
233
        ``//`` (double slash).
234
        If it is a regex, the leading ``//`` is removed and candidates are matched
235
        against the regex with `re.fullmatch`. If it is a literal string, comparison
236
        is done with string equality.
237
        The :py:attr:`pageId` parameter supports the numeric range operator ``..``. For
238
        example, to find all files in pages ``PHYS_0001`` to ``PHYS_0003``,
239
        ``PHYS_0001..PHYS_0003`` will be expanded to ``PHYS_0001,PHYS_0002,PHYS_0003``.
240
        Keyword Args:
241
            ID (string) : ``@ID`` of the ``mets:file``
242
            fileGrp (string) : ``@USE`` of the ``mets:fileGrp`` to list files of
243
            pageId (string) : ``@ID`` of the corresponding physical ``mets:structMap`` entry (physical page)
244
            url (string) : ``@xlink:href`` (URL or path) of ``mets:Flocat`` of ``mets:file``
245
            mimetype (string) : ``@MIMETYPE`` of ``mets:file``
246
            local (boolean) : Whether to restrict results to local files in the filesystem
247
        Yields:
248
            :py:class:`ocrd_models:ocrd_file:OcrdFile` instantiations
249
        """
250
        pageId_list = []
251
        if pageId:
252
            pageId_patterns = []
253
            for pageId_token in re.split(r',', pageId):
254
                if pageId_token.startswith(REGEX_PREFIX):
255
                    pageId_patterns.append(re.compile(pageId_token[REGEX_PREFIX_LEN:]))
256
                elif '..' in pageId_token:
257
                    pageId_patterns += generate_range(*pageId_token.split('..', 1))
258
                else:
259
                    pageId_patterns += [pageId_token]
260
            if self._cache_flag:
261
                for page_id in self._page_cache.keys():
262
                    if page_id in pageId_patterns or \
263
                        any([isinstance(p, typing.Pattern) and p.fullmatch(page_id) for p in pageId_patterns]):
264
                        pageId_list += self._fptr_cache[page_id]
265
            else:
266
                for page in self._tree.getroot().xpath(
267
                    '//mets:div[@TYPE="page"]', namespaces=NS):
268
                    if page.get('ID') in pageId_patterns or \
269
                        any([isinstance(p, typing.Pattern) and p.fullmatch(page.get('ID')) for p in pageId_patterns]):
270
                        pageId_list += [fptr.get('FILEID') for fptr in page.findall('mets:fptr', NS)]
271
272
        if ID and ID.startswith(REGEX_PREFIX):
273
            ID = re.compile(ID[REGEX_PREFIX_LEN:])
274
        if fileGrp and fileGrp.startswith(REGEX_PREFIX):
275
            fileGrp = re.compile(fileGrp[REGEX_PREFIX_LEN:])
276
        if mimetype and mimetype.startswith(REGEX_PREFIX):
277
            mimetype = re.compile(mimetype[REGEX_PREFIX_LEN:])
278
        if url and url.startswith(REGEX_PREFIX):
279
            url = re.compile(url[REGEX_PREFIX_LEN:])
280
            
281
        candidates = []
282
        if self._cache_flag:
283
            if fileGrp:
284
                if isinstance(fileGrp, str):
285
                    candidates += self._file_cache.get(fileGrp, {}).values()
286
                else:
287
                    candidates = [x for fileGrp_needle, el_file_list in self._file_cache.items() if fileGrp.match(fileGrp_needle) for x in el_file_list.values()]
288
            else:
289
                candidates = [el_file for id_to_file in self._file_cache.values() for el_file in id_to_file.values()]
290
        else:
291
            candidates = self._tree.getroot().xpath('//mets:file', namespaces=NS)
292
            
293
        for cand in candidates:
294
            if ID:
295
                if isinstance(ID, str):
296
                    if not ID == cand.get('ID'): continue
297
                else:
298
                    if not ID.fullmatch(cand.get('ID')): continue
299
300
            if pageId is not None and cand.get('ID') not in pageId_list:
301
                continue
302
303
            if not self._cache_flag and fileGrp:
304
                if isinstance(fileGrp, str):
305
                    if cand.getparent().get('USE') != fileGrp: continue
306
                else:
307
                    if not fileGrp.fullmatch(cand.getparent().get('USE')): continue
308
309
            if mimetype:
310
                if isinstance(mimetype, str):
311
                    if cand.get('MIMETYPE') != mimetype: continue
312
                else:
313
                    if not mimetype.fullmatch(cand.get('MIMETYPE') or ''): continue
314
315
            if url:
316
                cand_locat = cand.find('mets:FLocat', namespaces=NS)
317
                if cand_locat is None:
318
                    continue
319
                cand_url = cand_locat.get('{%s}href' % NS['xlink'])
320
                if isinstance(url, str):
321
                    if cand_url != url: continue
322
                else:
323
                    if not url.fullmatch(cand_url): continue
324
325
            # Note: why we instantiate a class only to find out that the local_only is set afterwards
326
            # Checking local_only and url before instantiation should be better?
327
            f = OcrdFile(cand, mets=self)
328
329
            # If only local resources should be returned and f is not a file path: skip the file
330
            if local_only and not is_local_filename(f.url):
331
                continue
332
            yield f
333
334
    def add_file_group(self, fileGrp):
335
        """
336
        Add a new ``mets:fileGrp``.
337
        Arguments:
338
            fileGrp (string): ``@USE`` of the new ``mets:fileGrp``.
339
        """
340
        if ',' in fileGrp:
341
            raise Exception('fileGrp must not contain commas')
342
        el_fileSec = self._tree.getroot().find('mets:fileSec', NS)
343
        if el_fileSec is None:
344
            el_fileSec = ET.SubElement(self._tree.getroot(), TAG_METS_FILESEC)
345
        el_fileGrp = el_fileSec.find('mets:fileGrp[@USE="%s"]' % fileGrp, NS)
346
        if el_fileGrp is None:
347
            el_fileGrp = ET.SubElement(el_fileSec, TAG_METS_FILEGRP)
348
            el_fileGrp.set('USE', fileGrp)
349
            
350
            if self._cache_flag:
351
                # Assign an empty dictionary that will hold the files of the added fileGrp
352
                self._file_cache[fileGrp] = {}
353
                
354
        return el_fileGrp
355
356
    def rename_file_group(self, old, new):
357
        """
358
        Rename a ``mets:fileGrp`` by changing the ``@USE`` from :py:attr:`old` to :py:attr:`new`.
359
        """
360
        el_fileGrp = self._tree.getroot().find('mets:fileSec/mets:fileGrp[@USE="%s"]' % old, NS)
361
        if el_fileGrp is None:
362
            raise FileNotFoundError("No such fileGrp '%s'" % old)
363
        el_fileGrp.set('USE', new)
364
        
365
        if self._cache_flag:
366
            self._file_cache[new] = self._file_cache.pop(old)
367
368
    def remove_file_group(self, USE, recursive=False, force=False):
369
        """
370
        Remove a ``mets:fileGrp`` (single fixed ``@USE`` or multiple regex ``@USE``)
371
        Arguments:
372
            USE (string): ``@USE`` of the ``mets:fileGrp`` to delete. Can be a regex if prefixed with ``//``
373
            recursive (boolean): Whether to recursively delete each ``mets:file`` in the group
374
            force (boolean): Do not raise an exception if ``mets:fileGrp`` does not exist
375
        """
376
        log = getLogger('ocrd_models.ocrd_mets.remove_file_group')
377
        el_fileSec = self._tree.getroot().find('mets:fileSec', NS)
378
        if el_fileSec is None:
379
            raise Exception("No fileSec!")
380
        if isinstance(USE, str):
381
            if USE.startswith(REGEX_PREFIX):
382
                use = re.compile(USE[REGEX_PREFIX_LEN:])
383
                for cand in el_fileSec.findall('mets:fileGrp', NS):
384
                    if use.fullmatch(cand.get('USE')):
385
                        self.remove_file_group(cand, recursive=recursive)
386
                return
387
            else:
388
                el_fileGrp = el_fileSec.find('mets:fileGrp[@USE="%s"]' % USE, NS)
389
        else:
390
            el_fileGrp = USE
391
        if el_fileGrp is None:   # pylint: disable=len-as-condition
392
            msg = "No such fileGrp: %s" % USE
393
            if force:
394
                log.warning(msg)
395
                return
396
            raise Exception(msg)
397
398
        # The cache should also be used here
399
        if self._cache_flag:
400
            files = self._file_cache.get(el_fileGrp.get('USE'), {}).values()
401
        else:
402
            files = el_fileGrp.findall('mets:file', NS)
403
404
        if files:
405
            if not recursive:
406
                raise Exception("fileGrp %s is not empty and recursive wasn't set" % USE)
407
            for f in files:
408
                # NOTE: Here we know the fileGrp, we should pass it as a parameter
409
                self.remove_one_file(ID=f.get('ID'), fileGrp=f.get('USE'))
410
411
        if self._cache_flag:
412
            # Note: Since the files inside the group are removed
413
            # with the 'remove_one_file' method above, 
414
            # we should not take care of that again.
415
            # We just remove the fileGrp.
416
            del self._file_cache[el_fileGrp.get('USE')]
417
            
418
        el_fileGrp.getparent().remove(el_fileGrp)
419
420
    def add_file(self, fileGrp, mimetype=None, url=None, ID=None, pageId=None, force=False, local_filename=None, ignore=False, **kwargs):
421
        """
422
        Instantiate and add a new :py:class:`ocrd_models.ocrd_file.OcrdFile`.
423
        Arguments:
424
            fileGrp (string): ``@USE`` of ``mets:fileGrp`` to add to
425
        Keyword Args:
426
            mimetype (string): ``@MIMETYPE`` of the ``mets:file`` to use
427
            url (string): ``@xlink:href`` (URL or path) of the ``mets:file`` to use
428
            ID (string): ``@ID`` of the ``mets:file`` to use
429
            pageId (string): ``@ID`` in the physical ``mets:structMap`` to link to
430
            force (boolean): Whether to add the file even if a ``mets:file`` with the same ``@ID`` already exists.
431
            ignore (boolean): Do not look for existing files at all. Shift responsibility for preventing errors from duplicate ID to the user.
432
            local_filename (string):
433
        """
434
        if not ID:
435
            raise ValueError("Must set ID of the mets:file")
436
        if not fileGrp:
437
            raise ValueError("Must set fileGrp of the mets:file")
438
        if not REGEX_FILE_ID.fullmatch(ID):
439
            raise ValueError("Invalid syntax for mets:file/@ID %s (not an xs:ID)" % ID)
440
        if not REGEX_FILE_ID.fullmatch(fileGrp):
441
            raise ValueError("Invalid syntax for mets:fileGrp/@USE %s (not an xs:ID)" % fileGrp)
442
        log = getLogger('ocrd_models.ocrd_mets.add_file')
443
444
        el_fileGrp = self.add_file_group(fileGrp)
445
        if not ignore:
446
            mets_file = next(self.find_files(ID=ID, fileGrp=fileGrp), None)
447
            if mets_file:
448
                if mets_file.fileGrp == fileGrp and \
449
                   mets_file.pageId == pageId and \
450
                   mets_file.mimetype == mimetype:
451
                    if not force:
452
                        raise FileExistsError(f"A file with ID=={ID} already exists {mets_file} and neither force nor ignore are set")
453
                    self.remove_file(ID=ID, fileGrp=fileGrp)
454
                else:
455
                    raise FileExistsError(f"A file with ID=={ID} already exists {mets_file} but unrelated - cannot mitigate")
456
457
        # To get rid of Python's FutureWarning - checking if v is not None
458
        kwargs = {k: v for k, v in locals().items() if k in ['url', 'ID', 'mimetype', 'pageId', 'local_filename'] and v is not None}
459
        # This separation is needed to reuse the same el_mets_file element in the caching if block
460
        el_mets_file = ET.SubElement(el_fileGrp, TAG_METS_FILE)
461
        # The caching of the physical page is done in the OcrdFile constructor
462
        mets_file = OcrdFile(el_mets_file, mets=self, **kwargs)
463
464
        if self._cache_flag:
465
            # Add the file to the file cache
466
            self._file_cache[fileGrp].update({ID: el_mets_file})
467
468
        return mets_file
469
470
    def remove_file(self, *args, **kwargs):
471
        """
472
        Delete each ``ocrd:file`` matching the query. Same arguments as :py:meth:`find_files`
473
        """
474
        files = list(self.find_files(*args, **kwargs))
475
        if files:
476
            for f in files:
477
                self.remove_one_file(f)
478
            if len(files) > 1:
479
                return files
480
            else:
481
                return files[0] # for backwards-compatibility
482
        if any(1 for kwarg in kwargs
483
               if isinstance(kwarg, str) and kwarg.startswith(REGEX_PREFIX)):
484
            # allow empty results if filter criteria involve a regex
485
            return []
486
        raise FileNotFoundError("File not found: %s %s" % (args, kwargs))
487
488
    def remove_one_file(self, ID, fileGrp=None):
489
        """
490
        Delete an existing :py:class:`ocrd_models.ocrd_file.OcrdFile`.
491
        Arguments:
492
            ID (string): ``@ID`` of the ``mets:file`` to delete 
493
            -> ID could also be an OcrdFile, potentially misleading?
494
            fileGrp (string):
495
        Returns:
496
            The old :py:class:`ocrd_models.ocrd_file.OcrdFile` reference.
497
        """
498
        log = getLogger('ocrd_models.ocrd_mets.remove_one_file')
499
        log.debug("remove_one_file(%s %s)" % (ID, fileGrp))
500
        if isinstance(ID, OcrdFile):
501
            ocrd_file = ID
502
            ID = ocrd_file.ID
503
            # fileGrp = ocrd_file.fileGrp 
504
            # -> could this potentially help to improve the cached approach?
505
        else:
506
            ocrd_file = next(self.find_files(ID=ID, fileGrp=fileGrp), None)
507
508
        if not ocrd_file:
509
            raise FileNotFoundError("File not found: %s" % ID)
510
511
        # Delete the physical page ref
512
        fptrs = []
513
        if self._cache_flag:
514
            for page in self._fptr_cache.keys():
515
                if ID in self._fptr_cache[page]:
516
                    fptrs.append(self._fptr_cache[page][ID])
517
        else:
518
            fptrs = self._tree.getroot().findall('.//mets:fptr[@FILEID="%s"]' % ID, namespaces=NS)
519
520
        # Delete the physical page ref
521
        for fptr in fptrs:
522
            log.debug("Delete fptr element %s for page '%s'", fptr, ID)
523
            page_div = fptr.getparent()
524
            page_div.remove(fptr)
525
            # Remove the fptr from the cache as well
526
            if self._cache_flag:
527
                del self._fptr_cache[page_div.get('ID')][ID]
528
            # delete empty pages
529
            if not page_div.getchildren():
530
                log.debug("Delete empty page %s", page_div)
531
                page_div.getparent().remove(page_div)
532
                # Delete the empty pages from caches as well
533
                if self._cache_flag:
534
                    del self._page_cache[page_div.get('ID')]
535
                    del self._fptr_cache[page_div.get('ID')]
536
537
        # Delete the file reference from the cache
538
        if self._cache_flag:
539
            parent_use = ocrd_file._el.getparent().get('USE')
540
            del self._file_cache[parent_use][ocrd_file.ID]
541
542
        # Delete the file reference
543
        # pylint: disable=protected-access
544
        ocrd_file._el.getparent().remove(ocrd_file._el)
545
546
        return ocrd_file
547
548
    @property
549
    def physical_pages(self):
550
        """
551
        List all page IDs (the ``@ID`` of each physical ``mets:structMap`` ``mets:div``)
552
        """
553
        if self._cache_flag:
554
            return self._page_cache.values()
555
            
556
        return self._tree.getroot().xpath(
557
            'mets:structMap[@TYPE="PHYSICAL"]/mets:div[@TYPE="physSequence"]/mets:div[@TYPE="page"]/@ID',
558
            namespaces=NS)
559
560
    def get_physical_pages(self, for_fileIds=None):
561
        """
562
        List all page IDs (the ``@ID`` of each physical ``mets:structMap`` ``mets:div``),
563
        optionally for a subset of ``mets:file`` ``@ID`` :py:attr:`for_fileIds`.
564
        """
565
        if for_fileIds is None:
566
            return self.physical_pages
567
        ret = [None] * len(for_fileIds)
568
        
569
        if self._cache_flag:
570
            for pageId in self._fptr_cache.keys():
571
                for fptr in self._fptr_cache[pageId].keys():
572
                    if fptr in for_fileIds:
573
                        ret[for_fileIds.index(fptr)] = pageId
574
        else:
575
          for page in self._tree.getroot().xpath(
576
              'mets:structMap[@TYPE="PHYSICAL"]/mets:div[@TYPE="physSequence"]/mets:div[@TYPE="page"]',
577
                  namespaces=NS):
578
              for fptr in page.findall('mets:fptr', NS):
579
                  if fptr.get('FILEID') in for_fileIds:
580
                      ret[for_fileIds.index(fptr.get('FILEID'))] = page.get('ID')
581
        return ret
582
583
    def set_physical_page_for_file(self, pageId, ocrd_file, order=None, orderlabel=None):
584
        """
585
        Set the physical page ID (``@ID`` of the physical ``mets:structMap`` ``mets:div`` entry)
586
        corresponding to the ``mets:file`` :py:attr:`ocrd_file`, creating all structures if necessary.
587
        Arguments:
588
            pageId (string): ``@ID`` of the physical ``mets:structMap`` entry to use
589
            ocrd_file (object): existing :py:class:`ocrd_models.ocrd_file.OcrdFile` object
590
        Keyword Args:
591
            order (string): ``@ORDER`` to use
592
            orderlabel (string): ``@ORDERLABEL`` to use
593
        """
594
595
        # delete any page mapping for this file.ID
596
        candidates = []
597
        if self._cache_flag:
598
            for page_id in self._fptr_cache.keys():
599
                if ocrd_file.ID in self._fptr_cache[page_id].keys():
600
                    if self._fptr_cache[page_id][ocrd_file.ID] is not None:
601
                        candidates.append(self._fptr_cache[page_id][ocrd_file.ID])
602
        else:
603
            candidates = self._tree.getroot().findall(
604
                'mets:structMap[@TYPE="PHYSICAL"]/mets:div[@TYPE="physSequence"]/mets:div[@TYPE="page"]/mets:fptr[@FILEID="%s"]' %
605
                ocrd_file.ID, namespaces=NS)
606
607
        for el_fptr in candidates:
608
            if self._cache_flag:
609
                del self._fptr_cache[el_fptr.getparent().get('ID')][ocrd_file.ID]
610
            el_fptr.getparent().remove(el_fptr)
611
612
        # find/construct as necessary
613
        el_structmap = self._tree.getroot().find('mets:structMap[@TYPE="PHYSICAL"]', NS)
614
        if el_structmap is None:
615
            el_structmap = ET.SubElement(self._tree.getroot(), TAG_METS_STRUCTMAP)
616
            el_structmap.set('TYPE', 'PHYSICAL')
617
        el_seqdiv = el_structmap.find('mets:div[@TYPE="physSequence"]', NS)
618
        if el_seqdiv is None:
619
            el_seqdiv = ET.SubElement(el_structmap, TAG_METS_DIV)
620
            el_seqdiv.set('TYPE', 'physSequence')
621
        
622
        el_pagediv = None
623
        if self._cache_flag:
624
            if pageId in self._page_cache.keys():
625
                el_pagediv = self._page_cache[pageId]
626
        else:
627
            el_pagediv = el_seqdiv.find('mets:div[@ID="%s"]' % pageId, NS)
628
        
629
        if el_pagediv is None:
630
            el_pagediv = ET.SubElement(el_seqdiv, TAG_METS_DIV)
631
            el_pagediv.set('TYPE', 'page')
632
            el_pagediv.set('ID', pageId)
633
            if order:
634
                el_pagediv.set('ORDER', order)
635
            if orderlabel:
636
                el_pagediv.set('ORDERLABEL', orderlabel)
637
            if self._cache_flag:
638
                # Create a new entry in the page cache
639
                self._page_cache[pageId] = el_pagediv
640
                # Create a new entry in the fptr cache and 
641
                # assign an empty dictionary to hold the fileids
642
                self._fptr_cache[pageId] = {}
643
                
644
        el_fptr = ET.SubElement(el_pagediv, TAG_METS_FPTR)
645
        el_fptr.set('FILEID', ocrd_file.ID)
646
647
        if self._cache_flag:
648
            # Assign the ocrd fileID to the pageId in the cache
649
            self._fptr_cache[el_pagediv.get('ID')].update({ocrd_file.ID : el_fptr})
650
651
    def get_physical_page_for_file(self, ocrd_file):
652
        """
653
        Get the physical page ID (``@ID`` of the physical ``mets:structMap`` ``mets:div`` entry)
654
        corresponding to the ``mets:file`` :py:attr:`ocrd_file`.
655
        """
656
        ret = []
657
        if self._cache_flag:
658
            for pageId in self._fptr_cache.keys():
659
                if ocrd_file.ID in self._fptr_cache[pageId].keys():
660
                    ret.append(self._page_cache[pageId].get('ID'))
661
        else:
662
            ret = self._tree.getroot().xpath(
663
                '/mets:mets/mets:structMap[@TYPE="PHYSICAL"]/mets:div[@TYPE="physSequence"]/mets:div[@TYPE="page"][./mets:fptr[@FILEID="%s"]]/@ID' %
664
                ocrd_file.ID, namespaces=NS)
665
666
        # To get rid of the python's FutureWarning
667
        if len(ret):
668
            return ret[0]
669
670
    def remove_physical_page(self, ID):
671
        """
672
        Delete page (physical ``mets:structMap`` ``mets:div`` entry ``@ID``) :py:attr:`ID`.
673
        """
674
        mets_div = None
675
        if self._cache_flag:
676
            if ID in self._page_cache.keys():
677
                mets_div = [self._page_cache[ID]]
678
        else:
679
            mets_div = self._tree.getroot().xpath(
680
                'mets:structMap[@TYPE="PHYSICAL"]/mets:div[@TYPE="physSequence"]/mets:div[@TYPE="page"][@ID="%s"]' % ID,
681
                namespaces=NS)
682
        if mets_div is not None:
683
            mets_div[0].getparent().remove(mets_div[0])
684
            if self._cache_flag:
685
                del self._page_cache[ID]
686
                del self._fptr_cache[ID]
687
688
    def remove_physical_page_fptr(self, fileId):
689
        """
690
        Delete all ``mets:fptr[@FILEID = fileId]`` to ``mets:file[@ID == fileId]`` for :py:attr:`fileId` from all ``mets:div`` entries in the physical ``mets:structMap``.
691
        Returns:
692
            List of pageIds that mets:fptrs were deleted from
693
        """
694
695
        # Question: What is the reason to keep a list of mets_fptrs?
696
        # Do we have a situation in which the fileId is same for different pageIds ?
697
        # From the examples I have seen inside 'assets' that is not the case
698
        # and the mets_fptrs list will always contain a single element.
699
        # If that's the case then we do not need to iterate 2 loops, just one.
700
        mets_fptrs = []
701
        if self._cache_flag:
702
            for page_id in self._fptr_cache.keys():
703
                if fileId in self._fptr_cache[page_id].keys():
704
                    mets_fptrs.append(self._fptr_cache[page_id][fileId]) 
705
        else:
706
            mets_fptrs = self._tree.getroot().xpath(
707
                'mets:structMap[@TYPE="PHYSICAL"]/mets:div[@TYPE="physSequence"]/mets:div[@TYPE="page"]/mets:fptr[@FILEID="%s"]' % fileId, namespaces=NS)
708
        ret = []
709
        for mets_fptr in mets_fptrs:
710
            mets_div = mets_fptr.getparent()
711
            ret.append(mets_div.get('ID'))
712
            if self._cache_flag:
713
                del self._fptr_cache[mets_div.get('ID')][mets_fptr.get('FILEID')]
714
            mets_div.remove(mets_fptr)
715
        return ret
716
717
    def merge(self, other_mets, force=False, fileGrp_mapping=None, fileId_mapping=None, pageId_mapping=None, after_add_cb=None, **kwargs):
718
        """
719
        Add all files from other_mets.
720
        Accepts the same kwargs as :py:func:`find_files`
721
        Keyword Args:
722
            force (boolean): Whether to :py:meth:`add_file`s with force (overwriting existing ``mets:file``s)
723
            fileGrp_mapping (dict): Map :py:attr:`other_mets` fileGrp to fileGrp in this METS
724
            fileId_mapping (dict): Map :py:attr:`other_mets` file ID to file ID in this METS
725
            pageId_mapping (dict): Map :py:attr:`other_mets` page ID to page ID in this METS
726
            after_add_cb (function): Callback received after file is added to the METS
727
        """
728
        if not fileGrp_mapping:
729
            fileGrp_mapping = {}
730
        if not fileId_mapping:
731
            fileId_mapping = {}
732
        if not pageId_mapping:
733
            pageId_mapping = {}
734
        for f_src in other_mets.find_files(**kwargs):
735
            f_dest = self.add_file(
736
                    fileGrp_mapping.get(f_src.fileGrp, f_src.fileGrp),
737
                    mimetype=f_src.mimetype,
738
                    url=f_src.url,
739
                    ID=fileId_mapping.get(f_src.ID, f_src.ID),
740
                    pageId=pageId_mapping.get(f_src.pageId, f_src.pageId),
741
                    force=force)
742
            # FIXME: merge metsHdr, amdSec, dmdSec as well
743
            # FIXME: merge structMap logical and structLink as well
744
            if after_add_cb:
745
                after_add_cb(f_dest)
746