python-lottie  0.7.0+dev66cafb9
A framework to work with lottie files and telegram animated stickers (tgs)
utils.py
Go to the documentation of this file.
1 from xml.dom import minidom
2 from distutils.util import strtobool
3 
4 from lottie.nvector import NVector
5 from lottie.parsers.sif.sif.frame_time import FrameTime
6 
7 
8 class _tag:
9  def __init__(self, type):
10  self.typetype = type
11 
12  def __call__(self, v):
13  return self.typetype(v)
14 
15 
16 bool_str = _tag(bool)
17 
18 
19 def str_to_bool(strval):
20  return bool(strtobool(strval))
21 
22 
23 def value_from_xml_string(xml_str, type, registry):
24  if type in (bool_str, bool):
25  return str_to_bool(xml_str)
26  elif type is NVector:
27  return NVector(*map(float, xml_str.split()))
28  if type is FrameTime:
29  return FrameTime.parse_string(xml_str, registry)
30  return type(xml_str)
31 
32 
33 def value_to_xml_string(value, type):
34  if type is bool:
35  return "1" if value else "0"
36  if type is bool_str:
37  return "true" if value else "false"
38  elif type is NVector:
39  return " ".join(map(str, value))
40  return str(value)
41 
42 
43 def value_isinstance(value, type):
44  if isinstance(type, _tag):
45  type = type.type
46  return isinstance(value, type)
47 
48 
49 def xml_text(node):
50  return "".join(
51  x.nodeValue
52  for x in node.childNodes
53  if x.nodeType in {minidom.Node.TEXT_NODE, minidom.Node.CDATA_SECTION_NODE}
54  )
55 
56 
57 def xml_make_text(dom: minidom.Document, tag_name, text):
58  e = dom.createElement(tag_name)
59  e.appendChild(dom.createTextNode(text))
60  return e
61 
62 
63 def xml_element_matches(ch: minidom.Node, tagname=None):
64  if ch.nodeType != minidom.Node.ELEMENT_NODE:
65  return False
66 
67  if tagname is not None and ch.tagName != tagname:
68  return False
69 
70  return True
71 
72 
73 def xml_child_elements(xml: minidom.Node, tagname=None):
74  for ch in xml.childNodes:
75  if xml_element_matches(ch, tagname):
76  yield ch
77 
78 
79 def xml_first_element_child(xml: minidom.Node, tagname=None, allow_none=False):
80  for ch in xml_child_elements(xml, tagname):
81  return ch
82 
83  if allow_none:
84  return None
85  raise ValueError("No %s in %s" % (tagname or "child element", getattr(xml, "tagName", "node")))
def __init__(self, type)
Definition: utils.py:9
def xml_first_element_child(minidom.Node xml, tagname=None, allow_none=False)
Definition: utils.py:79
def xml_element_matches(minidom.Node ch, tagname=None)
Definition: utils.py:63
def xml_make_text(minidom.Document dom, tag_name, text)
Definition: utils.py:57
def xml_child_elements(minidom.Node xml, tagname=None)
Definition: utils.py:73
def value_to_xml_string(value, type)
Definition: utils.py:33
def str_to_bool(strval)
Definition: utils.py:19
def value_from_xml_string(xml_str, type, registry)
Definition: utils.py:23
def value_isinstance(value, type)
Definition: utils.py:43