Coverage for /usr/local/lib/python3.11/site-packages/tgclients/utils.py: 100%
23 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-02 16:49 +0000
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-02 16:49 +0000
1# SPDX-FileCopyrightText: 2022 Georg-August-Universität Göttingen
2#
3# SPDX-License-Identifier: LGPL-3.0-or-later
5"""Utility functions for working with the TextGrid repository"""
6from pathlib import Path
7from typing import List
9import defusedxml.ElementTree as ET
10from jinja2 import Environment, FileSystemLoader
12from tgclients.databinding.tgsearch import Response as SearchResponse
15class Utils:
16 """Utility functions for working with the TextGrid repository"""
18 @staticmethod
19 def list_to_aggregation(textgrid_uri: str, members: List[str]) -> str:
20 """Create XML for a TextGrid aggregation from list
22 Args:
23 textgrid_uri (str): textgrid URI of the aggregation to create
24 members (list[str]): list of textgrid URIs inside aggregation
26 Returns:
27 str: XML for TextGrid Aggregation
28 """
29 path = Path(__file__).parent / 'templates'
30 env = Environment(
31 loader=FileSystemLoader(Path(path)), autoescape=True)
32 template = env.get_template('aggregation.xml.jinja2')
33 aggregation = template.render(id=textgrid_uri, members=members)
34 return aggregation
36 @staticmethod
37 def aggregation_to_list(xml: str) -> List[str]:
38 """Extract URIs from TextGrid aggregation into a list
40 Args:
41 xml (str): TextGrid aggregation XML
43 Returns:
44 list[str]: TextGrid URIs from aggregation
45 """
46 res = []
47 root = ET.fromstring(xml)
48 tag_name = '{http://www.openarchives.org/ore/terms/}aggregates'
49 attr_name = '{http://www.w3.org/1999/02/22-rdf-syntax-ns#}resource'
50 for descendant in root.iter(tag_name):
51 res.append(descendant.attrib[attr_name])
52 return res