import os, cStringIO from model import * from mtypes import * c_dbid = Concept() c_file = Concept() c_image = Concept() pathname = Morphism(c_string, c_file, "A string as the path name of a file.") strcontent= Morphism(c_string, c_file, "A string with the whole content of a file.") dbimage = Morphism(c_dbid, c_image, "An integer identifier for an image in the database.") jpegimage = Morphism(c_file, c_image, "A file containing a JPEG image.") ppmimage = Morphism(c_file, c_image, "A file containing a PPM image.") show = Operation([c_image, c_none], "Show the given image.") mul = Operation([c_image, c_image, c_image], "Mask the given image (binary 'and' with mask).") ### implementation ### def show_xv(src): os.system('xv "%s"' % src) show[pathname+jpegimage, 0] = show_xv # or = Operation([c_string, c_none], implement=show_xv) def mul_and(fn1, fn2): return os.popen('./and "%s" "%s"' % (fn1, fn2), 'r') mul[pathname+ppmimage, pathname+ppmimage, ppmimage] = mul_and def encode_jpg(src): return os.popen('cjpeg "%s"' % src, 'r') c_image.eq[pathname+ppmimage, jpegimage] = encode_jpg def decode_jpg(src): return os.popen('djpeg "%s"' % src, 'r') c_image.eq[pathname+jpegimage, ppmimage] = decode_jpg def binary_open(fn): return open(fn, 'rb') c_file.eq[pathname, 0] = binary_open ## Python 2.3 only ##def make_temp_file(f, hack={}): ## if f in hack: ## return hack[f] ## import tempfile, atexit ## fd, filename = tempfile.mkstemp() ## def try_unlink(): ## try: ## os.unlink(filename) ## except: ## pass ## atexit.register(try_unlink) ## g = os.fdopen(fd, 'wb') ## while True: ## buf = f.read(4096) ## if not buf: break ## g.write(buf) ## g.close() ## f.close() ## hack[f] = filename ## return filename def make_temp_file(f, hack={}): if f in hack: return hack[f] import tempfile, atexit filename = tempfile.mktemp() def try_unlink(): try: os.unlink(filename) except: pass atexit.register(try_unlink) g = open(filename, 'wb') while True: buf = f.read(4096) if not buf: break g.write(buf) g.close() f.close() hack[f] = filename return filename c_file.eq[0, pathname] = make_temp_file c_file.eq[strcontent, 0] = cStringIO.StringIO def load_file(f): return f.read() c_file.eq[0, strcontent] = load_file def db_load(n): if os.curdir not in sys.path: sys.path.insert(0, os.curdir) cwd = os.getcwd() try: os.chdir('../db') import mytest return mytest.load(n, djpeg=None) finally: os.chdir(cwd) c_image.eq[dbimage, strcontent+jpegimage] = db_load