def plot(self): """ Draw an interactive python figure containing the tree for the created schedule. """ sl.draw_tree(self.tree)
def run_polarization(self, binary_dep, relation, replaced, sentence): self.polarizer.dependtree = binary_dep self.polarizer.relation = relation self.polarizer.replaced = replaced self.polarizer.polarize_deptree() if self.verbose == 2: self.postprocess(binary_dep) elif self.verbose == 1: polarized = self.postprocess(binary_dep) svgling.draw_tree(polarized)
def plot_tree(sent: str, cnf: bool = False) -> None: """Plot sent's tree using svgling.draw_tree.""" tree = parser.parse(sent) if cnf: tree.chomsky_normal_form() if callable(display): display(svgling.draw_tree(tree)) else: show_tree(tree)
def buildPrintedResults(apparentWinner, apparentNonWinnersWithNames, WOLosers,IRVElims): elimTrees=[] apparentNonWinners = [c[0] for c in apparentNonWinnersWithNames] for c in apparentNonWinnersWithNames: candidateSet=set(apparentNonWinners).copy() candidateSet.add(apparentWinner) candidateSet.remove(c[0]) treeAsLists=buildRemainingTreeAsLists(c[0],candidateSet, WOLosers, IRVElims) treeAsTuples=treeListToTuple(treeAsLists) drawnTree = svgling.draw_tree(treeAsTuples) elimTrees.append(Caption(drawnTree,"Pruned tree in which "+printTuple(c)+" wins.")) return elimTrees
def write_svgtree(tree, output_file=None): """convert an nltk.tree into an SVG file using svgling.""" # We're not importing svgling globally because it monkey-patches # nltk's tree drawing mechanism, i.e. all trees in Jupyter will # look different when importing svgling. import svgling svgling.disable_nltk_png() tree_layout = svgling.draw_tree(tree) drawing = tree_layout.get_svg() if output_file is None: # return string representation of SVG image f = io.StringIO() drawing.write(f) return f.getvalue() else: drawing.saveas(output_file)
def tree2png(treestring, outname): IMAGE_DIR = BASE_DIR + 'web/static/images/' # convert treestring to a tree using nltk t = Tree.fromstring(treestring) # draw an svg from the tree img = svgling.draw_tree(t) svg_data = img.get_svg() # save the svg file to the disk print('writing generated svg to disk..') with open(IMAGE_DIR + 'tmp.svg', 'w', encoding='utf-8') as fp: svg_data.write(fp, pretty=True, indent=2) # return svg_data print('conveting from svg to png..') p_convert = subprocess.run(['rsvg-convert', IMAGE_DIR + 'tmp.svg', '-o', IMAGE_DIR + outname], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) print('The image file is written to disk:', IMAGE_DIR + outname) print((p_convert.stdout).decode()) print('cleaning up svg..') os.remove(IMAGE_DIR + 'tmp.svg')
def main(): #svgディレクトリがなければ作る if not os.path.exists(SVG_DATA_PATH): os.mkdir(SVG_DATA_PATH) #svgディレクトリの中身を調べる files = os.listdir(SVG_DATA_PATH) if files: #なんか入ってたら shutil.rmtree(SVG_DATA_PATH) #消して os.mkdir(SVG_DATA_PATH) #作る #tempフォルダ内のファイルを読み込む files = glob.glob(PKL_DATA_PATH) print(files) for step_idx, pkl_file_name in enumerate(files): #svgファイルの保存場所確保 step_num = os.path.splitext(os.path.basename(pkl_file_name))[0] svg_save_dir = SVG_DATA_PATH + step_num if not os.path.exists(svg_save_dir): os.makedirs(svg_save_dir) #pkl展開->tree書き出し trees = pd.read_pickle(pkl_file_name) # print(trees) for idx, tree in enumerate(trees): if idx < DRAWING_THRESHOLD: data = tree['tree'] svg_image = svgling.draw_tree(data, leaf_nodes_align=True) # id あり # svg_image.get_svg().saveas(svg_save_dir+"/"+ "rank_" + str(idx) +"id_"+str(tree['id'])+"prob_"+str(tree['prob'])+".svg",pretty=True) # id なし svg_image.get_svg().saveas(svg_save_dir + "/" + '{0:03d}'.format(idx) + ".svg", pretty=True)
def writeToFile(treestr, filename): import svgling tree = svgling.draw_tree(treestr) svgobj = tree.get_svg() svgobj.filename = filename svgobj.save()
def do_GET(self): # Sending an '200 OK' response self.send_response(200) query_components = parse_qs(urlparse(self.path).query) if query_components != None: print(query_components) tree = ET.parse('tree.xml') name = None addAs = None ref = None if 'addAs' in query_components: addAs = query_components["addAs"][0] if 'name' in query_components: name = query_components["name"][0] if 'ref' in query_components: ref = query_components["ref"][0] if 'delete' in query_components: for elem in tree.iter(): if 'text' in elem.attrib: if elem.attrib['text'] == name: parent = elem.getparent() children = elem.getchildren() parent.remove(elem) it = 0 while it < len(children): parent.append(children[it]) it += 1 with open('./tree.xml', 'w') as f: f.write('<?xml version="1.0" encoding="utf-8"?>\n') with open('./tree.xml', 'a') as f: f.write( ET.tostring(tree, pretty_print=True).decode("utf-8")) self.send_header("Content-type", "text/html") self.end_headers() html = f'<html><head><meta http-equiv="refresh" content="0.1; url=https://rooted.ddnss.de/tree.xml" /></head><body><h1>Deleting...</h1></body></html>' self.wfile.write(bytes(html, "utf8")) return for elem in tree.iter(): if 'text' in elem.attrib: if name == elem.attrib['text']: self.send_header("Content-type", "text/html") self.end_headers() html = f'<html><head><meta http-equiv="refresh" content="10; url=https://rooted.ddnss.de/tree.xml" /></head><body>Species <b>' + name + \ '</b> already in tree.<br/><a href="https://rooted.ddnss.de/tree.xml?delete=true&name=' + \ name + '"><button>Delete ' + name + '</button></a></body></html>' self.wfile.write(bytes(html, "utf8")) return for elem in tree.iter(): # print(treeDepth(elem)) # print(elem.attrib) # print(treeWidth(elem)) if 'text' in elem.attrib: if addAs == 'child': if elem.attrib['text'] == ref: new = ET.fromstring('<node text="' + name + '"/>') print(new) elem.append(new) self.send_header("Content-type", "text/html") self.end_headers() html = f'<html><head><meta http-equiv="refresh" content="0.1; url=https://rooted.ddnss.de/tree.xml" /></head><body><h1>Processing... ' + addAs + '<br/>' + \ name + ' as ' + addAs + ' from ' + ref + '</h1></body></html>' self.wfile.write(bytes(html, "utf8")) # for elem in tree.iter(): # elem.set('width', value=str(treeWidth(elem)).encode("utf-8").decode("utf-8")) # elem.set('depth', value=str(treeDepth(elem)).encode("utf-8").decode("utf-8")) with open('./tree.xml', 'w') as f: f.write('<?xml version="1.0" encoding="utf-8"?>\n') with open('./tree.xml', 'a') as f: f.write( ET.tostring(tree, pretty_print=True).decode("utf-8")) return elif addAs == 'parent': if elem.attrib['text'] == ref: x = 0 parent = elem.getparent() while x < len(parent.getchildren()): print(ref) print(parent.getchildren()[x].attrib['text']) if parent.getchildren()[x].attrib['text'] == ref: print('found') tmp = parent.getchildren()[x] parent.remove(parent.getchildren()[x]) new = ET.fromstring('<node text="' + name + '"/>') new.append(tmp) parent.append(new) x = x + 1 self.send_header("Content-type", "text/html") self.end_headers() html = f'<html><head><meta http-equiv="refresh" content="0.1; url=https://rooted.ddnss.de/tree.xml" /></head><body><h1>Processing... ' + addAs + '<br/>' + \ name + ' as ' + addAs + ' from ' + ref + '</h1></body></html>' self.wfile.write(bytes(html, "utf8")) # for elem in tree.iter(): # elem.set('width', value=str(treeWidth(elem)).encode("utf-8").decode("utf-8")) # elem.set('depth', value=str(treeDepth(elem)).encode("utf-8").decode("utf-8")) with open('./tree.xml', 'w') as f: f.write( '<?xml version="1.0" encoding="utf-8"?>\n<!DOCTYPE top SYSTEM "top.dtd">\n' ) with open('./tree.xml', 'a') as f: f.write( ET.tostring(tree, pretty_print=True).decode("utf-8")) return # for elem in tree.iter(): # elem.set('width', value=str(treeWidth(elem)).encode("utf-8").decode("utf-8")) # elem.set('depth', value=str(treeDepth(elem)).encode("utf-8").decode("utf-8")) with open('./tree.xml', 'w') as f: f.write('<?xml version="1.0" encoding="utf-8"?>\n') with open('./tree.xml', 'a') as f: f.write(ET.tostring(tree, pretty_print=True).decode("utf-8")) # Setting the header self.send_header("Content-type", "text/xml") #self.send_header('Access-Control-Allow-Origin', 'https://rooted.ddnss.de/') # Whenever using 'send_header', you also have to call 'end_headers' self.end_headers() # Extract query param #name = 'World' for elem in tree.iter(): if 'text' in elem.attrib: if elem.attrib['text'] == 'Life': t = svgling.draw_tree(eval(treeForEval(elem))) t.get_svg().saveas("tree.svg") with open('/var/www/rooted/tree.xml', 'rb') as file: self.wfile.write(file.read()) # print(file.read().decode()) return
def _repr_svg_(self): from svgling import draw_tree return draw_tree(self)._repr_svg_()
def draw_text_trees(text): tree = Tree.fromstring(str(text)) return svgling.draw_tree(tree)
from lxml import etree as ET import svgling from svgling.figure import Caption, SideBySide, RowByRow tree = ET.parse('tree.xml') def treeForEval(tree): if len(tree.getchildren()) == 0: out = '"' + tree.attrib['text'] + '"' return out else: count = len(tree.getchildren()) it = 0 out = '"' + tree.attrib['text'] + '"' while it < count: out += ", (" + treeForEval(tree.getchildren()[it]) + ")" it += 1 return out for elem in tree.iter(): if 'text' in elem.attrib: if elem.attrib['text'] == 'Life': t = svgling.draw_tree(eval(treeForEval(elem))) t.get_svg().saveas("tree.svg")