PK!qIIsped_parser/__init__.pyfrom .nodes import SpedNode __version__ = '0.2.0' __all__ = [SpedNode] PK!e88sped_parser/compare.pyimport sys if __name__ == '__main__': f1, f2 = sys.argv[1:] with open(f1) as fh1, open(f2) as fh2: data1 = list(l.strip() for l in fh1 if l.strip()) data2 = list(l.strip() for l in fh2 if l.strip()) exit_code = 0 # assert lengths match if len(data1) != len(data2): print('WARNING: Files have different number non-blank lines.') exit_code = 1 sys.exit(exit_code) # find different content different_content_found = False for (i, j) in zip(data1, data2): if i != j: different_content_found = True print('WRONG!') print(i) print(j) print('---') exit_code = 1 if not different_content_found: print("No different content was found.") sys.exit(exit_code) PK!qwwsped_parser/nodes.pyfrom itertools import islice, takewhile from typing import List # Data model # ---------- class SpedNode: def __init__(self, content, children=[], parent=None): if isinstance(content, list): assert content for el in content: assert isinstance(el, str) self.values = content elif isinstance(content, str): if not content: content = '.' else: content = content.strip() if content[0] == "|" and content[-1] == "|": content = content[1:-1] self.values = content.split("|") self.children = list(children) for child_node in children: child_node.parent = self if parent and self not in parent.children: parent.insert(self) self.parent = parent @property def record_type(self): return self.values[0] def as_text(self): "renders a SpedNode as a sped-like file" self_content = '|' + '|'.join(self.values) + '|\n' children_content = ''.join(c.as_text() for c in self.children) return self_content + children_content def find_all(self, predicate): "return all direct " yield from (node for node in self if predicate(node)) def find(self, predicate): "returns the first occurence of node that passes the predicate test" iterator = islice(self.find_all(predicate), 1) return next(iterator) def get_node(self, record_type): "returns the first occurence of node for that record type" return next(self.get_nodes(record_type)) def get_nodes(self, record_type): "generates all descendant nodes that match the given record type" generator = self.find_all(lambda n: n.record_type == record_type) yield from generator def filter(self, predicate): """recursively removes child nodes whenever `predicate(child)` returns true""" self.children = [c for c in self.children if predicate(c)] for c in self.children: c.filter(predicate) def count(self): "returns number of nodes (including self)" return 1 + sum(c.count() for c in self.children) def update(self, index, new_value): "DEPRECATED. Use `node[index] = new_value` instead." self.values[index] = new_value def insert(self, node): "inserts a node into self.children in an appropriate position" # base case: children is an empty list if not self.children: self.children.append(node) else: pos = (idx for idx, sibling in enumerate(self.children) if sibling.record_type >= node.record_type) try: index = next(pos) except StopIteration: self.children.append(node) else: # using slices because `list.insert` causes RecursionErrors self.children = (self.children[:index] + [node] + self.children[index:]) node.parent = self def ancestors(self): yield self if self.parent: yield from self.parent.ancestors() def delete(self): self.parent.children.remove(self) def __eq__(self, other): if not isinstance(other, SpedNode): return False if self.values != other.values: return False if self.children != other.children: return False return True def __hash__(self): return hash(tuple(self.values)) def __iter__(self): yield self for child in self.children: yield from child def __getitem__(self, index): return self.values[index] def __setitem__(self, key, value): self.values[key] = value def __repr__(self): return "" % (repr(self.record_type),) # Parser utilities # ---------------- def sped_iterator(sped_file_handle): "simple iterator for sped files" def strip_line(text): "helper function for stripping unwanted characters out of sped lines" return text.strip()[1:-1] def predicate(text): try: return text[4] == '|' except IndexError: return False return takewhile(predicate, (strip_line(i) for i in sped_file_handle)) def build_forest(sped_file_path, record_relations): """reads a sped file and a relations dictionary and returns a list of nodes (forest). """ forest = [] tracker = {} with open(sped_file_path, encoding='latin-1') as f: for line in sped_iterator(f): node = SpedNode(line, []) tracker[node.record_type] = node parent_record_type = record_relations[node.record_type] parent = tracker.get(parent_record_type) if parent: parent.children.append(node) node.parent = parent else: forest.append(node) return forest # Forest functions # ---------------- Forest = List[SpedNode] def forest_iterator(forest: Forest): for node in forest: yield from node def forest_find_all(forest: Forest, predicate): for node in forest: yield from node.find_all(predicate) def forest_find(forest: Forest, predicate): return next(islice(forest_find_all(forest, predicate), 1)) def forest_get_node(forest: Forest, record_type): return forest_find(forest, lambda n: n.record_type == record_type) def forest_get_nodes(forest: Forest, record_type): yield from forest_find_all(forest, lambda n: n.record_type == record_type) def forest_as_text(forest: Forest): "serializes a forest as a sped file" return ''.join(node.as_text() for node in forest) def forest_size(forest): "returns the count of all nodes inside a forest" return sum(tree.count() for tree in forest) def forest_size_by_prefix(forest, prefix): "returns the count of all forest nodes for a given record_type prefix" return sum(tree.count() for tree in forest if tree.record_type.startswith(prefix)) PK!b }rrsped_parser/record_relations.pyimport json from xml.etree.ElementTree import iterparse def relations(json_file_path): "reads a sped specification file and return a children-to-parent mapping" with open(json_file_path) as f: data = json.load(f) return dict((i['name'], i['parent_record']) for i in data) def build_relations_from_xml(filepath): "reads a xml specification (PVA) and return a child-to-parent mapping" hierarchy = {} records = [] for (event, node) in iterparse(filepath, events=['start', 'end']): if event == 'start' and node.tag == 'registro': records.append(node.attrib['id']) if event == 'end' and node.tag == 'registro': child = records.pop() try: parent = records[-1] except IndexError: parent = None hierarchy[child] = parent return hierarchy PK!'11#sped_parser-0.2.0.dist-info/LICENSEMIT License Copyright (c) 2019 Tiago Guimarães Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PK!HڽTU!sped_parser-0.2.0.dist-info/WHEEL A н#Z;/"d&F[xzw@Zpy3Fv]\fi4WZ^EgM_-]#0(q7PK!H`S$sped_parser-0.2.0.dist-info/METADATAN0 Eڎ iR Ll0mWdZ5qHRPTH[b_{%%l0aD!8 Xݣ% SSx iq9RZ }b"جICQ݊H73bgu^lRNNO-ȯL~Zf39 kd:ixM/*ިNzaM^"' _/PK!HQu"sped_parser-0.2.0.dist-info/RECORD}ˎ@}? %Y\EfS(hxfޝ՗68CMQ}"TEЬaA&uXh='@fQH 6䖋 VM03 _w|ǷSѳB'gAA|jab-;9r3f<8Ոqy!0@8KZSee~uE>_{*yR^ȿrv&)yA(< 30 E}!ַI/Gw7%Dy: KـԤ75OOy=MʶFž(5;S/-0(SV~u==T55T4Lsq.6̓v GG6UY‰k?8/PK!qIIsped_parser/__init__.pyPK!e88~sped_parser/compare.pyPK!qwwsped_parser/nodes.pyPK!b }rrsped_parser/record_relations.pyPK!'11#B sped_parser-0.2.0.dist-info/LICENSEPK!HڽTU!$sped_parser-0.2.0.dist-info/WHEELPK!H`S$G%sped_parser-0.2.0.dist-info/METADATAPK!HQu"&sped_parser-0.2.0.dist-info/RECORDPKZf(