#!/usr/bin/env python """ Toki Pona to English Translation CGI Author: Sean B. Palmer, inamidst.com """ import cgitb; cgitb.enable() import sys, os, re, urllib import cgi, random, textwrap r_wordOrTag = re.compile(r'((?:[A-Za-z]+)|(?:<(?!\!)[^>]+>))') r_head = re.compile(r'(?ims)]*>') form = cgi.FieldStorage() form.__call__ = lambda s: form[s].value nimi = {} if os.path.isfile('./nimi.txt'): nimifn = './nimi.txt' else: nimifn = '../misc/nimi.txt' f = open(nimifn) for line in f: line = line.rstrip('\r\n') word, translations = line.split(': ', 1) translations = translations.split(', ') nimi[word] = translations f.close() def translateWord(word): w = word.lower() if nimi.has_key(w): return random.choice(nimi[w]) return {'li': 'is', 'la': "it's said", 'e': 'such'}.get(w) or word def translate(s): def translateMatch(m): wordOrTag = m.group(1) if wordOrTag.startswith('<'): return wordOrTag return translateWord(wordOrTag) return r_wordOrTag.sub(translateMatch, s) def translateURI(uri): u = urllib.urlopen(uri) translation = translate(u.read()) u.close() return translation def homepage(): print textwrap.dedent((""" Content-Type: text/html; charset=utf-8 TokiPana - Toki Pona to English Translation Service

Toki Pona to English Translation

URI:
Text:

More information: about this service, Python source.

Sean B. Palmer
""").lstrip('\n')) sys.exit() def serve(): if form.has_key('uri'): uri = form('uri') else: uri = False if form.has_key('text'): text = form('text') else: text = False if uri: assert ':' in uri u = urllib.urlopen(uri) info = u.info() text = u.read() u.close() mediatype = info.get('Content-Type') or 'text/html; charset=utf-8' if mediatype.startswith('text/html'): base = '\n\n' % uri m = r_head.search(text) if m: endpos = m.end() text = text[:endpos] + base + text[endpos:] else: text = base + text elif text: mediatype = 'text/plain; charset=utf-8' else: homepage() print "Content-Type: %s" % mediatype print result = translate(text) if text: def wrap(line): return '\n'.join(textwrap.wrap(line, width=79)) result = '\n'.join(wrap(line) for line in result.splitlines()) print result def main(): fn = sys.argv[1] print translateURI(fn) if __name__=="__main__": if os.environ.has_key('SCRIPT_NAME'): serve() else: main()