posted by SteveHowell


This is not my favorite code sample of all time, but it was handy, and there's a story behind it. There's a great tool called graphviz that can produce Visio-like graphs from simple text descriptions of directed graphs. Graphviz can also be configured to produce a text description of the bitmap that it would be draw, and another cool tool called webdot robustly builds an HTML image map from the outputs of graphviz, so that you could click on nodes of a graph and see other relevant HTML pages. One day I needed webdot on Windows, but their web site was down. No worries, I just reinvented webdot in Python. The code follows:


# Poor man's webdot.
from os import path
from os import system
import string

print 'Processing...'
system('dot.exe -Tpng -o tasks.png tasks.dot')
system('dot.exe -Tplain -o tasks.txt tasks.dot')

class WebDot:
    def __init__(self):
        outfn = 'c:/program files/apache group/apache/htdocs/tasks.htm'
        self.out = open(outfn, 'w')
        self.out_start()
        f = open('tasks.txt', 'r')
        lines = f.readlines()
        for line in lines:
            words = string.split(line)
            if words[0] == 'graph':
                self.graph(words)
            elif words[0] == 'node':
                self.nodes(words)
        self.out_end()

    def out_start(self):
        self.out.write("""
<h1>Here are our tasks:</h1>
<map>
<map name="tasks">
""");

    def out_end(self):
        self.out.write("""
</map>
<img src="c:\\mydocuments\\computer\\python\\webdot\\tasks.png" usemap="#tasks">
""");

    def graph(self, words):
        self.width = int(96 * float(words[2]))
        self.height = int(96 * float(words[3]))
        
    def nodes(self, words):
        name = words[1]
        (x, y, width, height) = [int(float(w) * 96) for w in words[2:6]]
        y = self.height - y
        x1 = x - width / 2
        x2 = x + width /2 
        y1 = y - height / 2
        y2 = y + height / 2
        href = 'http://127.0.0.1/cgi-bin/FolderPiki.py/webdot:%s' % name
        areatag = '<area shape="rectangle" coords="%d,%d,%d,%d" href="%s">'+"\n"
        self.out.write(areatag % (x1, y1, x2, y2, href))

WebDot()

WebDotReinvented (last edited 2008-03-04 08:33:12 by localhost)